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

Revision 1650, 116.1 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #611 - Adicionada a chamada do unescape para apresentacao dos dados na tela

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