source: branches/2.2/contactcenter/inc/class.ui_data.inc.php @ 3211

Revision 3211, 116.4 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1185 - Corrigido erro ao listar OU com muitos objetos dentro do Catálogo Geral.

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