source: trunk/contactcenter/inc/class.ui_data.inc.php @ 1517

Revision 1517, 110.8 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #684 - Implementada a aba corporativa com a opção genérica no admin

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2  /***************************************************************************\
3  * eGroupWare - Contacts Center                                              *
4  * http://www.egroupware.org                                                 *
5  * Written by:                                                               *
6  *  - Raphael Derosso Pereira <raphaelpereira@users.sourceforge.net>         *
7  *  - Jonas Goes <jqhcb@users.sourceforge.net>                               *
8  *  sponsored by Thyamad - http://www.thyamad.com                            *
9  * ------------------------------------------------------------------------- *
10  *  This program is free software; you can redistribute it and/or modify it  *
11  *  under the terms of the GNU General Public License as published by the    *
12  *  Free Software Foundation; either version 2 of the License, or (at your   *
13  *  option) any later version.                                               *
14  \***************************************************************************/
15
16       
17        class ui_data
18        {
19                var $public_functions = array(
20                        'data_manager' => true,
21                );
22               
23                var $bo;
24                var $typeContact;
25               
26                var $page_info = array(
27                        'n_cards'          => 20,
28                        'n_pages'          => false,
29                        'actual_letter'    => 'A',
30                        'actual_page'      => 1,
31                        'actual_entries'   => false,
32                        'changed'          => false,
33                        'catalogs'         => false,
34                        'actual_catalog'   => false
35                );
36               
37                /*!
38               
39                        @function ui_data
40                        @abstract The constructor. Sets the initial parameters and loads
41                                the data saved in the session
42                        @author Raphael Derosso Pereira
43                       
44                */
45                function ui_data()
46                {
47                        $temp = $GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter');
48                        $temp2 = $GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter');
49                       
50                        $this->bo = CreateObject('contactcenter.bo_contactcenter');
51                       
52                        if ($temp)
53                        {
54                                $this->page_info = $temp;
55                        }
56
57                        if ($temp2)
58                        {
59                                $this->all_entries = $temp2;
60                        }
61                       
62                        if (!$this->page_info['actual_catalog'])
63                        {
64                                $catalogs = $this->bo->get_catalog_tree();
65                                $this->page_info['actual_catalog'] = $catalogs[0];
66                        }
67                       
68                        $this->page_info['actual_catalog'] =& $this->bo->set_catalog($this->page_info['actual_catalog']);                       
69                       
70                        if($this->page_info['actual_catalog']['class'] == 'bo_group_manager')
71                                $this -> typeContact = 'groups';
72                        else if($this->page_info['actual_catalog']['class'] == 'bo_shared_group_manager')
73                                $this -> typeContact = 'shared_groups';
74                        else if($this->page_info['actual_catalog']['class'] == 'bo_shared_people_manager')
75                                $this -> typeContact = 'shared_contacts';
76                        else
77                                $this -> typeContact = 'contacts';
78                }
79
80                /*!
81               
82                        @function index
83                        @abstract Builds the Main Page
84                        @author Raphael Derosso Pereira
85                        @author Jonas Goes
86                       
87                */             
88                function index()
89                {       
90                        if(!@is_object($GLOBALS['phpgw']->js))
91                        {
92                                $GLOBALS['phpgw']->js = CreateObject('phpgwapi.javascript');
93                        }
94                        $GLOBALS['phpgw']->js->validate_file('venus','table');
95                        $GLOBALS['phpgw']->js->validate_file('venus','shapes');
96                        $GLOBALS['phpgw']->js->validate_file('venus','jsStructUtil');
97                        $GLOBALS['phpgw']->js->validate_file('venus','cssUtil');
98                       
99//                      $GLOBALS['phpgw']->js->set_onload('setTimeout(\'updateCards()\',1000)');
100                        $GLOBALS['phpgw']->common->phpgw_header();
101                       
102                        $GLOBALS['phpgw']->template->set_file(array('index' => 'index.tpl'));
103                        $GLOBALS['phpgw']->template->set_var('cc_root_dir', $GLOBALS['phpgw_info']['server']['webserver_url'].'/contactcenter/');
104                       
105                        /* Quick Add */
106                        $GLOBALS['phpgw']->template->set_var('cc_qa_alias',lang('Alias').':');
107                        $GLOBALS['phpgw']->template->set_var('cc_qa_given_names',lang('Given Names').':');
108                        $GLOBALS['phpgw']->template->set_var('cc_qa_family_names',lang('Family Names').':');
109                        $GLOBALS['phpgw']->template->set_var('cc_qa_phone',lang('Phone').':');
110                        $GLOBALS['phpgw']->template->set_var('cc_qa_email',lang('Email').':');
111                        $GLOBALS['phpgw']->template->set_var('cc_qa_save',lang('Save'));
112                        $GLOBALS['phpgw']->template->set_var('cc_qa_clear',lang('Clear'));
113                        $GLOBALS['phpgw']->template->set_var('cc_qa_close',lang('Close'));
114                        /* End Quick Add */
115                       
116                        $cc_css_file = $GLOBALS['phpgw_info']['server']['webserver_url'].'/contactcenter/styles/cc.css';
117                        $cc_card_image_file = $GLOBALS['phpgw_info']['server']['webserver_url'].'/contactcenter/templates/default/images/card.png';
118                        $GLOBALS['phpgw']->template->set_var('cc_css',$cc_css_file);
119                        $GLOBALS['phpgw']->template->set_var('cc_dtree_css', $cc_dtree_file);
120                        $GLOBALS['phpgw']->template->set_var('cc_card_image',$cc_card_image_file);
121                       
122                        $GLOBALS['phpgw']->template->set_var('cc_personal',lang('Personal'));
123                       
124                        $GLOBALS['phpgw']->template->set_var('cc_full_add_button',lang('Full Add'));
125                        $GLOBALS['phpgw']->template->set_var('cc_full_add_button_sh',lang('Full Add Shared'));
126                        $GLOBALS['phpgw']->template->set_var('cc_reset',lang('Reset'));
127                       
128                        $GLOBALS['phpgw']->template->set_var('cc_personal_data',lang('Personal Data'));
129                        $GLOBALS['phpgw']->template->set_var('cc_addresses',lang('Addresses'));
130                        $GLOBALS['phpgw']->template->set_var('cc_connections',lang('Connections'));
131                        $GLOBALS['phpgw']->template->set_var('cc_relations',lang('Relations'));
132
133                        $GLOBALS['phpgw']->template->set_var('cc_quick_add',lang('Quick Add'));
134                        $GLOBALS['phpgw']->template->set_var('cc_catalogs',lang('Catalogues'));
135                        $GLOBALS['phpgw']->template->set_var('cc_group_add',lang('Group Add'));
136                       
137                        /* Panel */
138                        $GLOBALS['phpgw']->template->set_var('cc_panel_new',lang('New').'...');
139                        $GLOBALS['phpgw']->template->set_var('cc_panel_search',lang('Search').'...');
140                        $GLOBALS['phpgw']->template->set_var('cc_panel_table',lang('Table View'));
141                        $GLOBALS['phpgw']->template->set_var('cc_panel_cards',lang('Cards View'));
142                        $GLOBALS['phpgw']->template->set_var('cc_btn_import_export', lang('Import/Export'));
143                        $GLOBALS['phpgw']->template->set_var('cc_btn_new', lang("New..."));
144                       
145                        $GLOBALS['phpgw']->template->set_var('cc_panel_search_found',lang('Showing found entries'));
146                        $GLOBALS['phpgw']->template->set_var('cc_panel_first_page',lang('First Page'));
147                        $GLOBALS['phpgw']->template->set_var('cc_panel_previous_page',lang('Previous Page'));
148                        $GLOBALS['phpgw']->template->set_var('cc_panel_next_page',lang('Next Page'));
149                        $GLOBALS['phpgw']->template->set_var('cc_panel_last_page',lang('Last Page'));
150                        $GLOBALS['phpgw']->template->set_var('cc_all',lang('all'));
151                        /* End Panel */
152                       
153                        /* Messages */
154                        $GLOBALS['phpgw']->template->set_var('cc_msg_not_allowed',lang('Not Allowed'));
155                        $GLOBALS['phpgw']->template->set_var('cc_msg_unavailable',lang('Unavailable function'));                       
156                        $GLOBALS['phpgw']->template->set_var('cc_msg_no_cards',lang('No Cards'));
157                        $GLOBALS['phpgw']->template->set_var('cc_msg_err_no_room',lang('No Room for Cards! Increase your browser area.'));
158                        $GLOBALS['phpgw']->template->set_var('cc_msg_card_new',lang('New from same Company'));
159                        $GLOBALS['phpgw']->template->set_var('cc_msg_card_edit',lang('Edit Contact'));
160                        $GLOBALS['phpgw']->template->set_var('cc_msg_card_remove',lang('Remove Contact'));
161                        $GLOBALS['phpgw']->template->set_var('cc_send_mail',lang('Send Mail'));
162                        $GLOBALS['phpgw']->template->set_var('cc_msg_group_edit',lang('Edit Group'));
163                        $GLOBALS['phpgw']->template->set_var('cc_msg_group_remove',lang('Remove Group'));
164                        $GLOBALS['phpgw']->template->set_var('cc_msg_group_remove_confirm',lang('Confirm Removal of this Group?'));
165                        $GLOBALS['phpgw']->template->set_var('cc_msg_card_remove_confirm',lang('Confirm Removal of this Contact?'));
166                        $GLOBALS['phpgw']->template->set_var('cc_participants',lang('Participants'));
167                        $GLOBALS['phpgw']->template->set_var('cc_empty',lang('Empty'));
168                        /* End Messages */
169                       
170                        $GLOBALS['phpgw']->template->set_var('cc_results',lang('Results'));
171                        $GLOBALS['phpgw']->template->set_var('cc_is_my',lang('Is My'));
172                        $GLOBALS['phpgw']->template->set_var('cc_ie_personal',lang('Import/Export pesonal contacts'));
173                        $GLOBALS['phpgw']->template->set_var('cc_btn_search',lang('Search'));
174                        $GLOBALS['phpgw']->template->set_var('cc_add_relation',lang('Add Relation'));
175                        $GLOBALS['phpgw']->template->set_var('cc_del_relation',lang('Remove Selected Relations'));                     
176                        $GLOBALS['phpgw']->template->set_var('cc_msg_group',lang('Group'));
177                        $GLOBALS['phpgw']->template->set_var('cc_msg_contact_full',lang('Contact [Full]'));
178                        $GLOBALS['phpgw']->template->set_var('cc_msg_contact_sh',lang('Contact [Shared]'));
179                        $GLOBALS['phpgw']->template->set_var('cc_msg_contact_qa',lang('Contact [Quick Add]'));
180                        $GLOBALS['phpgw']->template->set_var('cc_contact_title',lang('Contact Center').' - '.lang('Contacts'));
181                        $GLOBALS['phpgw']->template->set_var('cc_window_views_title',lang('Contact Center').' - '.lang('Views'));
182                        $GLOBALS['phpgw']->template->set_var('phpgw_img_dir', $GLOBALS['phpgw_info']['server']['webserver_url'] . '/phpgwapi/images');
183
184                        $GLOBALS['phpgw']->template->set_var('cc_msg_import_contacts', lang('Import Contacts'));
185                        $GLOBALS['phpgw']->template->set_var('cc_msg_export_contacts', lang('Export Contacts'));
186                        $GLOBALS['phpgw']->template->set_var('cc_msg_expresso_info_csv', lang('The Expresso supports the contacts importation in the CSV file format.'));
187                        $GLOBALS['phpgw']->template->set_var('cc_msg_choose_file_type', lang('Select the file type'));
188                        $GLOBALS['phpgw']->template->set_var('cc_msg_outlook_express', lang('Outlook Express'));
189                        $GLOBALS['phpgw']->template->set_var('cc_msg_outlook2k', lang('Outlook 2000'));
190                        $GLOBALS['phpgw']->template->set_var('cc_msg_expresso_default', lang('Expresso (default)'));
191                        $GLOBALS['phpgw']->template->set_var('cc_msg_choose_contacts_file', lang('Select the file that contains the contacts to be imported:'));
192                        $GLOBALS['phpgw']->template->set_var('cc_msg_close_win', lang('Close'));
193                        $GLOBALS['phpgw']->template->set_var('cc_msg_close', lang('Close'));
194                        $GLOBALS['phpgw']->template->set_var('cc_msg_ie_personal', lang('Import / Export personal Contacts'));
195                        $GLOBALS['phpgw']->template->set_var('cc_msg_import_fail', lang('The importation has failed. Verify the file format.'));
196                        $GLOBALS['phpgw']->template->set_var('cc_msg_importing_contacts', lang('Importing Contacts...'));
197                        $GLOBALS['phpgw']->template->set_var('cc_msg_import_finished', lang('The importation has finished.'));
198                        $GLOBALS['phpgw']->template->set_var('cc_msg_new', lang(' new'));
199                        $GLOBALS['phpgw']->template->set_var('cc_msg_failure', lang(' failed'));
200                        $GLOBALS['phpgw']->template->set_var('cc_msg_exists', lang(' were existent'));
201                        $GLOBALS['phpgw']->template->set_var('cc_msg_show_more_info', lang('show more info'));
202                        $GLOBALS['phpgw']->template->set_var('cc_msg_clean', lang('Clean'));
203                        $GLOBALS['phpgw']->template->set_var('cc_msg_invalid_csv', lang('Select a valid CSV file to import your contacts'));
204                        $GLOBALS['phpgw']->template->set_var('cc_msg_export_csv', lang('Select the format type that you want to export your contacts'));
205                        $GLOBALS['phpgw']->template->set_var('cc_msg_automatic', lang('Automatic'));
206                        $GLOBALS['phpgw']->template->set_var('cc_msg_export_error', lang('An error has occurred while the exportation.'));
207                        $GLOBALS['phpgw']->template->set_var('cc_msg_new_email', lang('New Email'));
208                        $GLOBALS['phpgw']->template->set_var('cc_msg_main', lang('Main'));
209                        $GLOBALS['phpgw']->template->set_var('cc_msg_alternative', lang('Alternative'));
210                        $GLOBALS['phpgw']->template->set_var('cc_msg_select_email', lang('Select E-Mail'));
211                        $GLOBALS['phpgw']->template->set_var('cc_msg_new_phone', lang('New Telephone'));
212                        $GLOBALS['phpgw']->template->set_var('cc_msg_home', lang('Home'));
213                        $GLOBALS['phpgw']->template->set_var('cc_msg_cellphone', lang('Cellphone'));
214                        $GLOBALS['phpgw']->template->set_var('cc_msg_corporative_cellphone', lang('Corporative Cellphone'));
215                        $GLOBALS['phpgw']->template->set_var('cc_msg_corporative_fax', lang('Corporative Fax'));
216                        $GLOBALS['phpgw']->template->set_var('cc_msg_corporative_pager', lang('Corporative Pager'));                   
217                        $GLOBALS['phpgw']->template->set_var('cc_msg_work', lang('Work'));
218                        $GLOBALS['phpgw']->template->set_var('cc_msg_fax', lang('Fax'));
219                        $GLOBALS['phpgw']->template->set_var('cc_msg_pager', lang('Pager'));
220                        $GLOBALS['phpgw']->template->set_var('cc_msg_choose_phone', lang('Select the telephone'));
221                        $GLOBALS['phpgw']->template->set_var('cc_msg_warn_firefox', lang('Warning: Too old version of Firefox'));
222                        $GLOBALS['phpgw']->template->set_var('cc_msg_firefox_half1', lang('For this application work correctly</u>'));
223                        $GLOBALS['phpgw']->template->set_var('cc_msg_firefox_half2', lang('it\'s necessary to update your Firefox Browser for a new version (version > 1.5) Install now clicking in the link bellow, or if you want to update it later'));
224                        $GLOBALS['phpgw']->template->set_var('cc_msg_click_close', lang('click Close'));
225                        $GLOBALS['phpgw']->template->set_var('cc_msg_install_now', lang('Install Now'));
226                        $GLOBALS['phpgw']->template->set_var('cc_msg_install_new_firefox', lang('Install a new Firefox version'));
227                        $GLOBALS['phpgw']->template->set_var('cc_msg_moz_thunderbird', lang('Export as Mozilla Thunderbird CSV.'));
228                        $GLOBALS['phpgw']->template->set_var('cc_msg_outlook_express_pt', lang('Export as Outlook Express (Portuguese) CSV.'));
229                        $GLOBALS['phpgw']->template->set_var('cc_msg_outlook_express_en', lang('Export as Outlook Express (English) CSV.'));
230                        $GLOBALS['phpgw']->template->set_var('cc_msg_outlook_2k_pt', lang('Export as Outlook 2000 (Portuguese) CSV.'));
231                        $GLOBALS['phpgw']->template->set_var('cc_msg_outlook_2k_en', lang('Export as Outlook 2000 (English) CSV.'));
232                        $GLOBALS['phpgw']->template->set_var('cc_msg_expresso_default_csv', lang('Export as Expresso (Default) CSV.'));
233                        $GLOBALS['phpgw']->template->set_var('cc_msg_copy_to_catalog', lang('Copy to personal catalog.'));
234                        $GLOBALS['phpgw']->template->set_var('cc_msg_add_contact_to_group', lang('You did not add any contact for this group.'));
235                        $GLOBALS['phpgw']->template->set_var('cc_msg_fill_field_name', lang('Fill the field Full Name'));
236                       
237                        if($GLOBALS['phpgw_info']['server']['personal_contact_type']=='True'){
238                                $GLOBALS['phpgw']->template->set_var('cc_contact_type', 'advanced');
239                        }else{
240                                $GLOBALS['phpgw']->template->set_var('cc_contact_type', 'default');
241                        }
242                        $GLOBALS['phpgw']->template->parse('out','index');
243                       
244                        $api = CreateObject('contactcenter.ui_api');
245                        $main = $api->get_full_add();
246                        $main .= $api->get_search_obj();
247                        $main .= $api->get_quick_add_plugin();
248                        $main .= $api->get_add_group();
249                        $main .= $GLOBALS['phpgw']->template->get_var('out');
250
251                        echo $main;
252                }
253
254               
255                /*!
256               
257                        @function data_manager
258                        @abstract Calls the right method and passes to it the right
259                                parameters
260                        @author Raphael Derosso Pereira
261               
262                */
263                function data_manager()
264                {
265                        switch($_GET['method'])
266                        {
267                                /* Cards Methods */
268                                case 'set_n_cards':
269                                        return $this->set_n_cards((int)$_GET['ncards']);
270                                       
271                                case 'get_cards_data':                                 
272                                        $ids = false;
273                                        // To support ldap catalogs using accentuation
274                                        if ($_POST['letter'] == 'search' && isset($_POST['data']))
275                                        {
276                                                $ids = utf8_decode($this->search($_POST['data']));
277                                        }
278                                       
279                                        if(isset($_SESSION['ids']))
280                                                $ids = $_SESSION['ids'];
281                                       
282                                        return $this->get_cards_data($_POST['letter'], $_POST['page'], $ids);                                           
283                                case 'get_cards_data_get':
284                                        return $this->get_cards_data($_GET['letter'], $_GET['page'], unserialize(str_replace('\\"','"',$_GET['ids'])));
285
286
287                                case 'get_photo':
288                                        return $this->get_photo($_GET['id']);
289
290                                case 'get_visible_all_ldap':
291                                        echo $this->get_visible_all_ldap();
292                                        return;
293                                       
294                                /* Catalog Methods */
295                                case 'set_catalog':
296                                        return $this->set_catalog($_GET['catalog']);
297                                       
298                                case 'get_catalog_tree':
299                                        echo serialize($this->get_catalog_tree($_GET['level']));
300                                        return;
301
302                                case 'get_actual_catalog':
303                                        echo serialize($this->get_actual_catalog());
304                                        return;
305
306                                case 'get_catalog_participants_list':
307                                        echo serialize($this->get_catalog_participants_list($_POST['id']));
308                                        return;
309                               
310                                case 'get_catalog_participants_group':
311                                        echo serialize($this->get_catalog_participants_group($_POST['id']));
312                                        return;
313
314                                case 'get_catalog_add_contact':
315                                        // To support ldap catalogs with accentuation
316                                        echo serialize($this->get_catalog_add_contact(utf8_decode($_POST['id'])));
317                                        return;
318                                       
319                                /* Full Add Methods */
320                                case 'get_full_data':
321                                        return $this->get_full_data($_GET['id'],$_GET['catalog']);
322                               
323                                case 'get_group':
324                                        return $this->get_group_data($_GET['id'],isset($_GET['shared_from'])?$_GET['shared_from']:null);
325                                       
326                                case 'get_contact_full_add_const':
327                                        return $this->get_contact_full_add_const();
328
329                                case 'post_full_add':
330                                        return $this->post_full_add();
331
332                                case 'post_full_add_shared' :
333                                        return $this->post_full_add_shared();
334
335                                case 'post_photo':
336                                        return $this->post_photo((int) $_GET['id'] ? (int) $_GET['id'] : '_new_');
337
338                                case 'get_states':
339                                        return $this->get_states($_GET['country']);
340                                       
341                                case 'get_cities':
342                                        return $this->get_cities($_GET['country'], $_GET['state'] ? $_GET['state'] : null);
343                                       
344                                       
345                                /* Other Methods */
346                                case 'quick_add':                                                                                                                       
347                                        return $this->quick_add($_POST['add']);
348                               
349                                case 'add_group':                                                                                                                       
350                                        return $this->add_group($_POST['add']);
351                                                                       
352                                case 'remove_entry':
353                                        return $this->remove_entry((int)$_GET['remove']);
354                               
355                                case 'remove_all_entries':
356                                        return $this->remove_all_entries();
357
358                                case 'remove_group':
359                                                                               
360                                        return $this->remove_group((int)$_GET['remove']);                                       
361
362                                case 'search':
363                                        $ids = false;
364                                        $ids = $this->search($_GET['data']);
365                                        return $this->get_cards_data('search', '1', $ids);
366
367                                case 'email_win':
368                                        $GLOBALS['phpgw']->common->phpgw_header();
369                                        $api = CreateObject('contactcenter.ui_api');
370                                        $win = $api->get_email_win();
371                                        $win .= $api->get_quick_add_plugin();
372                                        $win .= '<input id="QAbutton" type="button" value="QuickAdd" />'
373                                                .'<br><input type="button" value="EmailWin" onclick="ccEmailWin.open()" />'
374                                                .'<script type="text/javascript">'
375                                                .'      ccQuickAdd.associateAsButton(Element("QAbutton"));'
376                                                .'</script>';
377                                        echo $win;
378                                        return;
379
380                                /* Information Gathering */
381                                case 'get_multiple_entries':
382                                        echo serialize($this->get_multiple_entries(str_replace('\\"','"',$_POST['data'])));
383                                        return;
384
385                                case 'get_all_entries':
386                                        echo serialize($this->get_all_entries(str_replace('\\"','"',$_POST['data'])));
387                                        return;
388
389                                case 'import_contacts':
390                                        return $this->import_contacts($_GET['typeImport']);
391
392                                case 'export_contacts':
393                                        return $this->export_contacts($_POST['typeExport']);
394
395                        }
396                }
397
398                /*!
399               
400                        @function set_n_cards
401                        @abstract Informs the class the number of cards the page can show
402                        @author Raphael Derosso Pereira
403                       
404                        @param integer $n_cards The number of cards
405                       
406                */
407                function set_n_cards($n_cards)
408                {
409                        if (is_int($n_cards))
410                        {
411                                $this->page_info['n_cards'] = $n_cards;
412                                echo 1;
413                        }
414                       
415                        $this->save_session();
416                }
417                               
418                /*!
419               
420                        @function set_catalog
421                        @abstract Sets the current catalog selected by the user
422                        @author Raphael Derosso Pereira
423                       
424                        @param string $id_catalog The sequence of IDs to reach the catalog
425                                separated by commas
426               
427                */
428                function set_catalog($id_catalog)
429                {
430                        $id_catalog = str_replace('\\"', '"', $id_catalog);
431                        $temp =& $this->bo->set_catalog($id_catalog);
432                       
433                        if ($temp)
434                        {
435                                $this->page_info['changed'] = true;
436                                $this->page_info['actual_entries'] = false;
437                                $this->page_info['actual_catalog'] =& $temp;
438                                $this->save_session();
439                               
440                                $catalog_info = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
441                               
442                                if ($catalog_info['class'] === 'bo_global_ldap_catalog' ||
443                                    $catalog_info['class'] === 'bo_catalog_group_catalog')
444                                {
445                                        $perms = 1;
446                                }
447                                else
448                                {
449                                        $perms = 15;
450                                }
451                               
452                                echo serialize(array(
453                                        'status' => 'ok',
454                                        'perms'  => $perms
455                                ));
456
457                                return;
458                        }
459                       
460                        echo serialize(array(
461                                'status' => 'ok',
462                                'perms'  => 0
463                        ));
464                }
465               
466               
467                /*!
468               
469                        @function get_catalog_tree
470                        @abstract Returns the JS serialized array to used as the tree
471                                level
472                        @author Raphael Derosso Pereira
473            @author Mário César Kolling (error messages and timeout)
474                       
475                        @param (string) $level The level to be taken
476               
477                */
478                function get_catalog_tree($level)
479                {
480                        if ($level === '0')
481                        {
482                                $folderImageDir = $GLOBALS['phpgw_info']['server']['webserver_url'] . '/phpgwapi/dftree/images/';
483
484                                $parent = '0';
485                               
486                                if (!($tree = $this->bo->get_catalog_tree($level)))
487                                {
488                                        return array(
489                                                'msg'    => lang('Couldn\'t get the Catalogue Tree. Please contact the Administrator.'),
490                                                'status' => 'fatal'
491                                        );
492                                }
493                        }
494                        else
495                        {
496                                $last_dot = strrpos($level,'.');
497                                $parent = substr($level, 0, $last_dot);
498                                $child = substr($level, $last_dot+1, strlen($level));
499                                if (!($tree[$child] = $this->bo->get_catalog_tree($level)))
500                                {
501                                        return array(
502                                                'msg'    => lang('Couldn\'t get the Catalogue Tree. Please contact the Administrator.'),
503                                                'status' => 'fatal'
504                                        );
505                                }
506                                // Deals with timeout and returns the generated message to the browser
507                                else if (!empty($tree[$child]['timeout']) && !empty($tree[$child]['msg']))
508                                {
509                                        $tmp = array(
510                                                'msg'    => $tree[$child]['msg'],
511                                                'status' => 'fatal'
512                                        );
513                                        unset($tree[$child]);
514                                        return $tmp;
515                                }
516                        }
517                       
518                        $folderImageDir = $GLOBALS['phpgw']->common->image('contactcenter','globalcatalog-mini.png');
519                        $folderImageDir = substr($folderImageDir, 0, strpos($folderImageDir, 'globalcatalog-mini.png'));
520                       
521                        // Deals with error messages from the server and returns them to the browser
522                        if ($tree['msg'])
523                        {
524                                $msg = $tree['msg'];
525                                unset($tree['msg']);
526                        }
527
528                        $tree_js = $this->convert_tree($tree, $folderImageDir, $parent);
529
530                        // Return status = ok, or else return generated message to the browser
531                        if (!$msg)
532                        {
533                                return array(
534                                        'data' => $tree_js,
535                                        'msg'  => lang('Catalog Tree Successfully taken!'),
536                                        'status' => 'ok'
537                                );
538                        }
539                        else
540                        {
541                                return array(
542                                        'data' => $tree_js,
543                                        'msg'  => $msg,
544                                        'status' => 'error'
545                                );
546                        }
547                }
548               
549                /*!
550               
551                        @function get_actual_catalog
552                        @abstract Returns the actual selected Catalog
553                        @author Raphael Derosso Pereira
554
555                */
556                function get_actual_catalog()
557                {                       
558                        $level = $this->bo->get_level_by_branch($this->bo->get_actual_catalog(), $this->bo->tree['branches'], '0');
559                       
560                        if ($level)
561                        {
562                                return array(
563                                        'status' => 'ok',
564                                        'data'   => $level
565                                );
566                        }
567
568                        return array(
569                                'status' => 'fatal',
570                                'msg'    => lang('Couldn\'t get the actual catalog.'),
571                        );
572                }
573               
574                /*!
575               
576                        @function get_cards_data
577                        @abstract Returns the information that is placed on the cards
578                        @author Raphael Derosso Pereira
579                       
580                        @param string $letter The first letter to be searched
581                        @param (int)  $page The page to be taken
582                        @param (str)  $ids The ids to be taken in case of search
583
584                        TODO: This function is not well done. It must be rewritten
585                                using the new array 'msg','status','data' schema.
586                */
587                function get_cards_data($letter, $page, $ids)
588                {
589                        if( $ids )
590                                $_SESSION['ids'] = $ids;                   
591
592                        // It's an external catalog?
593                        $external = $this->bo->is_external($this->page_info['actual_catalog']);
594                        //echo $page."\n";
595                        if ($letter !== 'search' and ($letter != $this->page_info['actual_letter'] or
596                            ($letter == $this->page_info['actual_letter'] and $page == $this->page_info['actual_page']) or
597                            $this->page_info['changed']))
598                        {
599                                unset($ids);
600                                $this->page_info['changed'] = false;
601                                switch ($this->page_info['actual_catalog']['class'])
602                                {
603                                        case 'bo_shared_people_manager':
604                                        case 'bo_people_catalog':
605                                                $field_name = 'id_contact';
606                                                if ($letter !== 'number')
607                                                {
608                                                        $find_restric[0] = array(
609                                                                0 => array(
610                                                                        'field' => 'contact.names_ordered',
611                                                                        'type'  => 'iLIKE',
612                                                                        'value' => $letter !== 'all' ? $letter.'%' : '%'
613                                                                )                                                               
614                                                        );
615
616                                                        //Tratamento de permissão de escrita no compartilhamento de catalogo
617                                                        $so_contact = CreateObject('contactcenter.so_contact',  $GLOBALS['phpgw_info']['user']['account_id']);
618                                                        $relacionados = $so_contact->get_relations();
619                                                       
620                                                        $perms_relacao = array();                               
621
622                                                        foreach($relacionados as $uid_relacionado => $tipo_relacionamento) {
623                                                                $aclTemp = CreateObject("phpgwapi.acl",$uid_relacionado);
624                                                                $aclTemp->read();
625                                                                $perms_relacao[$uid_relacionado] = $aclTemp->get_specific_rights($GLOBALS['phpgw_info']['user']['account_id'],'contactcenter'); //Preciso verificar as permissões que o contato relacionado deu para o atual
626                                                        }
627
628                                                        $validos = array();
629                                                        $count = 0;
630                                                        foreach($perms_relacao as $uid_relacionado => $val){
631                                                                if ($perms_relacao[$uid_relacionado]&2)
632                                                                {
633                                                                        $validos[$uid_relacionado] = $perms_relacao[$uid_relacionado];
634                                                                        $count++;
635                                                                }
636                                                        }
637                                                        $prop_names = array();
638                                                        if($validos) {
639                                                                $filtro = "(|";
640                                                                foreach($validos as $i => $prop) {
641                                                                        $filtro .= "(uidNumber=".$i.")";
642                                                                }
643                                                                $filtro .= ")";
644
645                                                                if(!$this->bo->catalog->src_info) {
646                                                                        $ldaps = CreateObject('contactcenter.bo_ldap_manager');
647                                                                        $this->bo->catalog->src_info = $ldaps->srcs[1];
648                                                                }
649                                                                $s = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], false);
650                                                                $n=$this->bo->catalog->src_info['dn'];
651                                                                $apenasThese = array("cn","uidnumber","uid");
652                                                                $r = ldap_search($s,$n, $filtro,$apenasThese);                                       
653                                                                $infos = ldap_get_entries($s, $r);
654                                                                ldap_close($s);                                                                       
655                                                                for($z = 0; $z < $infos['count']; $z++) {
656                                                                        $prop_names[$infos[$z]['uidnumber'][0]] = array("cn" => $infos[$z]['cn'][0], "uid" => $infos[$z]['uid'][0]);
657                                                                }
658                                                        }
659                                                        //--------------------------------------------------------------------------------
660                                                        if($this->page_info['actual_catalog']['class'] == 'bo_people_catalog')
661                                                        {
662                                                                $find_restric[0][1] = array(
663                                                                                'field' => 'contact.id_owner',
664                                                                                'type'  => '=',
665                                                                                'value' => $GLOBALS['phpgw_info']['user']['account_id']
666                                                                );
667                                                        }
668                                                }
669                                                else
670                                                {
671                                                        $find_restric[0] = array(
672                                                                0 => array(
673                                                                        'type'  => 'branch',
674                                                                        'value' => 'OR',
675                                                                        'sub_branch' => array(
676                                                                                0 => array(
677                                                                                        'field' => 'contact.names_ordered',
678                                                                                        'type'  => 'LIKE',
679                                                                                        'value' => '0%'
680                                                                                ),
681                                                                                1 => array(
682                                                                                        'field' => 'contact.names_ordered',
683                                                                                        'type'  => 'LIKE',
684                                                                                        'value' => '1%'
685                                                                                ),
686                                                                                2 => array(
687                                                                                        'field' => 'contact.names_ordered',
688                                                                                        'type'  => 'LIKE',
689                                                                                        'value' => '2%'
690                                                                                ),
691                                                                                3 => array(
692                                                                                        'field' => 'contact.names_ordered',
693                                                                                        'type'  => 'LIKE',
694                                                                                        'value' => '3%'
695                                                                                ),
696                                                                                4 => array(
697                                                                                        'field' => 'contact.names_ordered',
698                                                                                        'type'  => 'LIKE',
699                                                                                        'value' => '4%'
700                                                                                ),
701                                                                                5 => array(
702                                                                                        'field' => 'contact.names_ordered',
703                                                                                        'type'  => 'LIKE',
704                                                                                        'value' => '5%'
705                                                                                ),
706                                                                                6 => array(
707                                                                                        'field' => 'contact.names_ordered',
708                                                                                        'type'  => 'LIKE',
709                                                                                        'value' => '6%'
710                                                                                ),
711                                                                                7 => array(
712                                                                                        'field' => 'contact.names_ordered',
713                                                                                        'type'  => 'LIKE',
714                                                                                        'value' => '7%'
715                                                                                ),
716                                                                                8 => array(
717                                                                                        'field' => 'contact.names_ordered',
718                                                                                        'type'  => 'LIKE',
719                                                                                        'value' => '8%'
720                                                                                ),
721                                                                                9 => array(
722                                                                                        'field' => 'contact.names_ordered',
723                                                                                        'type'  => 'LIKE',
724                                                                                        'value' => '9%'
725                                                                                ),
726                                                                        ),
727                                                                )
728                                                        );
729                                                }
730
731                                                if($this->page_info['actual_catalog']['class'] == 'bo_people_catalog'){                                                         
732                                                        $find_restric[0][1]     = array(
733                                                                'field' => 'contact.id_owner',
734                                                                'type'  => '=',
735                                                                'value' => $GLOBALS['phpgw_info']['user']['account_id']
736                                                        );
737                                                }
738                                               
739                                               
740                                                $find_field[0] = array('contact.id_contact','contact.names_ordered');
741                                               
742                                                $find_other[0] = array(
743                                                        'order'  => 'contact.names_ordered'
744                                                );
745                                               
746                                                break;
747                                       
748                                        case 'bo_global_ldap_catalog':
749                                       
750                                                $field_name = 'id_contact';
751
752                                                if ($letter !== 'number')
753                                                {
754                                                        $find_restric[0] = array(
755                                                                0 => array(
756                                                                        'field' => 'contact.names_ordered',
757                                                                        'type'  => 'iLIKE',
758                                                                        'value' => $letter !== 'all' ? $letter.'%' : '%'
759                                                                ),
760                                                                /*
761                                                                 * Restrict the returned contacts in a "first letter" search
762                                                                 * to objectClass = phpgwAccount, must have attibute phpgwAccountStatus,
763                                                                 * phpgwAccountVisible != -1
764                                                                 */
765                                                                1 => array(
766                                                                        'field' => 'contact.object_class',
767                                                                        'type'  => '=',
768                                                                        'value' => 'phpgwAccount'
769                                                                ),
770                                                                2 => array(
771                                                                        'field' => 'contact.account_status',
772                                                                        'type'  => 'iLIKE',
773                                                                        'value' => '%'
774                                                                ),
775                                                                3 => array(
776                                                                        'field' => 'contact.account_visible',
777                                                                        'type'  => '!=',
778                                                                        'value' => '-1'
779                                                                )
780                                                        );
781                                                        // If not external catalog get only phpgwAccountType = u ou l
782                                                        if (!$external)
783                                                        {
784                                                                $find_restric[0][5] =  array(
785                                                                                'type'  => 'branch',
786                                                                                'value' => 'OR',
787                                                                                'sub_branch' => array(
788                                                                                        0 => array(
789                                                                                        'field' => 'contact.account_type',
790                                                                                        'type'  => '=',
791                                                                                        'value' => 'u'
792                                                                                        ),
793                                                                                        1 => array(
794                                                                                        'field' => 'contact.account_type',
795                                                                                        'type'  => '=',
796                                                                                        'value' => 'i'
797                                                                                        ),
798                                                                                        2 => array(
799                                                                                        'field' => 'contact.account_type',
800                                                                                        'type'  => '=',
801                                                                                        'value' => 'l'
802                                                                                        ),
803                                                                                        3 => array(
804                                                                                        'field' => 'contact.account_type',
805                                                                                        'type'  => '=',
806                                                                                        'value' => 'g'
807                                                                                        )
808                                                                                )
809                                                                );
810                                                        }
811                                                }
812                                                else
813                                                {
814                                                        $find_restric[0] = array(
815                                                                /*
816                                                                 * Restrict the returned contacts in a "first number" search
817                                                                 * to objectClass = phpgwAccount, must have attibute phpgwAccountStatus,
818                                                                 * phpgwAccountVisible != -1
819                                                                 */
820                                                                0 => array(
821                                                                        'field' => 'contact.object_class',
822                                                                        'type'  => '=',
823                                                                        'value' => 'phpgwAccount'
824                                                                ),
825                                                                1 => array(
826                                                                        'field' => 'contact.account_status',
827                                                                        'type'  => 'iLIKE',
828                                                                        'value' => '%'
829                                                                ),
830                                                                2 => array(
831                                                                        'field' => 'contact.account_visible',
832                                                                        'type'  => '!=',
833                                                                        'value' => '-1'
834                                                                ),
835                                                                3 => array(
836                                                                        'type'  => 'branch',
837                                                                        'value' => 'OR',
838                                                                        'sub_branch' => array(
839                                                                                0 => array(
840                                                                                        'field' => 'contact.names_ordered',
841                                                                                        'type'  => 'LIKE',
842                                                                                        'value' => '0%'
843                                                                                ),
844                                                                                1 => array(
845                                                                                        'field' => 'contact.names_ordered',
846                                                                                        'type'  => 'LIKE',
847                                                                                        'value' => '1%'
848                                                                                ),
849                                                                                2 => array(
850                                                                                        'field' => 'contact.names_ordered',
851                                                                                        'type'  => 'LIKE',
852                                                                                        'value' => '2%'
853                                                                                ),
854                                                                                3 => array(
855                                                                                        'field' => 'contact.names_ordered',
856                                                                                        'type'  => 'LIKE',
857                                                                                        'value' => '3%'
858                                                                                ),
859                                                                                4 => array(
860                                                                                        'field' => 'contact.names_ordered',
861                                                                                        'type'  => 'LIKE',
862                                                                                        'value' => '4%'
863                                                                                ),
864                                                                                5 => array(
865                                                                                        'field' => 'contact.names_ordered',
866                                                                                        'type'  => 'LIKE',
867                                                                                        'value' => '5%'
868                                                                                ),
869                                                                                6 => array(
870                                                                                        'field' => 'contact.names_ordered',
871                                                                                        'type'  => 'LIKE',
872                                                                                        'value' => '6%'
873                                                                                ),
874                                                                                7 => array(
875                                                                                        'field' => 'contact.names_ordered',
876                                                                                        'type'  => 'LIKE',
877                                                                                        'value' => '7%'
878                                                                                ),
879                                                                                8 => array(
880                                                                                        'field' => 'contact.names_ordered',
881                                                                                        'type'  => 'LIKE',
882                                                                                        'value' => '8%'
883                                                                                ),
884                                                                                9 => array(
885                                                                                        'field' => 'contact.names_ordered',
886                                                                                        'type'  => 'LIKE',
887                                                                                        'value' => '9%'
888                                                                                ),
889                                                                        ),
890                                                                ),
891                                                        );
892                                                        // If not external catalog get only phpgwAccountType = u ou l
893                                                        if (!$external)
894                                                        {
895                                                                $find_restric[0][5] =  array(
896                                                                        'type'  => 'branch',
897                                                                        'value' => 'OR',
898                                                                        'sub_branch' => array(
899                                                                                0 => array(
900                                                                                'field' => 'contact.account_type',
901                                                                                'type'  => '=',
902                                                                                'value' => 'u'
903                                                                                ),
904                                                                                1 => array(
905                                                                                'field' => 'contact.account_type',
906                                                                                'type'  => '=',
907                                                                                'value' => 'i'
908                                                                                ),
909                                                                                2 => array(
910                                                                                'field' => 'contact.account_type',
911                                                                                'type'  => '=',
912                                                                                'value' => 'l'
913                                                                                ),
914                                                                                3 => array(
915                                                                                'field' => 'contact.account_type',
916                                                                                'type'  => '=',
917                                                                                'value' => 'g'
918                                                                                )
919                                                                               
920                                                                        )
921                                                                );
922                                                        }
923                                                }
924
925                                                if (!$external)
926                                                {
927                                                        // Get only this attributes: dn, cn, phpgwAccountType, objectClass, phpgwAccountStatus, phpghAccountVisible
928                                                        // for non-external catalogs, used to restrict the attributes used in filters
929                                                        $find_field[0] = array('contact.id_contact','contact.names_ordered','contact.account_type',
930                                                                'contact.object_class',/*'contact.account_status',*/'contact.account_visible');
931                                                }
932                                                else
933                                                {
934                                                        // Get only this attributes: dn, cn for external catalogs,
935                                                        // used to restrict the attributes used in filters
936                                                        $find_field[0] = array('contact.id_contact','contact.names_ordered');
937                                                }
938                                               
939                                                $find_other[0] = array(
940                                                        //'offset' => (($page-1)*$this->page_info['n_cards']),
941                                                        //'limit'  => $this->page_info['n_cards'],
942                                                        'order'  => 'contact.names_ordered'
943                                                );
944                                               
945                                                break;
946                                       
947                                        case 'bo_company_manager':
948                                                $field_name = 'id_company';
949       
950                                                $find_field[0] = array('company.id_company','company.company_name');
951                                               
952                                                $find_other[0] = array(
953                                                        //'offset' => (($page-1)*$this->page_info['n_cards']),
954                                                        //'limit'  => $this->page_info['n_cards'],
955                                                        'order'  => 'company.company_name'
956                                                );
957       
958                                                $find_restric[0] = array(
959                                                        0 => array(
960                                                                'field' => 'company.company_name',
961                                                                'type'  => 'iLIKE',
962                                                                'value' => $letter !== 'all' ? $letter.'%' : '%'
963                                                        )
964                                                );
965                                                       
966                                                break;
967
968                                        case 'bo_group_manager':
969                                        case 'bo_shared_group_manager':
970                                                                                               
971                                                $field_name = 'id_group';
972                                               
973                                                if ($letter !== 'number')       {
974                                                       
975                                                        $find_restric[0] = array(
976                                                                0 => array(
977                                                                        'field' => 'group.title',
978                                                                        'type'  => 'iLIKE',
979                                                                        'value' => $letter !== 'all' ? $letter.'%' : '%'
980                                                                )
981                                                        );
982                                                }
983                                                 else {
984                                                       
985                                                        $find_restric[0] = array(
986                                                                0 => array(
987                                                                                        'field' => 'group.title',
988                                                                                        'type'  => 'LIKE',
989                                                                                        'value' => '0%'                                                                         
990                                                                )
991                                                        );                                             
992                                                }
993                                               
994                                                if($this->page_info['actual_catalog']['class'] == 'bo_group_manager'){
995                                                        array_push($find_restric[0],  array(
996                                                                                        'field' => 'group.owner',
997                                                                                        'type'  => '=',
998                                                                                        'value' => $GLOBALS['phpgw_info']['user']['account_id']                                                                         
999                                                                        )
1000                                                        );
1001                                                }
1002                                               
1003                                                $find_field[0] = array('group.id_group','group.title','group.short_name');                                             
1004                                                $find_other[0] = array(
1005                                                        'order'  => 'group.title'
1006                                                );                                             
1007                                                break;
1008                                       
1009                                        case 'bo_catalog_group_catalog':
1010                                                $this->page_info['actual_entries'] = false;
1011                                               
1012                                                $this->page_info['actual_letter'] = $letter;
1013                                                $this->page_info['actual_page'] = 0;
1014                                               
1015                                                $this->save_session();
1016                                                $final[0] = 0;
1017                                                $final[1] = $this->typeContact;
1018                                                echo serialize($final);                                         
1019                                                return;
1020
1021                                }
1022
1023                                $result = $this->bo->find($find_field[0],$find_restric[0],$find_other[0]);
1024                                $n_entries = count($result);
1025                               
1026                                if ($n_entries)
1027                                {
1028                                        //echo 'N_entries: '.$n_entries.'<br>';
1029                                        $this->page_info['n_pages'] = ceil($n_entries/($this->page_info['n_cards'] ? $this->page_info['n_cards'] : 1));
1030                                }
1031                                else
1032                                {
1033                                        $this->page_info['n_pages'] = 0;
1034                                }
1035
1036                                if (!$result)
1037                                {
1038                                       
1039                                        $this->page_info['actual_entries'] = false;
1040                                       
1041                                        $this->page_info['actual_letter'] = $letter;
1042                                        $this->page_info['actual_page'] = 0;
1043                                       
1044                                        $this->save_session();                         
1045                                        $final[0] = 0;
1046                                        $final[1] = $this->typeContact;
1047                                        echo serialize($final);                                                                                 
1048                                        return;
1049                                }
1050                                else
1051                                {
1052                                        unset($this->page_info['actual_entries']);
1053                                        foreach ($result as $id => $value)
1054                                        {
1055                                                if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
1056                                                        $this->page_info['actual_entries'][] = $value[$field_name];
1057                                                else
1058                                                        $this->page_info['actual_entries'][] = array(0=>$value[$field_name],1=>$value['perms'],2=>$value['owner']);
1059                                        }
1060                                        //print_r($this->page_info['actual_entries']);
1061                                }
1062                        }
1063                        else if ($letter === 'search')
1064                        {
1065                                //if (!$ids and $this->page_info['actual_letter'] !== 'search')
1066                                if (!$ids)
1067                                {
1068                                        //error_log('!$ids e $this->page_info[\'actual_letter\'] != search');
1069                                        $this->page_info['actual_entries'] = false;
1070                                       
1071                                        $this->page_info['actual_letter'] = $letter;
1072                                        $this->page_info['actual_page'] = 0;
1073                                       
1074                                        $this->save_session();
1075                                        $final[0] = 0;
1076                                        $final[1] = $this -> typeContact;
1077                                        echo serialize($final);                                 
1078                                        return;
1079                                }
1080                                else if ($ids['error'])
1081                                {
1082                                        $this->page_info['actual_entries'] = false;
1083                                        $this->page_info['actual_letter'] = $letter;
1084                                        $this->page_info['actual_page'] = 0;
1085
1086                                        $this->save_session();
1087                                        $final[0] = 0;
1088                                        $final[1] = $this -> typeContact;
1089                                        $final['error'] = $ids['error'];
1090                                        echo serialize($final);
1091                                        return;
1092                                }
1093                                else if ($ids)
1094                                {                               
1095                                        $this->page_info['actual_letter']  = $letter;
1096                                        $this->page_info['actual_entries'] = $ids;
1097                                        $this->page_info['n_pages'] = ceil(count($ids)/($this->page_info['n_cards'] ? $this->page_info['n_cards'] : 1));
1098                                }
1099                        }
1100                        else
1101                        {
1102                                unset($ids);
1103                        }
1104
1105                        if ($this->page_info['actual_entries'])
1106                        {
1107                                if ($page >= $this->page_info['n_pages'])
1108                                {
1109                                        $page = $this->page_info['n_pages'];
1110                                }
1111                               
1112                                $final = array(
1113                                        0 => (int)$this->page_info['n_pages'],
1114                                        1 => (int)$page,
1115                                        2 => array(
1116                                                0 => 'cc_company',
1117                                                1 => 'cc_name',
1118                                                2 => 'cc_title',
1119                                                3 => 'cc_phone',
1120                                                4 => 'cc_mail',
1121                                                5 => 'cc_alias',
1122                                                6 => 'cc_id',
1123                                                7 => 'cc_forwarding_address'                                           
1124                                        )
1125                                );
1126                               
1127                                //echo 'Page: '.$page.'<br>';
1128                                $id_i = (($page-1)*$this->page_info['n_cards']);
1129                                $id_f = $id_i + $this->page_info['n_cards'];
1130                                $n_entries = count($this->page_info['actual_entries']);
1131                               
1132                                //echo 'ID_I: '.$id_i.'<br>';
1133                                //echo 'ID_F: '.$id_f.'<br>';
1134                               
1135                                $ids = array();
1136                                $perms = array();
1137                                $owners = array();
1138                                $array_temp = array();                 
1139                               
1140                                foreach($this->page_info['actual_entries'] as $key=>$tmp){
1141                                                $array_temp[] = $tmp;                           
1142                                }
1143                       
1144                                for($i = $id_i; $i < $id_f and $i < $n_entries; $i++)
1145                                {
1146                                        if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
1147                                                $ids[] = $array_temp[$i];
1148                                        else {
1149                                                $ids[] = $array_temp[$i][0];
1150                                                $perms[] = $array_temp[$i][1];
1151                                                $owners[] = $array_temp[$i][2];
1152                                        }
1153                                        //$perms[] = $array_temp[$i];
1154                                }
1155                               
1156                                // Carrega o nome completo dos donos dos objetos (contatos e grupos);
1157                                $owner_names = array();
1158                                                       
1159                                if($owners) {
1160                                        $filter = "(|";
1161                                        foreach($owners as $i => $owner) {
1162                                                $filter .= "(uidNumber=".$owner.")";
1163                                        }
1164                                        $filter .= ")";
1165
1166                                        if(!$this->bo->catalog->src_info) {
1167                                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
1168                                                $this->bo->catalog->src_info = $ldap->srcs[1];
1169                                        }
1170                                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], false);                             
1171                                        $dn=$this->bo->catalog->src_info['dn'];
1172                                        $justThese = array("cn","uidnumber","uid");
1173                                        $sr = ldap_search($ds,$dn, $filter,$justThese);                                                         
1174                                        $info = ldap_get_entries($ds, $sr);
1175                                        ldap_close($ds);                                                                                       
1176                                        for($z = 0; $z < $info['count']; $z++) {
1177                                                $owner_names[$info[$z]['uidnumber'][0]] = array("cn" => $info[$z]['cn'][0], "uid" => $info[$z]['uid'][0]);
1178                                        }                               
1179                                }
1180                                /// Original
1181                                //for($i = $id_i; $i < $id_f and $i < $n_entries; $i++)
1182                                //{
1183                                //      $ids[] = $this->page_info['actual_entries'][$i];
1184                                //}
1185                                ///
1186                                $fields = $this->bo->catalog->get_fields(false);
1187                                if( $this->typeContact == 'groups' || $this->typeContact == 'shared_groups') {
1188                                        $final = array(
1189                                                0 => (int)$this->page_info['n_pages'],
1190                                                1 => (int)$page,
1191                                                2 => array(
1192                                                        0 => 'cc_title',
1193                                                        1 => 'cc_short_name',
1194                                                        2 => 'cc_id',
1195                                                        3 => 'cc_contacts'
1196                                                )                                               
1197                                        );                                     
1198                                        $groups =& $this->bo->catalog->get_multiple_entries($ids,$fields);
1199                                                                                                                       
1200                                        $i = 0;
1201                                        // contatos do grupo
1202                                        $boGroups = CreateObject('contactcenter.bo_group');                                     
1203                                        $contacts = array();
1204                                       
1205                                        foreach($groups as $group)              {       
1206                                                $final[3][$i][0] = $group['title'] ? $group['title'] : 'none';
1207                                                $final[3][$i][1] = $group['short_name'] ? $group['short_name'] : 'none';                                               
1208                                                $final[3][$i][2] = $group['id_group'] ? $group['id_group'] : 'none';
1209                                                $contacts = $boGroups -> get_contacts_by_group($group['id_group']);
1210                                                $final[3][$i][3] = $contacts;
1211                                                $final[3][$i][4] = $perms[$i];
1212                                                if($this->typeContact == 'shared_groups'){
1213                                                        $final[3][$i][5] = lang('Shared').": ".$owner_names[$owners[$i]]['cn'];
1214                                                        $final[3][$i][6] = $owner_names[$owners[$i]]['uid'];
1215                                                        $final[3][$i][7] = $owners[$i]; //uidNumber
1216                                                }                                               
1217                                                $i++;                                                   
1218                                        }
1219                                       
1220                                        $this->page_info['actual_letter'] = $letter;
1221                                        $this->page_info['actual_page'] = $page;                                       
1222                                       
1223                                       
1224                                        $lnk_compose = "location.href=('../expressoMail1_2/index.php?to=";
1225                                       
1226                                        $final[5] = '<span class="link"  onclick="'.$lnk_compose;                                       
1227                                        $final[10] = $this->typeContact;                                                                                                                                                                                                               
1228                                        $this->save_session();                                 
1229                                        echo serialize($final);
1230                                        return;                                 
1231                                }
1232                                $final[10] = $this -> typeContact;
1233                               
1234                                $fields['photo'] = true;
1235                                $fields['names_ordered'] = true;
1236                                $fields['alias'] = true;
1237                                $fields['account_type'] = true;
1238                                $fields['companies'] = 'default';
1239                                $fields['connections'] = 'default';
1240                                // ?aqui alterar a chamada desse método para receber o base dn?
1241                                if($external)
1242                                        $contacts = &$this->bo->catalog->get_multiple_entries($ids,$fields,false,true);
1243                                else
1244                                        $contacts = &$this->bo->catalog->get_multiple_entries($ids,$fields);
1245                               
1246                               
1247                                if (!is_array($contacts) or !count($contacts))
1248                                {
1249                                        $final[0] = 0;
1250                                        $final[1] = $this -> typeContact;
1251                                        echo serialize($final);
1252                                        return;
1253                                }
1254                               
1255                                $i = 0;
1256                                foreach($contacts as $index => $contact)
1257                                {
1258                                        /*
1259                                         * TODO: Os timeouts de conexão foram retirados, ver se será necessário retornar essa funcionalidade, e,
1260                                         * neste caso, terminar a implementação das mensagens de retorno.
1261                                         */
1262                                        if ($index !== 'error'){
1263                                                $final[3][$i][0] = $contact['companies']['company1']['company_name']?$contact['companies']['company1']['company_name']:'none';
1264                                                if($this->page_info['actual_catalog']['class']!='bo_global_ldap_catalog'){
1265                                                        $final[3][$i][1] = $contact['names_ordered'] ? urldecode($contact['names_ordered'])  : 'none';
1266                                                }
1267                                                else {
1268                                                        $contact['names_ordered'][0] = urldecode($contact['names_ordered'][0]);
1269                                                        $final[3][$i][1] = $contact['names_ordered'] ? $contact['names_ordered']  : 'none';
1270                                                }
1271                                                $final[3][$i][2] = $contact['companies']['company1']['title']? urldecode( $contact['companies']['company1']['title'] ) :'none';
1272
1273                                                /* Select the correct Email and Telephone to be shown */
1274                                                $preferences = ExecMethod('contactcenter.ui_preferences.get_preferences');
1275                                               
1276                                                if (!is_array($preferences))
1277                                                {
1278                                                        $preferences['personCardEmail'] = 1;
1279                                                        $preferences['personCardPhone'] = 2;
1280                                                }
1281                                                if ($contact['connections'])
1282                                                {
1283                                                        $default_email_found = false;
1284                                                        $default_phone_found = false;
1285                                                        foreach($contact['connections'] as $conn_info)
1286                                                        {
1287                                                                if ($conn_info['id_type'] == $preferences['personCardEmail'] and !$default_email_found)
1288                                                                {
1289                                                                        if ($conn_info['connection_is_default'])
1290                                                                        {
1291                                                                                $default_email_found = true;
1292                                                                        }
1293                                                                        $final[3][$i][4] = $conn_info['connection_value'] ? $conn_info['connection_value'] : 'none';
1294                                                                }
1295                                                                else if ($conn_info['id_type'] == $preferences['personCardPhone'] and !$default_phone_found)
1296                                                                {
1297                                                                        if ($conn_info['connection_is_default'])
1298                                                                        {
1299                                                                                $default_phone_found = true;
1300                                                                        }
1301                                                                        if (!($_SESSION['phpgw_info']['user']['preferences']['contactcenter']['telephone_number'] == $conn_info['connection_value']) && $_SESSION['phpgw_info']['user']['preferences']['contactcenter']['voip_enabled'] && $conn_info['connection_value'] && preg_match('/^\([0-9]{2}\)[0-9]{4}\-[0-9]{4}$/',$conn_info['connection_value'])==1 && !$external){
1302                                                                                $conn_info['connection_value'] = "<a title=\"".lang("Call Extension")."\" href=\"#\" onclick=\"connectVoip('".$conn_info['connection_value']."', 'com')\">".$conn_info['connection_value']."</a>";
1303                                                                        }
1304                                                                        $final[3][$i][3] = $conn_info['connection_value'] ? $conn_info['connection_value'] : 'none';
1305                                                                }
1306                                                        }
1307                                                }
1308                                               
1309                                                if (!$final[3][$i][3])
1310                                                {
1311                                                        $final[3][$i][3] = 'none';
1312                                                }
1313
1314                                                if (!$final[3][$i][4])
1315                                                {
1316                                                        $final[3][$i][4] = 'none';
1317                                                }
1318
1319                                                $final[3][$i][5] = $contact['alias']? urldecode( $contact['alias'] ):'none';
1320                                                $final[3][$i][6] = $ids[$i];
1321
1322                                        //      If contact is a public list or a group, then load the forwarding addresses.
1323                                                if($contact['account_type'][0] == 'l' || $contact['account_type'][0] == 'g')
1324                                                        $final[3][$i][7] = ($contact['account_type'][0] == 'l' ? 'list' : 'group');
1325                                                       
1326                                                if($this->page_info['actual_catalog']['class']=='bo_shared_people_manager') {
1327                                                        $final[3][$i][8] = $perms[$i];
1328                                                        $final[3][$i][9] = lang('Shared').": ".$owner_names[$owners[$i]]['cn'];
1329                                                }
1330
1331                                                $final[4][$i] = $contact['photo'] ? 1  : 0;
1332                                        //      print_r($final[3][$i]);
1333                                        //      exit;
1334                                                $i++;
1335                                        }
1336                                        else
1337                                        {
1338                                                // coloca mensagem de erro no vetor que retorna para o browser
1339                                        }
1340                                       
1341                                }
1342                                $lnk_compose = "location.href=('../expressoMail1_2/index.php?to=";
1343                                $final[5] = '<span class="link" onclick="'.$lnk_compose;
1344                                $final[6] = $prop_names;
1345                                $final[7] = $validos;
1346                                $final[8] = $this->page_info['actual_catalog']['class'];
1347                                $final[9] = $count;
1348
1349                                $this->page_info['actual_letter'] = $letter;
1350                                $this->page_info['actual_page'] = $page;
1351                               
1352                                $this->save_session();                         
1353                                echo serialize($final);
1354                                return;
1355                        }
1356                       
1357                        $this->page_info['actual_letter'] = $letter;
1358                        $this->page_info['actual_page'] = $page;
1359                       
1360                        $this->save_session();
1361                       
1362                        $final[0] = 0;
1363                        $final[1] = $this -> typeContact;
1364                        echo serialize($final);
1365                }
1366               
1367                function get_visible_all_ldap()
1368                {
1369                        $bo = CreateObject('contactcenter.bo_ldap_manager');
1370                        $ldap_query = $bo->srcs;
1371                        return $ldap_query[1]['visible'];       
1372                }
1373
1374 
1375                /*!
1376               
1377                        @function get_group_data
1378                        @abstract Returns all the information of a given Group
1379                        @author Nilton Emilio Buhrer Neto
1380                       
1381                        @param (integer) $id The id to get information
1382               
1383                */             
1384                function get_group_data($id,$shared_from=null)
1385                {
1386                        $this->bo->catalog = CreateObject('contactcenter.bo_group_manager');
1387                        $fields = $this->bo->catalog->get_fields(true);
1388                        $data = $this->bo->catalog->get_single_entry($id,$fields);
1389                       
1390                        if($id) {                       
1391                                // get All Contacts by group.
1392                                $data['contact_in_list'] = $this->bo->catalog->get_contacts_by_group($id);                                                             
1393                        }
1394                       
1395                        $boGroup = CreateObject('contactcenter.bo_group');
1396                                               
1397                        $all_contacts = $boGroup->get_all_contacts('only_email',$shared_from);
1398                       
1399                        $contact_options = "";
1400                        if(count($all_contacts)) {                                     
1401                                foreach($all_contacts as $idx => $contact) {                           
1402                                        $contact_options .= "<OPTION value='".$contact['id_connection']."'>".$contact['names_ordered']." (".$contact['connection_value'].")</OPTION>";
1403                                }
1404                        }
1405                        $data['contact_list'] = $contact_options;                       
1406                        $data['result'] = 'ok';
1407                                                                                       
1408                        echo serialize($data);                 
1409                }               
1410               
1411                /*!
1412               
1413                        @function get_full_data
1414                        @abstract Returns all the information of a given Entry
1415                        @author Raphael Derosso Pereira
1416                       
1417                        @param (integer) $id The id to get information
1418               
1419                */
1420                function get_full_data($id,$catalog='bo_people_catalog')
1421                {
1422                        $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
1423                        $this->bo->catalog = CreateObject('contactcenter.'.$catalog);           
1424                        $fields = $this->bo->catalog->get_fields(true);
1425                        $fields['photo'] = false;
1426                        $entry = $this->bo->catalog->get_single_entry($id,$fields);
1427
1428                        if (is_bool($entry['given_names']))
1429                        {
1430                                $data['result'] = 'false';
1431                                echo serialize($data);
1432                                return;
1433                        }
1434
1435                        $date = explode('-', $entry['birthdate']);
1436                        $j = 0;
1437                        for ($i = 0; $i < 5; $i+=2)
1438                        {
1439                                switch($dateformat{$i})
1440                                {
1441                                        case 'Y':
1442                                                $birthdate[$j] = $date[0];
1443                                                break;
1444
1445                                        case 'm':
1446                                        case 'M':
1447                                                $birthdate[$j] = $date[1];
1448                                                break;
1449
1450                                        case 'd':
1451                                                $birthdate[$j] = $date[2];
1452                                }
1453                                $j++;
1454                        }
1455                        $datecount = 0;
1456                       
1457                        $data['result'] = 'ok';
1458                        $data['cc_full_add_contact_id'] = $id;
1459
1460                        /* Personal Data */
1461                        $data['personal']['cc_pd_photo'] = '../index.php?menuaction=contactcenter.ui_data.data_manager&method=get_photo&id='.$id;
1462                        $data['personal']['cc_pd_alias'] = $entry['alias'];
1463                        $data['personal']['cc_pd_given_names'] = $entry['given_names'];
1464                        $data['personal']['cc_pd_family_names'] = $entry['family_names'];
1465                        $data['personal']['cc_pd_full_name'] = $entry['names_ordered'];
1466                        $data['personal']['cc_pd_suffix'] = $entry['id_suffix'];
1467                        $data['personal']['cc_pd_birthdate_0'] = $birthdate[0];
1468                        $data['personal']['cc_pd_birthdate_1'] = $birthdate[1];
1469                        $data['personal']['cc_pd_birthdate_2'] = $birthdate[2];
1470                        //$data['personal']['cc_pd_sex'] = $entry['sex'] === 'M' ? 1 : ($entry['sex'] === 'F' ? 2 : 0);
1471                        $data['personal']['cc_pd_prefix'] = $entry['id_prefix'];
1472                        $data['personal']['cc_pd_gpg_finger_print'] = $entry['pgp_key'];
1473                        $data['personal']['cc_pd_notes'] = $entry['notes'];
1474
1475                        /* Addresses */
1476                        if (is_array($entry['addresses']))
1477                        {
1478                                $data['addresses'] = $entry['addresses'];
1479                        }
1480
1481                        /* Connections */
1482                        if (is_array($entry['connections']))
1483                        {
1484                                $data['connections'] = array();
1485                                foreach ($entry['connections'] as $connection)
1486                                {
1487                                        $type = $connection['id_type'];
1488                                        $i = count($data['connections'][$type]);
1489                                        $data['connections'][$type][$i]['id'] = $connection['id_connection'];
1490                                        $data['connections'][$type][$i]['name'] = $connection['connection_name'];
1491                                        $data['connections'][$type][$i]['value'] = $connection['connection_value'];
1492                                        $data['connections'][$type][$i]['is_default'] = $connection['connection_is_default'];
1493                                }
1494                        }
1495                       
1496                        /*Corporative*/
1497                        $data['personal']['cc_name_corporate'] = $entry['corporate_name'];
1498                        $data['personal']['cc_job_title'] = $entry['job_title'];
1499                        $data['personal']['cc_department'] = $entry['department'];
1500                        $data['personal']['cc_name_corporate'] = $entry['corporate_name'];
1501                        $data['personal']['cc_web_page'] = $entry['web_page'];
1502                       
1503                       
1504                        /* Relations */
1505                       
1506                        echo serialize($data);
1507                }
1508
1509                /*!
1510
1511                        @function get_contact_full_add_const
1512                        @abstract Returns all the constant fields in Contact Full Add Window to the JS
1513                        @author Raphael Derosso Pereira
1514                */
1515                function get_contact_full_add_const()
1516                {
1517                        $data = array();
1518                        $boPeopleCatalog = CreateObject('contactcenter.bo_people_catalog');
1519                        $predata[] = $boPeopleCatalog -> get_all_prefixes();
1520                        $predata[] = $boPeopleCatalog -> get_all_suffixes();
1521                        $predata[] = $boPeopleCatalog -> get_all_addresses_types();
1522                        $predata[] = $boPeopleCatalog -> get_all_countries();
1523                        $predata[] = $boPeopleCatalog -> get_all_connections_types();
1524                        //$predata[] = $this->bo->catalog->get_all_relations_types();
1525
1526                        $i = 0;
1527                        foreach($predata as $data_)
1528                        {
1529                                if ($data_)
1530                                {
1531                                        $data[$i] = $data_;
1532                                }
1533
1534                                $i++;
1535                        }
1536
1537                        if (count($data))
1538                        {
1539                                echo serialize($data);
1540                                return;
1541                        }
1542                       
1543                        echo 0;
1544                }
1545               
1546                /*!
1547               
1548                        @function quick_add
1549                        @abstract Adds a new Contact using the Quick Add interface
1550                        @author Raphael Derosso Pereira
1551                       
1552                        @param string $sdata Serialized data
1553                */
1554                function quick_add($sdata)
1555                {
1556                       
1557                        $sdata = str_replace('\\"', '"', $sdata);
1558                        $new_array = unserialize($sdata);
1559                        $tdata = array();
1560                       
1561                        foreach($new_array as $tmp)
1562                                $tdata[] = $tmp;
1563                       
1564                        if (!$tdata)
1565                        {
1566                                echo serialize(array(
1567                                        'msg'    => lang('Problems on adding your Contact. Invalid Data came from client. No Contact added!'),
1568                                        'status' => 'abort'
1569                                ));
1570                               
1571                                return;
1572                        }
1573                       
1574                        // verifica se email já existe!
1575                        $boGroup = CreateObject('contactcenter.bo_group');
1576                        $contact = $boGroup->verify_contact($tdata[4]);
1577                                                                                               
1578                        if($contact)
1579                        {                                                       
1580                                $str_contact = "\r\n - ".implode("\r\n - ",$contact);
1581                               
1582                                echo serialize(array(
1583                                        'msg'    => lang('Problems on adding your Contact. The email "%1" already exists in: %2',$tdata[4], $str_contact),
1584                                        'status' => 'alreadyExists'
1585                                ));
1586                               
1587                                return;                 
1588                        }
1589
1590                        $data['alias'] = $tdata[0];
1591                        $data['given_names'] = $tdata[1];
1592                        $data['family_names'] = $tdata[2];
1593//                      $data['connections']['default_phone']['id_typeof_connection'] = 1;
1594                        $data['connections']['default_phone']['connection_name'] = lang('Main');
1595                        $data['connections']['default_phone']['connection_value'] = $tdata[3];
1596//                      $data['connections']['default_email']['id_typeof_connection'] = 2;
1597                        $data['connections']['default_email']['connection_name'] = lang('Main');
1598                        $data['connections']['default_email']['connection_value'] = $tdata[4];
1599                        $boPeople = CreateObject('contactcenter.bo_people_catalog');
1600
1601                        if ($boPeople ->quick_add($data))
1602                        {                               
1603                                $this->page_info['changed'] = true;
1604                               
1605                                echo serialize(array(
1606                                        'msg'    => lang('Entry added with success!'),
1607                                        'status' => 'ok'
1608                                ));
1609                        }
1610                        else
1611                        {
1612                                echo serialize(array(
1613                                        'msg'    => lang('Problems on adding your Contact. No Contact added!'),
1614                                        'status' => 'error'
1615                                ));
1616                        }
1617
1618                        $this->save_session(); 
1619                       
1620                }
1621
1622                /*!
1623               
1624                        @function add_group
1625                        @abstract Adds a new Group using the Add Group interface
1626                        @author Nilton Emilio Buhrer Neto
1627                       
1628                        @param string $sdata Serialized data
1629                */
1630                function add_group($sdata)
1631                {
1632                        $sdata = str_replace('\\"', '"', $sdata);
1633                        $tdata = unserialize($sdata);
1634                        $new_tdata = array();
1635                       
1636                        if (!$tdata)
1637                        {
1638                                echo serialize(array(
1639                                        'msg'    => lang('Problems on adding your Contact. Invalid Data came from client. No Contact added!'),
1640                                        'status' => 'abort'
1641                                ));
1642                               
1643                                return;
1644                        }
1645                       
1646                        foreach($tdata as $tmp)
1647                                $new_tdata[] = $tmp;
1648                       
1649                        $data['title'] = $new_tdata[0];                 
1650                        $data['contact_in_list'] = $new_tdata[1];
1651                        $data['id_group'] = $new_tdata[2];
1652                                               
1653                        $boGroup = CreateObject('contactcenter.bo_group_manager');
1654                        $id = $boGroup -> add_group($data);
1655                       
1656                        if ($id)
1657                        {
1658                                $this->page_info['changed'] = true;
1659                               
1660                                echo serialize(array(
1661                                        'msg'    => lang('Entry added with success!'),
1662                                        'status' => 'ok'
1663                                ));
1664                        }
1665                        else
1666                        {
1667                                echo serialize(array(
1668                                        'msg'    => lang('Problems on adding your Contact. No Contact added!'),
1669                                        'status' => 'error'
1670                                ));
1671                        }
1672
1673                        $this->save_session();
1674                }
1675
1676                /*!
1677               
1678                        @function remove_group
1679                        @abstract Removes a group if the user has the right to do it
1680                        @author Nilton Emilio Buhrer Neto                       
1681                        @param (integer) $id The id to be removed
1682                               
1683                */
1684                function remove_group($id)
1685                {                               
1686                                $soGroup = CreateObject('contactcenter.so_group');                             
1687                                $data = array ('id_group' => $id);
1688                                if($soGroup -> delete($data)) {
1689                                        echo serialize(array(
1690                                                'msg'    => lang('Removed Entry ID '.$id.'!'),
1691                                                'status' => 'ok'
1692                                        ));                                                     
1693                                }
1694                                else {
1695                                        echo serialize(array(
1696                                                'msg'    => lang('Problems on adding your Contact. No Contact added!'),
1697                                                'status' => 'error'
1698                                        ));
1699                                }
1700
1701                        $this->save_session();                         
1702                }
1703
1704
1705                function remove_all_entries (){
1706               
1707                        $error = false;
1708                        $this->all_entries = $this->bo->catalog->get_all_entries_ids();
1709
1710                        foreach($this->all_entries as $index => $id) {
1711                                $result = $this->bo->catalog->remove_single_entry($id);
1712                                if(!$result) {
1713                                        $error = true;
1714                                        break;         
1715                                }
1716                        }
1717
1718                        if(!$error) {
1719                                echo serialize(array(
1720                                        'msg'    => lang('Removed Entry ID '.$id.'!'),
1721                                        'status' => 'ok'
1722                                ));
1723                        }
1724                        else {
1725                                echo serialize(array(
1726                                        'msg'    => lang('Couldn\'t remove this entry. Inform the Site Admin!'),
1727                                        'status' => 'fail'
1728                                ));
1729                        }
1730
1731                        $this->save_session();
1732                }
1733
1734                /*!
1735               
1736                        @function remove_entry
1737                        @abstract Removes an entry if the user has the right to do it
1738                        @author Raphael Derosso Pereira
1739                       
1740                        @param (integer) $id The id to be removed
1741                               
1742                */
1743                function remove_entry ($id)
1744                {
1745                        if (!is_int($id))
1746                        {
1747                                echo lang('Couldn\'t remove entry! Problem passing data to the server. Please inform admin!');
1748                                return;
1749                        }
1750                       
1751                        $this->page_info['changed'] = true;
1752                        $result = $this->bo->catalog->remove_single_entry($id);
1753                       
1754                        if ($result)
1755                        {
1756                                if ($pos = array_search($id, $this->page_info['actual_entries']))
1757                                {
1758                                        unset($this->page_info['actual_entries'][$pos]);
1759                                }
1760                               
1761                                $temp = false;
1762                                reset($this->page_info['actual_entries']);
1763                                foreach($this->page_info['actual_entries'] as $t)
1764                                {
1765                                        $temp[] = $t;
1766                                }
1767                               
1768                                $this->page_info['actual_entries'] = $temp;
1769
1770                                echo serialize(array(
1771                                        'msg'    => lang('Removed Entry ID '.$id.'!'),
1772                                        'status' => 'ok'
1773                                ));
1774                        }
1775                        else
1776                        {
1777                                echo serialize(array(
1778                                        'msg'    => lang('Couldn\'t remove this entry. Inform the Site Admin!'),
1779                                        'status' => 'fail'
1780                                ));
1781                        }
1782                       
1783                        $this->save_session();
1784                }
1785
1786               
1787                /*!
1788               
1789                        @function post_full_add
1790                        @abstract Saves all the information altered/entered in the Full Add
1791                                window
1792                        @author Raphael Derosso Pereira
1793
1794                */
1795                function post_full_add()
1796                {
1797                        $data =  $_POST['data'];
1798                        // Exceptions!!! utf8 special chars.
1799                        $data = preg_replace("/\%u2(\d+)(\d+)(\d+)/","-",$data);
1800                        $data = unserialize(str_replace('\\"', '"', $data));
1801                        $this -> bo -> catalog = CreateObject('contactcenter.bo_people_catalog');
1802
1803                        if (!is_array($data))
1804                        {
1805                                echo serialize(array(
1806                                        'msg' => lang('<p>Some problem receiving data from browser. This is probably a bug in ContactCenter<br>'.
1807                                                  'Please go to eGroupWare Bug Reporting page and report this bug.<br>'.
1808                                                          'Sorry for the inconvenient!<br><br>'.
1809                                                          '<b><i>ContactCenter Developer Team</i></b></p>'),
1810                                        'status' => 'fatal'
1811                                ));
1812                                return;
1813                        }
1814//                      print_r($data);
1815//                      echo '<br><br>';
1816
1817                        $replacer = $data['commercialAnd'];
1818                        unset($data['commercialAnd']);
1819                        if (!is_string($replacer) or strpos($replacer, "'") or strpos($replacer, '"'))
1820                        {
1821                                echo serialize(array(
1822                                        'msg' => lang('Invalid \'&\' replacer! This may be an attempt to bypass Security! Action aborted!'),
1823                                        'status' => 'fatal'
1824                                ));
1825                               
1826                                return;
1827                        }
1828
1829                        if ($data['id_contact'])
1830                        {
1831                                $id = $data['id_contact'];
1832                                $id_photo = $id;
1833                                unset($data['id_contact']);
1834                        }
1835                        else
1836                        {
1837                                $id_photo = '_new_';
1838                        }
1839                       
1840                        /*
1841                         * Process Photo, if available
1842                         */
1843                        $sleep_count = 0;
1844                        $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
1845                        while($photo_ok[0]{0} !== 'o' and $photo_ok[1]{0} === 'y')
1846                        {
1847                                sleep(1);
1848                                $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
1849                                $sleep_count++;
1850
1851                                if ($sleep_count > 35)
1852                                {
1853                                        // TODO
1854                                        return;
1855                                }
1856                        }
1857                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'n'));
1858                       
1859                        if (isset($this->page_info['photos'][$id_photo]))
1860                        {
1861                                if (array_search($this->page_info['photos'][$id_photo]['status'], array('changed', 'sync')) === false)
1862                                {
1863                                        echo serialize(array(
1864                                                'msg' => $this->page_info['photos'][$id_photo]['msg'],
1865                                                'status' => $this->page_info['photos'][$id_photo]['status']
1866                                        ));
1867
1868                                        return;
1869                                }
1870
1871                                $data['photo'] = $this->page_info['photos'][$id_photo]['content'];
1872                                unset($this->page_info['photos'][$id_photo]);
1873                                $this->save_session();
1874                        }
1875                       
1876                        /*
1877                         * Arrange Date so it gets inserted correctly
1878                         */
1879                         
1880                        $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
1881               
1882                        $j = 0;
1883                        for ($i = 0; $i < 5; $i+=2)
1884                        {
1885                                switch($dateformat{$i})
1886                                {
1887                                        case 'Y':
1888                                                $date[$j]['size'] = 4;
1889                                                $date[$j]['digit'] = 'Y';
1890                                                break;
1891
1892                                        case 'm':
1893                                        case 'M':
1894                                                $date[$j]['size'] = 2;
1895                                                $date[$j]['digit'] = 'M';
1896                                                break;
1897
1898                                        case 'd':
1899                                                $date[$j]['size'] = 2;
1900                                                $date[$j]['digit'] = 'D';
1901                                }
1902                                $j++;
1903                        }
1904                        $datecount = 0;
1905
1906                        /* Verify Data and performs insertion/update */
1907                        foreach($data as $field => &$value)
1908                        {
1909                                if ($value == '' or is_null($value))
1910                                {
1911                                        unset($data[$field]);
1912                                        continue;
1913                                }
1914                               
1915                                switch($field)
1916                                {
1917                                        case 'corporate_name':
1918                                        case 'job_title':
1919                                        case 'department':
1920                                        case 'web_page':
1921                                        case 'alias':
1922                                        case 'given_names':
1923                                        case 'family_names':
1924                                        case 'names_ordered':
1925                                        case 'pgp_key':
1926                                        case 'notes':
1927                                        case 'photo':
1928                                                $value = urldecode( $value );
1929                                                /* Do Nothing. This is just to make sure no invalid field is passed */
1930                                                break;
1931                                       
1932                                        case 'id_status':
1933                                        case 'id_prefix':
1934                                        case 'id_suffix':
1935                                                if ($data[$field] == 0)
1936                                                {
1937                                                        unset($data[$field]);
1938                                                }
1939                                                break;
1940                                       
1941                                        case 'birthdate_0':
1942                                        case 'birthdate_1':
1943                                        case 'birthdate_2':
1944                                       
1945                                                switch($date[$datecount]['digit'])
1946                                                {
1947                                                        case 'Y':
1948                                                                $date['value'][2] = (int) $data[$field];
1949                                                                break;
1950
1951                                                        case 'M':
1952                                                                $date['value'][0] = (int) $data[$field];
1953                                                                break;
1954
1955                                                        case 'D':
1956                                                                $date['value'][1] = (int) $data[$field];
1957                                                                break;
1958                                                }
1959                                                unset($data[$field]);
1960                                                $datecount++;
1961
1962                                                if ($datecount != 3)
1963                                                {
1964                                                        break;
1965                                                }
1966                                               
1967                                                if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
1968                                                {
1969                                                        echo serialize(array(
1970                                                                'msg' => lang('Invalid Date'),
1971                                                                'status' => 'invalid_data'
1972                                                        ));
1973                                                        return;
1974                                                }
1975                                               
1976                                                $data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
1977                                                break;
1978
1979                                        case 'sex':
1980                                                if ($data[$field] !== 'M' and $data[$field] !== 'F')
1981                                                {
1982                                                        echo serialize(array(
1983                                                                'msg' => lang('Invalid Sex'),
1984                                                                'status' => 'invalid_data'
1985                                                        ));
1986                                                        return;
1987                                                }
1988                                                break;
1989
1990
1991                                        case 'addresses':
1992                                                /* Insert new cities/states */
1993                                                if (isset($value['new_states']))
1994                                                {
1995                                                        foreach($value['new_states'] as $type => $state_info)
1996                                                        {
1997                                                                $index = 'address'.$type;
1998                                                               
1999                                                                $id_state = $this->bo->catalog->add_state($state_info);
2000                                                                $data['addresses'][$index]['id_state'] = $id_state;
2001
2002                                                                if ($value['new_cities'][$type])
2003                                                                {
2004                                                                        $value['new_cities'][$type]['id_state'] = $id_state;
2005                                                                }
2006                                                        }
2007
2008                                                        unset($data['addresses']['new_states']);
2009                                                }
2010
2011                                                if (isset($value['new_cities']))
2012                                                {
2013                                                        foreach($value['new_cities'] as $type => $city_info)
2014                                                        {
2015                                                                $index = 'address'.$type;
2016                                                               
2017                                                                $id_city = $this->bo->catalog->add_city($city_info);
2018                                                                $data['addresses'][$index]['id_city'] = $id_city;
2019                                                        }
2020
2021                                                        unset($data['addresses']['new_cities']);
2022                                                }
2023
2024                                        break;
2025
2026                                        case 'connections':
2027                                                /* Does nothing... */
2028                                                break;
2029
2030                                        default:
2031                                                echo serialize(array(
2032                                                        'msg' => lang('Invalid field: ').$field,
2033                                                        'status' => 'invalid_data'
2034                                                ));
2035                                                return;
2036                                }
2037                        }
2038
2039                        $code = '$id = $this->bo->catalog->';
2040
2041                        if (!is_null($id) and $id !== '')
2042                        {
2043                                $code .= $code.'update_single_info($id, $data);';
2044                                $result = array(
2045                                        'msg' => lang('Updated Successfully!'),
2046                                        'status' => 'ok'
2047                                );
2048                        }
2049                        else
2050                        {
2051                                $code .= 'add_single_entry($data);';
2052                                $result = array(
2053                                        'msg' => lang('Entry Added Successfully!'),
2054                                        'status' => 'ok'
2055                                );
2056                        }
2057                       
2058                        eval($code);
2059
2060                        if (!($id))
2061                        {
2062                                $result = array(
2063                                        'msg' => lang('Some problem occured when trying to insert/update contact information.<br>'.
2064                                                   'Report the problem to the Administrator.'),
2065                                        'status' => 'fail'
2066                                );
2067                        }
2068
2069                        echo serialize($result);
2070                }
2071
2072
2073                function post_full_add_shared()
2074                {
2075                        $data =  $_POST['data'];
2076                        // Exceptions!!! utf8 special chars.
2077                        $data = preg_replace("/\%u2(\d+)(\d+)(\d+)/","-",$data);
2078                        $data = unserialize(str_replace('\\"', '"', $data));
2079                        $this -> bo -> catalog = CreateObject('contactcenter.bo_shared_people_manager');
2080
2081                        if (!is_array($data))
2082                        {
2083                                echo serialize(array(
2084                                        'msg' => lang('<p>Some problem receiving data from browser. This is probably a bug in ContactCenter<br>'.
2085                                                  'Please go to eGroupWare Bug Reporting page and report this bug.<br>'.
2086                                                          'Sorry for the inconvenient!<br><br>'.
2087                                                          '<b><i>ContactCenter Developer Team</i></b></p>'),
2088                                        'status' => 'fatal'
2089                                ));
2090                                return;
2091                        }
2092//                      print_r($data);
2093//                      echo '<br><br>';
2094
2095                        $replacer = $data['commercialAnd'];
2096                        unset($data['commercialAnd']);
2097                        if (!is_string($replacer) or strpos($replacer, "'") or strpos($replacer, '"'))
2098                        {
2099                                echo serialize(array(
2100                                        'msg' => lang('Invalid \'&\' replacer! This may be an attempt to bypass Security! Action aborted!'),
2101                                        'status' => 'fatal'
2102                                ));
2103                               
2104                                return;
2105                        }
2106
2107                        if ($data['id_contact'])
2108                        {
2109                                $id = $data['id_contact'];
2110                                $id_photo = $id;
2111                                unset($data['id_contact']);
2112                        }
2113                        else
2114                        {
2115                                $id_photo = '_new_';
2116                        }
2117
2118                        if ($data['owner'])
2119                        {
2120                                $owner = $data['owner'];
2121                                unset($data['owner']);
2122                        }
2123                        /*
2124                         * Process Photo, if available
2125                         */
2126                        $sleep_count = 0;
2127                        $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
2128                        while($photo_ok[0]{0} !== 'o' and $photo_ok[1]{0} === 'y')
2129                        {
2130                                sleep(1);
2131                                $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
2132                                $sleep_count++;
2133
2134                                if ($sleep_count > 35)
2135                                {
2136                                        // TODO
2137                                        return;
2138                                }
2139                        }
2140                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'n'));
2141                       
2142                        if (isset($this->page_info['photos'][$id_photo]))
2143                        {
2144                                if (array_search($this->page_info['photos'][$id_photo]['status'], array('changed', 'sync')) === false)
2145                                {
2146                                        echo serialize(array(
2147                                                'msg' => $this->page_info['photos'][$id_photo]['msg'],
2148                                                'status' => $this->page_info['photos'][$id_photo]['status']
2149                                        ));
2150
2151                                        return;
2152                                }
2153
2154                                $data['photo'] = $this->page_info['photos'][$id_photo]['content'];
2155                                unset($this->page_info['photos'][$id_photo]);
2156                                $this->save_session();
2157                        }
2158                       
2159                        /*
2160                         * Arrange Date so it gets inserted correctly
2161                         */
2162                         
2163                        $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
2164               
2165                        $j = 0;
2166                        for ($i = 0; $i < 5; $i+=2)
2167                        {
2168                                switch($dateformat{$i})
2169                                {
2170                                        case 'Y':
2171                                                $date[$j]['size'] = 4;
2172                                                $date[$j]['digit'] = 'Y';
2173                                                break;
2174
2175                                        case 'm':
2176                                        case 'M':
2177                                                $date[$j]['size'] = 2;
2178                                                $date[$j]['digit'] = 'M';
2179                                                break;
2180
2181                                        case 'd':
2182                                                $date[$j]['size'] = 2;
2183                                                $date[$j]['digit'] = 'D';
2184                                }
2185                                $j++;
2186                        }
2187                        $datecount = 0;
2188
2189                        /* Verify Data and performs insertion/update */
2190                        foreach($data as $field => &$value)
2191                        {
2192                                if ($value == '' or is_null($value))
2193                                {
2194                                        unset($data[$field]);
2195                                        continue;
2196                                }
2197                               
2198                                switch($field)
2199                                {
2200                                        case 'alias':
2201                                        case 'given_names':
2202                                        case 'family_names':
2203                                        case 'names_ordered':
2204                                        case 'pgp_key':
2205                                        case 'notes':
2206                                        case 'photo':
2207                                                $value = urldecode( $value );
2208                                                /* Do Nothing. This is just to make sure no invalid field is passed */
2209                                                break;
2210                                       
2211                                        case 'id_status':
2212                                        case 'id_prefix':
2213                                        case 'id_suffix':
2214                                                if ($data[$field] == 0)
2215                                                {
2216                                                        unset($data[$field]);
2217                                                }
2218                                                break;
2219                                       
2220                                        case 'birthdate_0':
2221                                        case 'birthdate_1':
2222                                        case 'birthdate_2':
2223                                       
2224                                                switch($date[$datecount]['digit'])
2225                                                {
2226                                                        case 'Y':
2227                                                                $date['value'][2] = (int) $data[$field];
2228                                                                break;
2229
2230                                                        case 'M':
2231                                                                $date['value'][0] = (int) $data[$field];
2232                                                                break;
2233
2234                                                        case 'D':
2235                                                                $date['value'][1] = (int) $data[$field];
2236                                                                break;
2237                                                }
2238                                                unset($data[$field]);
2239                                                $datecount++;
2240
2241                                                if ($datecount != 3)
2242                                                {
2243                                                        break;
2244                                                }
2245                                               
2246                                                if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
2247                                                {
2248                                                        echo serialize(array(
2249                                                                'msg' => lang('Invalid Date'),
2250                                                                'status' => 'invalid_data'
2251                                                        ));
2252                                                        return;
2253                                                }
2254                                               
2255                                                $data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
2256                                                break;
2257
2258                                        case 'sex':
2259                                                if ($data[$field] !== 'M' and $data[$field] !== 'F')
2260                                                {
2261                                                        echo serialize(array(
2262                                                                'msg' => lang('Invalid Sex'),
2263                                                                'status' => 'invalid_data'
2264                                                        ));
2265                                                        return;
2266                                                }
2267                                                break;
2268
2269
2270                                        case 'addresses':
2271                                                /* Insert new cities/states */
2272                                                if (isset($value['new_states']))
2273                                                {
2274                                                        foreach($value['new_states'] as $type => $state_info)
2275                                                        {
2276                                                                $index = 'address'.$type;
2277                                                               
2278                                                                $id_state = $this->bo->catalog->add_state($state_info);
2279                                                                $data['addresses'][$index]['id_state'] = $id_state;
2280
2281                                                                if ($value['new_cities'][$type])
2282                                                                {
2283                                                                        $value['new_cities'][$type]['id_state'] = $id_state;
2284                                                                }
2285                                                        }
2286
2287                                                        unset($data['addresses']['new_states']);
2288                                                }
2289
2290                                                if (isset($value['new_cities']))
2291                                                {
2292                                                        foreach($value['new_cities'] as $type => $city_info)
2293                                                        {
2294                                                                $index = 'address'.$type;
2295                                                               
2296                                                                $id_city = $this->bo->catalog->add_city($city_info);
2297                                                                $data['addresses'][$index]['id_city'] = $id_city;
2298                                                        }
2299
2300                                                        unset($data['addresses']['new_cities']);
2301                                                }
2302
2303                                        break;
2304
2305                                        case 'connections':
2306                                                /* Does nothing... */
2307                                                break;
2308
2309                                        default:
2310                                                echo serialize(array(
2311                                                        'msg' => lang('Invalid field: ').$field,
2312                                                        'status' => 'invalid_data'
2313                                                ));
2314                                                return;
2315                                }
2316                        }
2317
2318                        $code = '$id = $this->bo->catalog->';
2319
2320                        if (!is_null($id) and $id !== '')
2321                        {
2322                                $code .= $code.'update_single_info($id, $data);';
2323                                $result = array(
2324                                        'msg' => lang('Updated Successfully!'),
2325                                        'status' => 'ok'
2326                                );
2327                        }
2328                        else
2329                        {
2330                                $code .= 'add_single_entry($data,'.$owner.');';
2331                                $result = array(
2332                                        'msg' => lang('Entry Added Successfully!'),
2333                                        'status' => 'ok'
2334                                );
2335                        }
2336                       
2337                        eval($code);
2338
2339                        if (!($id))
2340                        {
2341                                $result = array(
2342                                        'msg' => lang('Some problem occured when trying to insert/update contact information.<br>'.
2343                                                   'Report the problem to the Administrator.'),
2344                                        'status' => 'fail'
2345                                );
2346                        }
2347
2348                        echo serialize($result);
2349}
2350                /*!
2351               
2352                        @function post_photo
2353                        @abstract Wrapper to post a photo without reload a page.
2354                        @author Raphael Derosso Pereira
2355
2356                */
2357                function post_photo($id)
2358                {
2359                        //print_r($_FILES);
2360                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'y'));
2361                       
2362                        if (!is_array($_FILES) and is_array(!$_FILES['cc_pd_photo']))
2363                        {
2364                                $this->page_info['photos'][$id]['status'] = 'no_upload';
2365                                $this->page_info['photos'][$id]['msg'] = lang('No Photos uploaded to Server.');
2366                               
2367                                $this->save_session();
2368                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2369                                return;
2370                        }
2371
2372                        if (!function_exists('imagecreate'))
2373                        {
2374                                $this->page_info['photos'][$id]['status'] = 'no_GD_lib';
2375                                $this->page_info['photos'][$id]['msg'] = lang('Cannot manipulate Image. No Image added. Please, if you want to use images, ask the Administrator to install GD library.');
2376                               
2377                                $this->save_session();
2378                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2379                                return;
2380                        }
2381
2382                        // TODO: Get Max Size from preferences!
2383                        if ($_FILES['cc_pd_photo']['size'] > 1000000)
2384                        {
2385                                $this->page_info['photos'][$id]['status'] = 'too_large';
2386                                $this->page_info['photos'][$id]['msg'] = lang('Image too large! ContactCenter limits the image size to 1 Mb');
2387
2388                                $this->save_session();
2389                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2390                                return;
2391                        }
2392
2393                        if ($_FILES['cc_pd_photo']['error'])
2394                        {
2395                                $this->page_info['photos'][$id]['status'] = 'error';
2396                                $this->page_info['photos'][$id]['msg'] = lang('Some Error occured while processed the Image. Contact the Administrator. The error code was: ').$_FILES['cc_pd_photo']['error'];
2397
2398                                $this->save_session();
2399                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2400                                return;
2401                        }
2402                       
2403                        switch($_FILES['cc_pd_photo']['type'])
2404                        {
2405                                case 'image/jpeg':
2406                                case 'image/pjpeg':
2407                                        $src_img = imagecreatefromjpeg($_FILES['cc_pd_photo']['tmp_name']);
2408                                        if ($src_img == '')
2409                                        {
2410                                                $bogus = true;
2411                                        }
2412                                        break;
2413
2414                                case 'image/png':
2415                                case 'image/x-png':
2416                                        $src_img = imagecreatefrompng($_FILES['cc_pd_photo']['tmp_name']);
2417                                        if ($src_img == '')
2418                                        {
2419                                                $bogus = true;
2420                                        }
2421                                        break;
2422
2423                                case 'image/gif':
2424                                        $src_img = imagecreatefromgif($_FILES['cc_pd_photo']['tmp_name']);
2425                                        if ($src_img == '')
2426                                        {
2427                                                $bogus = true;
2428                                        }
2429                                        break;
2430
2431                                default:
2432                                       
2433                                        $this->page_info['photos'][$id]['status'] = 'invalid_image';
2434                                        $this->page_info['photos'][$id]['msg'] = lang('The file must be an JPEG, PNG or GIF Image.');
2435
2436                                        $this->save_session();
2437                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2438                                        return;
2439                        }
2440
2441                        if ($bogus)
2442                        {
2443                                        $this->page_info['photos'][$id]['status'] = 'invalid_file';
2444                                        $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
2445                                       
2446                                        $this->save_session();
2447                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2448                                        return;
2449                        }
2450                       
2451                        $img_size = getimagesize($_FILES['cc_pd_photo']['tmp_name']);
2452                        $dst_img = imagecreatetruecolor(60, 80);
2453                       
2454                        if (!imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, 60, 80, $img_size[0], $img_size[1]))
2455                        {
2456                                $this->page_info['photos'][$id]['status'] = 'invalid_file';
2457                                $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
2458                               
2459                                $this->save_session();
2460                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2461                                return;
2462                        }
2463                       
2464                        ob_start();
2465                        imagepng($dst_img);
2466                        $this->page_info['photos'][$id]['content'] = ob_get_contents();
2467                        ob_end_clean();
2468
2469                        $this->page_info['photos'][$id]['status'] = 'changed';
2470                        $this->page_info['photos'][$id]['msg'] = lang('Photo Successfully Updated!');
2471
2472                        $this->save_session();
2473               
2474                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2475
2476                        imagedestroy($src_img);
2477                        imagedestroy($dst_img);
2478                        echo 'ok';
2479                        return;
2480                }
2481
2482
2483                /*!
2484
2485                        @function get_photo
2486                        @abstract Returns the photo to the browser
2487                        @author Raphael Derosso Pereira
2488
2489                */
2490                function get_photo($id)
2491                {
2492                        $fields = $this->bo->catalog->get_fields(false);
2493                        $fields['photo'] = true;
2494                       
2495                        $contact = $this->bo->catalog->get_single_entry($id, $fields);
2496
2497                        if (!$contact['photo'])
2498                        {
2499                                header('Content-type: image/png');
2500                                echo file_get_contents(PHPGW_INCLUDE_ROOT.'/contactcenter/templates/default/images/photo_celepar.png');
2501                                return;
2502                        }
2503                       
2504                        header('Content-type: image/jpeg');
2505                        $photo = imagecreatefromstring ($contact['photo']);
2506                        $width = imagesx($photo);
2507                        $height = imagesy($photo);
2508                        $twidth = 70;
2509                        $theight = 90;
2510                        $small_photo = imagecreatetruecolor ($twidth, $theight);
2511                        imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
2512                        imagejpeg($small_photo,"",100);
2513                        return;
2514                }
2515               
2516                /*!
2517               
2518                        @function get_states
2519                        @abstract Echos a serialized array containing all the states for the given country
2520                        @author Raphael Derosso Pereira
2521
2522                        @params $id_country The ID of the Country that contains the requested states
2523
2524                */
2525                function get_states($id_country)
2526                {
2527                        $states = $this->bo->catalog->get_all_states($id_country);
2528
2529                        if (!$states)
2530                        {
2531                                $result = array(
2532                                        'msg'    => lang('No States found for this Country.'),
2533                                        'status' => 'empty'
2534                                );
2535
2536                                echo serialize($result);
2537                                return;
2538                        }
2539                       
2540                        $result = array(
2541                                'msg'    => lang('States Successfully retrieved!'),
2542                                'status' => 'ok'
2543                        );
2544                       
2545                        foreach ($states as $state_info)
2546                        {
2547                                $result['data'][$state_info['id_state']] = $state_info['name'];
2548
2549                                if ($state_info['symbol'])
2550                                {
2551                                        $result['data'][$state_info['id_state']] .= ', '.$state_info['symbol'];
2552                                }
2553                        }
2554
2555                        echo serialize($result);
2556                }
2557
2558                /*!
2559
2560                        @function get_cities
2561                        @abstract Echos a serialized array containing all the cities of a given state
2562                        @author Raphael Derosso Pereira
2563
2564                        @param $id_country The ID of the Country that has the specified Cities (in case the
2565                                Country doesn't have any States)
2566                        @param $id_state The ID of the State that has the Cities requested
2567
2568                */
2569                function get_cities($id_country, $id_state=false)
2570                {
2571                        $cities = $this->bo->catalog->get_all_cities($id_country, $id_state);
2572
2573                        if (!$cities)
2574                        {
2575                                $result = array(
2576                                        'msg'    => lang('No Cities found for this State.'),
2577                                        'status' => 'empty'
2578                                );
2579
2580                                echo serialize($result);
2581                                return;
2582                        }
2583                       
2584                        $result = array(
2585                                'msg'    => lang('Cities Successfully retrieved!'),
2586                                'status' => 'ok'
2587                        );
2588                       
2589                        foreach ($cities as $city_info)
2590                        {
2591                                $result['data'][$city_info['id_city']] = $city_info['name'];
2592                        }
2593                       
2594                        echo serialize($result);
2595                }
2596
2597
2598                /*!
2599               
2600                        @function search
2601                        @abstract Echos a serialized array containing the IDs
2602                                of the entries that matches the search argument
2603                        @author Raphael Derosso Pereira
2604                        @author Mário César Kolling (external catalogs)
2605
2606                        @param string $str_data A serialized array with two informations:
2607                                $data = array(
2608                                        'search_for' => (string),
2609                                        'recursive'  => (boolean),
2610                                );
2611
2612                */
2613                // SERPRO
2614                function search($str_data)
2615                {
2616                        $data = unserialize($str_data);
2617                        // It's an external catalog?
2618                        $external = $this->bo->is_external($this->page_info['actual_catalog']);
2619                       
2620            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
2621            {
2622                echo serialize(array(                                                                                                   
2623                   'msg'    => lang('Invalid parameters'),                                                                             
2624                    'status' => 'abort'
2625                ));
2626           
2627                return array('error' => lang('Invalid parameters'));                                                                                                                 
2628            }   
2629
2630           
2631                        /*
2632                         * TODO: look into the database to discover the database's encoding and convert the search_for field accordingly
2633                         */
2634                        // Support search parameters with accentuation
2635                        if ($this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
2636                                $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
2637                                $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
2638                                $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
2639                        {
2640
2641                                $data['search_for'] = utf8_encode($data['search_for']);
2642                        }
2643           
2644            $rules  = array();                                                                                                         
2645           
2646           
2647            if ($data['search_for'] === '*')                                                                                           
2648            {
2649                $rules = array(                                                                                                         
2650                    0 => array(                                                                                                         
2651                        'field' => $data['fields']['search'],                                                                           
2652                        'type'  => 'LIKE',
2653                        'value' => '%'
2654                    )   
2655                ); 
2656            }   
2657            else                                                                                                                       
2658            {
2659                $names = explode(' ', $data['search_for']);                                                                             
2660               
2661                if (!is_array($names))                                                                                                 
2662                {
2663                    echo serialize(array(                                                                                               
2664                        'msg'    => lang('Invalid Search Parameter'),                                                                   
2665                        'status' => 'abort'
2666                    ));
2667 
2668                }
2669
2670                                if (!$external && $this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
2671                                        $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
2672                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&                                   
2673                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager' )
2674                                {
2675                                        /*
2676                                         * Restrict the returned contacts search to objectClass = phpgwAccount,
2677                                         * must have attibute phpgwAccountStatus, phpgwAccountVisible != -1
2678                                         */
2679                                        $rules = array(
2680                                                0 => array(
2681                                                        'field' => 'contact.object_class',
2682                                                        'type'  => '=',
2683                                                        'value' => 'phpgwAccount'
2684                                                ),
2685                                                1 => array(
2686                                                        'field' => 'contact.account_status',
2687                                                        'type'  => 'iLIKE',
2688                                                        'value' => '%'
2689                                                ),
2690                                                2 => array(
2691                                                        'field' => 'contact.account_visible',
2692                                                        'type'  => '!=',
2693                                                        'value' => '-1'
2694                                                ),
2695                                        );
2696                                }
2697               
2698                foreach ($names as $name)
2699                {
2700                    if ($name != '')
2701                    {
2702                        array_push($rules, array(
2703                            'field' => $data['fields']['search'],
2704                            'type'  => 'iLIKE',
2705                            'value' => '%'.$name.'%'
2706                        ));
2707                    }
2708                }
2709            }
2710
2711                        if ($external || $this->page_info['actual_catalog']['class'] == 'bo_people_catalog' ||
2712                                $this->page_info['actual_catalog']['class'] == 'bo_group_manager' ||
2713                                $this->page_info['actual_catalog']['class'] == 'bo_shared_people_manager' ||
2714                                $this->page_info['actual_catalog']['class'] == 'bo_shared_group_manager'        )
2715                        {
2716                                // Get only this attributes: dn, cn for external catalogs,
2717                                // used to restrict the attributes used in filters
2718                                $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
2719                        }
2720                        else
2721                        {
2722                                // Get only this attributes: dn, cn, phpgwAccountType, objectClass, phpgwAccountStatus, phpghAccountVisible
2723                                // for non-external catalogs, used to restrict the attributes used in filters
2724                                $ids = $this->bo->find(array(
2725                                        $data['fields']['id'],
2726                                        $data['fields']['search'],
2727                                        'contact.object_class',
2728                                        //'contact.account_status',
2729                                        'contact.account_visible'
2730                                        ), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
2731                        }
2732
2733            if (!is_array($ids) || !count($ids))
2734            {
2735                                $this->last_search_ids = null;
2736                                $this->save_session();
2737                                return null;
2738            }
2739
2740            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
2741                       
2742            $ids_f = array();
2743
2744            foreach ($ids as $e_info)
2745            {
2746                                if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
2747                        $ids_f[] = $e_info[$id_field];
2748                else
2749                        $ids_f[] = array(0=>$e_info[$id_field],1=>$e_info['perms']);
2750            }
2751
2752                        return $ids_f;
2753                }
2754               
2755                // CELEPAR
2756                /*
2757        function search($str_data)
2758        {
2759            $data = unserialize($str_data);
2760
2761            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
2762            {
2763                echo serialize(array(
2764                    'msg'    => lang('Invalid parameters'),
2765                    'status' => 'abort'
2766                ));
2767
2768                return;
2769            }
2770
2771            $rules  = array();
2772
2773            if ($data['search_for'] === '*')
2774            {
2775                $rules = array(
2776                    0 => array(
2777                        'field' => $data['fields']['search'],
2778                        'type'  => 'LIKE',
2779                        'value' => '%'
2780                    )
2781                );
2782            }
2783            else
2784            {
2785                $names = explode(' ', $data['search_for']);
2786
2787                if (!is_array($names))
2788                {
2789                    echo serialize(array(
2790                        'msg'    => lang('Invalid Search Parameter'),
2791                        'status' => 'abort'
2792                    ));
2793                   
2794                    return;
2795                }
2796               
2797                foreach ($names as $name)
2798                {
2799                    if ($name != '')
2800                    {
2801                        array_push($rules, array(
2802                            'field' => $data['fields']['search'],
2803                            'type'  => 'iLIKE',
2804                            'value' => '%'.$name.'%'
2805                        ));
2806                    }
2807                }
2808            }
2809
2810           
2811           
2812            //$catalog = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
2813           
2814            //if ($catalog['class'] === 'bo_people_catalog')
2815            //{
2816            //    array_push($rules, array(
2817            //        'field' => 'contact.id_owner',
2818            //        'type'  => '=',
2819            //        'value' => $GLOBALS['phpgw_info']['user']['account_id']
2820            //    ));
2821            //}
2822           
2823           
2824            $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
2825
2826            if (!is_array($ids) || !count($ids))
2827            {
2828                echo serialize(array(
2829                    'msg'    => lang('No Entries Found!'),
2830                    'status' => 'empty'
2831                ));
2832
2833                return;
2834            }
2835            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
2836
2837            $ids_f = array();
2838            foreach ($ids as $e_info)
2839            {
2840                $ids_f[] = $e_info[$id_field];
2841            }
2842
2843            echo serialize(array(
2844                'data'   => $ids_f,
2845                'msg'    => lang('Found %1 Entries', count($ids)),
2846                'status' => 'ok'
2847            ));
2848                       
2849                        return;
2850        }*/
2851                /*!
2852
2853                        @function get_multiple_entries
2854                        @abstract Returns an array containing the specifiend data in the default
2855                                CC UI format
2856                        @author Raphael Derosso Pereira
2857
2858                        @param array str_data A serialized array containing the ID's of the entries
2859                                to be taken, the fields to be taken and the rules to be used on the
2860                                retrieval:
2861                                $data = array(
2862                                        'ids'    => array(...),
2863                                        'fields' => array(...),
2864                                        'rules'  => array(...)
2865                                );
2866
2867                */
2868                function get_multiple_entries($str_data)
2869                {
2870                        $data = unserialize($str_data);
2871                       
2872                        if (!is_array($data) or !count($data) or !count($data['fields']) or !count($data['ids']))
2873                        {
2874                                return array(
2875                                        'msg'    => lang('Invalid Parameters'),
2876                                        'status' => 'abort'
2877                                );
2878                        }
2879
2880                        $entries = $this->bo->catalog->get_multiple_entries($data['ids'], $data['fields']);
2881                       
2882                        if (!is_array($entries) or !count($entries))
2883                        {
2884                                return array(
2885                                        'msg'    => lang('No Entries Found!'),
2886                                        'status' => 'empty'
2887                                );
2888                        }
2889
2890                        return array(
2891                                'msg'    => lang('Found %1 Entries!', count($entries)),
2892                                'status' => 'ok',
2893                                'data'   => $entries
2894                        );
2895                }
2896
2897                /*
2898
2899                        @function get_all_entries
2900                        @abstract Returns the specified fields for all catalog's entries
2901                                in the default CC UI format
2902                        @author Raphael Derosso Pereira
2903
2904                        @params array str_data A serialized array containing the fields to
2905                                be grabbed, the maximum number of entries to be returned and a
2906                                boolean specifying if the calls refers to a new grab or to an
2907                                unfinished one.
2908
2909                */
2910                function get_all_entries($str_data)
2911                {
2912                        $data = unserialize($str_data);
2913                       
2914                        if (!is_array($data) or
2915                            !count($data) or
2916                                !count($data['fields']) or
2917                                !$data['maxlength'] or
2918                                (!$data['new'] and !$data['offset']))
2919                        {
2920                                return array(
2921                                        'msg'    => lang('Invalid Parameters'),
2922                                        'status' => 'abort'
2923                                );
2924                        }
2925
2926                        if ($data['new'])
2927                        {
2928                                $this->all_entries = $this->bo->catalog->get_all_entries_ids();
2929
2930                                $this->save_session();
2931
2932                                if (!is_array($this->all_entries) or !count($this->all_entries))
2933                                {
2934                                        return array(
2935                                                'msg'    => lang('No Entries Found!'),
2936                                                'status' => 'empty'
2937                                        );
2938                                }
2939
2940                                $data['offset'] = 0;
2941                        }
2942                       
2943                        if ($data['maxlength'] != -1)
2944                        {
2945                                $result = $this->bo->catalog->get_multiple_entries(array_slice($this->all_entries, $data['offset'], $data['maxlength']), $data['fields']);
2946                        }
2947                        else
2948                        {
2949                                $result = $this->bo->catalog->get_multiple_entries($this->all_entries, $data['fields']);
2950                        }
2951
2952                        $prefs = ExecMethod('contactcenter.ui_preferences.get_preferences');
2953                       
2954                        $jsCode = array();
2955                        $count = 0;
2956                        foreach ($result as $each)
2957                        {
2958                                if (!is_array($each))
2959                                {
2960                                        continue;
2961                                }
2962
2963                                if($this-> typeContact == 'groups') {                           
2964                                       
2965                                        foreach ($each as $field => $value)     {
2966                                                                               
2967                                                if ($field === 'title') {
2968                                                        $optionName = '\\"'.$value.'\\"';
2969                                                         
2970                                                }
2971                                                else if ($field === 'short_name')       {
2972                                                       
2973                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$optionName.' ('.$value.')", "'.$count.'");';
2974                                                        $count++;                                                                                                                                                                       
2975                                                }                                       
2976                                        }
2977                                }
2978                               
2979                                else  {
2980                                        foreach ($each as $field => $value)     {
2981                                                if ($field === 'names_ordered') {
2982                                                         if(is_array($value))
2983                                $value = $value[0];
2984                                                        $name = '\\"'.$value.'\\"';
2985                                                }
2986                                                else if ($field === 'connections')      {
2987                                                       
2988                                                        foreach ($value as $connection)         {
2989                                                                if ($connection['id_type'] == $prefs['personCardEmail'])        {
2990                                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$name.' <'.$connection['connection_value'].'>", "'.$count.'");';
2991                                                                        $count++;
2992                                                                }
2993                                                        }
2994                                                }
2995                                        }
2996                                }
2997                        }
2998
2999                        $jsCodeFinal = implode("\n", $jsCode);
3000                       
3001                        $nEntries = count($result);
3002                       
3003                        if (!$nEntries)
3004                        {
3005                                return array(
3006                                        'msg'    => lang('Error while getting user information...'),
3007                                        'status' => 'abort'
3008                                );
3009                        }
3010
3011                        return array(
3012                                'msg'      => lang('Found %1 Entries!', $nEntries),
3013                                'status'   => 'ok',
3014                                'typeContact'   => $this -> typeContact,
3015                                'final'    => $nEntries + $data['offset'] < count($this->all_entries) ? false : true,
3016                                'offset'   => $data['offset'] + $nEntries,
3017                                'data'     => $jsCodeFinal
3018                        );
3019                }
3020               
3021                /*********************************************************************\
3022                 *                      Auxiliar Methods                             *
3023                \*********************************************************************/
3024
3025                /*!
3026               
3027                        @function save_session
3028                        @abstract Saves the data on the session
3029                        @author Raphael Derosso Pereira
3030               
3031                */
3032                function save_session()
3033                {
3034                        $GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter',$this->page_info);
3035                        $GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter',$this->all_entries);
3036                }
3037
3038                /*!
3039               
3040                        @function convert_tree
3041                        @abstract Converts the tree array in the BO format to a JS tree array compatible
3042                                with the one available in eGW
3043                        @author Raphael Derosso Pereira
3044               
3045                        @param (array)  $tree    The tree in the BO format
3046                        @param (string) $name    The tree name
3047                        @param (string) $iconDir The dir where the icons are
3048                        @param (string) $parent  The parent
3049                */
3050
3051                function convert_tree($tree, &$iconDir, $parent='0')
3052                {
3053//                      echo "Entrou<br>\tPai: $parent <br>";
3054                        $rtree = array();
3055
3056                        if ($parent === '0')
3057                        {
3058//                              echo 'Root!<br>';
3059                                $rtree['0'] = array(
3060                                        'type'       => 'catalog_group',
3061                                        'id'         => '0',
3062                                        'pid'        => 'none',
3063                                        'caption'    => lang('Catalogues'),
3064                                        'class'      => 'bo_catalog_group_catalog',
3065                                        'class_args' => array('_ROOT_', '$this', '$this->get_branch_by_level($this->catalog_level[0])')
3066                                );
3067                        }
3068
3069                        foreach($tree as $id => $value)
3070                        {
3071//                              echo 'ID: '.$id.'<br>';
3072                                $rtree[$parent.'.'.$id] = array(
3073                                        'type'    => $value['type'],
3074                                        'id'      => $parent.'.'.$id,
3075                                        'pid'     => $parent,
3076                                        'caption' => $value['name']
3077                                );
3078                               
3079                                switch($value['type'])
3080                                {
3081                                        case 'catalog_group':
3082                                        case 'mixed_catalog_group':
3083                                                $rtree = $rtree + $this->convert_tree($value['sub_branch'],$iconDir,$parent.'.'.$id);
3084                                                break;
3085                                }
3086                        }
3087
3088                        if (count($rtree))
3089                        {
3090                                return $rtree;
3091                        }
3092                }
3093
3094                function get_catalog_add_contact($id){
3095
3096                        $array_participants = array();
3097                        if(!$this->bo->catalog->src_info) {
3098                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3099                                $this->bo->catalog->src_info = $ldap->srcs[1];
3100                        }
3101                       
3102                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);                             
3103                        $dn=$this->bo->catalog->src_info['dn'];
3104                        $justThese = array("givenname","givenname","sn","telephonenumber","mail");
3105                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);                                                   
3106                        $info = ldap_get_entries($ds, $sr);                                                     
3107                        for($z = 0; $z < 5; $z++) {
3108                                $participant = $info[0][$justThese[$z]];                                                                                                       
3109                                array_push($array_participants, $participant);
3110                        }
3111
3112                        ldap_close($ds);
3113                        echo serialize($array_participants);
3114                }       
3115               
3116                function get_catalog_participants_group($id)
3117                {
3118                        if(!$this->bo->catalog->src_info) {
3119                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3120                                $this->bo->catalog->src_info = $ldap->srcs[1];
3121                        }                       
3122                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);                     
3123                        $justThese = array("description","memberuid");                 
3124                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);                                                   
3125                        $info = ldap_get_entries($ds, $sr);
3126                        $member_uids = $info[0]['memberuid'];
3127                        $contact['names_ordered'] = $info[0]['description'];
3128                        $filter = "";                   
3129                        for($z = 0; $z < count($member_uids); $z++) {
3130                                if($member_uids[$z])
3131                                        $filter.="(uid=".$member_uids[$z].")"; 
3132                        }
3133                        $array_participants = array();
3134                        if($filter) {
3135                                $filter = "(|".$filter.")";
3136                                $valarray = explode(',',$id);
3137                                array_shift($valarray);
3138                                $dn = implode(',',$valarray);
3139                                $justThese = array("cn","mail");
3140                                $sr = ldap_search($ds,$dn, $filter,$justThese);                                                         
3141                                $info = ldap_get_entries($ds, $sr);                                                     
3142                                for($z = 0; $z < $info['count']; $z++) {
3143                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3144                                        $array_emails[$info[$z]['mail'][0]] = null;                                                             
3145                                        array_push($array_participants, $participant);                                 
3146                                }
3147                                ldap_close($ds);
3148                        }                       
3149                        sort($array_participants);
3150                        $innerHTML = '';                       
3151                        foreach($array_participants as $index => $participant){
3152                                $innerHTML .= $participant;
3153                        }
3154                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);                 
3155                        echo serialize($return);
3156                }
3157
3158                function get_catalog_participants_list($id)
3159                {
3160                       
3161                        $fields = $this->bo->catalog->get_fields(false);                       
3162                        $fields['names_ordered'] = true;
3163                        $fields['mail_forwarding_address'] = true;                     
3164                        $contact = $this->bo->catalog->get_single_entry($id,$fields);                   
3165                       
3166                        $array_participants = array();
3167                        $array_emails = array();
3168
3169                        $filter = null;
3170                        for($z = 0; $z < $contact['mail_forwarding_address']['count']; $z++) {                 
3171                                        if(strstr($contact['mail_forwarding_address'][$z],'@')) {
3172                                                $filter.="(mail=".$contact['mail_forwarding_address'][$z].")";
3173                                                $array_emails[$contact['mail_forwarding_address'][$z]] = "<font color=black>".$contact['mail_forwarding_address'][$z]."</font>";
3174                                        }                                                                                                                               
3175                                        else
3176                                                $array_participants[$z] = "<font color=red>".$contact['mail_forwarding_address'][$z]."</font>";
3177                        }                                       
3178                       
3179                        if($filter) {
3180                                $filter = "(|".$filter.")";                                                     
3181                                if(!$this->bo->catalog->src_info) {
3182                                        $ldap = CreateObject('contactcenter.bo_ldap_manager');
3183                                        $this->bo->catalog->src_info = $ldap->srcs[1];
3184                                }
3185                                $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3186                               
3187                                $dn=$this->bo->catalog->src_info['dn'];
3188                                $justThese = array("cn","mail");
3189                                $sr = ldap_search($ds,$dn, $filter,$justThese);                                                         
3190                                $info = ldap_get_entries($ds, $sr);                                                     
3191                                for($z = 0; $z < $info['count']; $z++) {
3192                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3193                                        $array_emails[$info[$z]['mail'][0]] = null;                                                             
3194                                        array_push($array_participants, $participant);                                 
3195                                }
3196                               
3197                                foreach($array_emails as $index => $email)
3198                                        if($email)
3199                                                array_push($array_participants, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$email."<br>");                         
3200                                                                                               
3201                                ldap_close($ds);
3202                        }
3203                        sort($array_participants);
3204                        $innerHTML = '';                       
3205                        foreach($array_participants as $index => $participant){
3206                                $innerHTML .= $participant;
3207                        }
3208                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);                 
3209                        echo serialize($return);
3210                }       
3211               
3212                function export_contacts($typeExport){
3213
3214                        $boGroup = CreateObject('contactcenter.bo_group');
3215                        $contacts = $boGroup->get_all_contacts();
3216                        $streamBuffer = '';
3217
3218                        if(!count($contacts))
3219                                echo null;
3220                       
3221                        switch($typeExport) {
3222
3223                                case 'outlook_en':
3224                                        $streamBuffer = "Name;E-mail Address;Notes;Mobile Phone;Pager;Company;".
3225                                                        "Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";                                                       
3226                                        foreach($contacts as $index => $object){
3227                                                $streamBuffer.= $object['names_ordered'].";".$object['connection_value'].";;;;;;".$object['phone'].";;;\r\n";
3228                                        }
3229                                break;
3230                               
3231                                case 'outlook_pt-BR':
3232                                        $streamBuffer = "Nome;End. de email;Endereço residencial;".
3233                                        "Cidade do endereço residencial;CEP do endereço residencial;".
3234                                        "Estado;País/região do endereço residencial;Telefone residencial;".
3235                                        "Rua do endereço comercial;Cidade do endereço comercial;".
3236                                        "CEP do endereço comercial;Estado do endereço comercial;".
3237                                        "País/região do endereço comercial;Telefone comercial;Empresa;Cargo\r\n";                                                       
3238                                        foreach($contacts as $index => $object){
3239                                                $streamBuffer.= $object['names_ordered'].";".$object['connection_value'].";;;;;;".$object['phone'].";;;;;;;;\r\n";
3240                                        }
3241                                break;
3242                               
3243                                case 'outlook2000_pt-BR':
3244                                        $streamBuffer = "\"Tratamento\",\"Nome\",\"Segundo Nome\",\"Sobrenome\",\"Sufixo\",".
3245                                        "\"Empresa\",\"Departamento\",\"Cargo\",\"Rua do endereço comercial\",\"Rua do endereço comercial 2\",".
3246                                        "\"Rua do endereço comercial 3\",\"Cidade do endereço comercial\",\"Estado do endereço comercial\",".
3247                                        "\"CEP do endereço comercial\",\"País do endereço comercial\",\"Endereço residencial\",\"Rua residencial 2\",".
3248                                        "\"Rua residencial 3\",\"Cidade do endereço residencial\",\"Estado\",\"CEP do endereço residencial\",\"País do endereço residencial\",".
3249                                        "\"Outro endereço\",\"Outro endereço 2\",\"Outro endereço 3\",\"Cidade\",\"Estado\",\"CEP\",\"País\",".
3250                                        "\"Telefone do assistente\",\"Fax comercial\",\"Telefone comercial\",\"Telefone comercial 2\",\"Retorno de chamada\",".
3251                                        "\"Telefone do carro\",\"Telefone principal da empresa\",\"Fax residencial\",\"Telefone residencial\",".
3252                                        "\"Telefone residencial 2\",\"ISDN\",\"Telefone celular\",\"Outro fax\",\"Outro telefone\",\"Pager\",\"Telefone principal\",".
3253                                        "\"Radiofone\",\"Telefone TTY/TDD\",\"Telex\",\"Aniversário\",\"Anotações\",\"Caixa postal\",\"Categorias\",".
3254                                        "\"Código da empresa\",\"Código do governo\",\"Cônjuge\",\"Conta\",\"Endereço de correio eletrônico\",".
3255                                        "\"Nome de exibição do correio eletr.\",\"Endereço de correio eletrônico 2\",".
3256                                        "\"Nome de exibição do correio eletr.2\",\"Endereço de correio eletrônico 3\",".
3257                                        "\"Nome de exibição do correio eletr.3\",\"Datas especiais\",\"Disponibilidade da Internet\",".
3258                                        "\"Filhos\",\"Hobby\",\"Idioma\",\"Indicação\",\"Informações para cobrança\",\"Iniciais\",\"Local\",".
3259                                        "\"Nome do assistente\",\"Nome do gerenciador\",\"Página da Web\",\"Palavras-chave\",\"Particular\",\"Personalizado 1\",\"Personalizado 2\",".
3260                                        "\"Personalizado 3\",\"Personalizado 4\",\"Prioridade\",\"Profissão\",\"Quilometragem\",\"Sala\",\"Sensibilidade\",\"Servidor de diretório\",".
3261                                        "\"Sexo\"\r\n";
3262                                        foreach($contacts as $index => $object){
3263                                                $streamBuffer.= ",\"".$object['names_ordered']."\",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,".$object['phone'].",,,,,,,,,,,,\"".$object['connection_value']."\",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3264                                        }
3265                                break;
3266                               
3267                                case 'outlook2000_en':
3268                                        $streamBuffer = "Title,First Name,Middle Name,Last Name,Suffix,Company,Department,Job Title,".
3269                                        "Business Street,Business Street 2,Business Street 3,Business City,Business State,Business Postal Code,".
3270                                        "Business Country,Home Street,Home Street 2,Home Street 3,Home City,Home State,Home Postal Code,Home Country,".
3271                                        "Other Street,Other Street 2,Other Street 3,Other City,Other State,Other Postal Code,Other Country,".
3272                                        "Assistant's Phone,Business Fax,Business Phone,Business Phone 2,Callback,Car Phone,Company Main Phone,Home Fax,".
3273                                        "Home Phone,Home Phone 2,ISDN,Mobile Phone,Other Fax,Other Phone,Pager,Primary Phone,Radio Phone,TTY/TDD Phone,Telex,".
3274                                        "Account,Anniversary,Assistant's Name,Billing Information,Birthday,Categories,Children,Directory Server,E-mail Address,".
3275                                        "E-mail Type,E-mail Display Name,E-mail 2 Address,E-mail 2 Type,E-mail 2 Display Name,E-mail 3 Address,E-mail 3 Type,E-mail 3 Display Name,".
3276                                        "Gender,Government ID Number,Hobby,Initials,Internet Free Busy,Keywords,Language,Location,Manager's Name,Mileage,Notes,".
3277                                        "Office Location,Organizational ID Number,PO Box,Priority,Private,Profession,Referred By,Sensitivity,Spouse,User 1,User 2,User 3,User 4,Web Page\r\n";
3278                                        foreach($contacts as $index => $object){
3279                                                $streamBuffer.= ",".$object['names_ordered'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,".$object['phone'].",,,,,,,,,,,,".$object['connection_value'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3280                                        }
3281                                break;
3282                                       
3283                                case 'thunderbird':
3284                                        $streamBuffer = "\n";                                                   
3285                                        foreach($contacts as $index => $object){
3286                                                $streamBuffer.= ",,".$object['names_ordered'].",,".$object['connection_value'].",,".$object['phone'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3287                                        }
3288                                break;
3289                               
3290                                case 'expresso':
3291                                        $streamBuffer = "Nome,Email,Telefone\r\n";
3292                                        foreach($contacts as $index => $object){
3293                                                $streamBuffer.= $object['names_ordered'].",".$object['connection_value'].",".$object['phone']."\r\n";
3294                                        }
3295                                break;
3296                               
3297                        }
3298
3299                        $file = "contacts_".md5(microtime()).".swp";
3300                        $tempDir = ini_get("session.save_path");
3301                        $f = fopen($tempDir.'/'.$file,"w");
3302                        if(!$f)
3303                                echo null;
3304               
3305                        fputs($f,$streamBuffer);
3306                        fclose($f);
3307
3308                        echo $tempDir.'/'.$file;
3309                }
3310
3311                // Get the csv field and put into array, from php.net
3312                function parse_line($input_text, $delimiter = ',', $text_qualifier = '"') {
3313                        $text = trim($input_text);
3314                          if(is_string($delimiter) && is_string($text_qualifier)) {
3315                         $re_d = '\x' . dechex(ord($delimiter));            //format for regexp
3316                        $re_tq = '\x' . dechex(ord($text_qualifier));    //format for regexp
3317                       
3318                        $fields = array();
3319                        $field_num = 0;
3320                        while(strlen($text) > 0) {
3321                        if($text{0} == $text_qualifier) {
3322                                preg_match('/^' . $re_tq . '((?:[^' . $re_tq . ']|(?<=\x5c)' . $re_tq . ')*)' . $re_tq . $re_d . '?(.*)$/', $text, $matches);
3323                               
3324                                $value = str_replace('\\' . $text_qualifier, $text_qualifier, $matches[1]);
3325                                $text = trim($matches[2]);
3326               
3327                                $fields[$field_num++] = $value;
3328                        } else {
3329                                preg_match('/^([^' . $re_d . ']*)' . $re_d . '?(.*)$/', $text, $matches);
3330                               
3331                                $value = $matches[1];
3332                                $text = trim($matches[2]);
3333               
3334                                $fields[$field_num++] = $value;
3335                }
3336                }
3337                        return $fields;
3338                    } else
3339                        return false;
3340                }
3341
3342                function import_contacts($typeImport){
3343
3344                        if($file = $_SESSION['contactcenter']['importCSV']) {                           
3345                                unset($_SESSION['contactcenter']['importCSV']);                         
3346                                $len = filesize($file);
3347                                $count = 0;
3348                                $return = array('error' => false, '_new' => 0, '_existing' => 0, '_failure' => 0);
3349                                $handle = @fopen($file, "r") or die(serialize($return['error'] = true));
3350                               
3351                                $input_header = fgets($handle);
3352                                if ($typeImport == 'outlook')
3353                                        $delim = ';';
3354                                else if ($typeImport == 'auto')
3355                                $delim = strstr($input_header,',') ? ',' : ';';
3356                                else 
3357                                        $delim = ',';
3358                                $csv_header = $this->parse_line($input_header,$delim);
3359                                $firstContact = fgets($handle);
3360                                preg_match("/\"(.+)\"[,;]/sU",$firstContact,$matches); // yahoo csv
3361                                rewind($handle);                               
3362
3363                                $header = @fgetcsv($handle, $len, $delim) or die(serialize($return['error'] = true));
3364                                if(count($header)  < 2 || count($header) > 100) {
3365                                        $return['error'] = true;
3366                                        $return['sizeheader'] = count($header);
3367                                        echo serialize($return);
3368                                        return;
3369                                }
3370                               
3371                                if ($matches[0][strlen($matches[0])-1] == ';')
3372                                        $delim = ';';
3373                               
3374                        $boGroup = CreateObject('contactcenter.bo_group');
3375                        $boPeople = CreateObject('contactcenter.bo_people_catalog');
3376                                switch($typeImport){
3377                                        case 'outlook2000':
3378                                                $name_pos=1;
3379                                                $email_pos=56;
3380                                                $phone_pos=44;
3381                                                break;
3382                                        case 'outlook':
3383                                                $name_pos=0;
3384                                                $email_pos=1;
3385                                                $phone_pos=7;
3386                                                break;
3387                                        case 'thunderbird':
3388                                                $name_pos=2;
3389                                                $email_pos=4;
3390                                                $phone_pos=7;
3391                                                break;
3392                                        case 'expresso':
3393                                                $name_pos=0;
3394                                                $email_pos=1;
3395                                                $phone_pos=2;
3396                                                break;
3397                                        default:
3398                                                foreach($csv_header as $index => $fieldName)
3399                                                {
3400                                                        switch(strtoupper($fieldName)){
3401                                                        case 'NAME':
3402                                                        case 'NOME':
3403                                                        case 'FIRST NAME':
3404                                                                $name_pos = $index;
3405                                                                break;
3406                                                        case 'E-MAIL':
3407                                                        case 'EMAIL':
3408                                                        case 'E-MAIL ADDRESS':
3409                                                        case 'ENDEREÇO DE CORREIO ELETRÔNICO':
3410                                                        case 'END. DE EMAIL':
3411                                                                $email_pos = $index;
3412                                                                break;
3413                                                        case 'HOME PHONE':
3414                                                        case 'PHONE':
3415                                                        case 'TELEFONE':
3416                                                        case 'TELEFONE PRINCIPAL':
3417                                                        case 'TELEFONE COMERCIAL':
3418                                                                $phone_pos = $index;
3419                                                                break;
3420                                                        }
3421                                                }
3422                                                break;
3423                                }
3424                               
3425
3426                                while (($data = fgetcsv($handle, $len, $delim))) {
3427                                foreach ($header as $key=>$heading)
3428                                $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
3429                               
3430                                        $sdata = array();
3431                                        $full_name  = trim($row[$header[$name_pos]]);
3432                                        $email          = trim($row[$header[$email_pos]]);
3433                                        $phone          = trim($row[$header[$phone_pos]]);
3434                                        $array_name = explode(' ', str_replace('"','',(str_replace('\'','',$full_name))));
3435                                        $sdata['given_names'] = $array_name[0];
3436                                        $array_name[0] = null;
3437                                        $sdata['family_names'] = trim(implode(' ',$array_name));
3438                                        $sdata['connections']['default_email']['connection_name'] = lang('Main');
3439                                        $sdata['connections']['default_email']['connection_value'] = $email;
3440
3441                                        $sdata['connections']['default_phone']['connection_name'] = lang('Main');
3442                                        $sdata['connections']['default_phone']['connection_value'] = $phone;
3443                                        $sdata['is_quick_add'] = true;
3444                                       
3445                                        //      verifica se email já existe!
3446                                        $contact = $boGroup->verify_contact($email);
3447                                                                               
3448                                        if(!$sdata['given_names'] && $email){
3449                                                        $a_email = explode("@",$email);
3450                                                        $sdata['given_names'] = $a_email[0];
3451                                        }
3452
3453                                        $line_iteration = $return['_failure'] + $return['_existing'] + $return['_new'];
3454                                        if($contact){
3455                                                $return['_existing']++;
3456                                        }                                                                                                               
3457                                        else if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
3458                                                $return['_failure']++;
3459                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid E-Mail address: " . $email ."<br>";
3460                                        }
3461                                        else if (!$sdata['given_names'] || !$email || !$boPeople ->quick_add($sdata)){
3462                                                $return['_failure']++;                                                 
3463                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid Name: " . $sdata['given_names'] ."<br>";
3464                                        }
3465                                        else
3466                                                $return['_new']++;
3467                        }                               
3468                                fclose($handle);
3469                                unlink($file);
3470                        }
3471                        else
3472                                $return['error'] = true;
3473
3474                        echo serialize($return);
3475                }
3476/*
3477                function convert_tree($tree, $name, &$iconDir, $parent='0')
3478                {
3479                        $new = null;
3480                        $code = null;
3481                       
3482                        if ($parent === '0')
3483                        {
3484
3485                                $code .= $name.".add(new dNode({id:'0', caption: '".lang('Catalogues')."'}),'none');\n";
3486                        }
3487                       
3488                        foreach ($tree as $id => $value)
3489                        {
3490                                $title = $value['name'];
3491
3492                                switch ($value['type'])
3493                                {                                       
3494                                        case 'unknown':
3495                                                $code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption:'{$value['name']}', onFirstOpen: 'getCatalogTree(\\'{$parent}.{$id}\\');', onClick: 'getCatalogTree(\\'{$parent}.{$id}\\'); waitForTree(\\'{$parent}.{$id}\\', 0)'}),'$parent');\n";
3496                                                break;
3497                                       
3498                                        case 'catalog_group':
3499                                                $code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}'}),'$parent');\n";
3500                                                $code .= $this->convert_tree($value['sub_branch'],$name,$iconDir,$parent.'.'.$id);
3501                                                break;
3502
3503                                        case 'mixed_catalog_group':
3504                                                $code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}', onClick: 'setCatalog(\\'{$parent}.{$id}\\')'}),'$parent');\n";
3505
3506                                                $code .= $this->convert_tree($value['sub_branch'],$name,$iconDir,$parent.'.'.$id);
3507                                                break;
3508                                       
3509                                        case 'catalog':
3510                                                $code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}', onClick: 'setCatalog(\\'{$parent}.{$id}\\')'}),'$parent');\n";
3511                                               
3512                                }
3513                        }
3514                       
3515                        return $code;
3516                }
3517*/
3518        }
3519
3520?>
Note: See TracBrowser for help on using the repository browser.