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

Revision 1599, 116.1 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #719 - Adicionados campos para importacao de contatos no Outlook Express

  • 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                                                $value = urldecode( $value );
2087                                                /* Do Nothing. This is just to make sure no invalid field is passed */
2088                                                break;
2089
2090                                        case 'id_status':
2091                                        case 'id_prefix':
2092                                        case 'id_suffix':
2093                                                if ($data[$field] == 0)
2094                                                {
2095                                                        unset($data[$field]);
2096                                                }
2097                                                break;
2098
2099                                        case 'birthdate_0':
2100                                        case 'birthdate_1':
2101                                        case 'birthdate_2':
2102
2103                                                switch($date[$datecount]['digit'])
2104                                                {
2105                                                        case 'Y':
2106                                                                $date['value'][2] = (int) $data[$field];
2107                                                                break;
2108
2109                                                        case 'M':
2110                                                                $date['value'][0] = (int) $data[$field];
2111                                                                break;
2112
2113                                                        case 'D':
2114                                                                $date['value'][1] = (int) $data[$field];
2115                                                                break;
2116                                                }
2117                                                unset($data[$field]);
2118                                                $datecount++;
2119
2120                                                if ($datecount != 3)
2121                                                {
2122                                                        break;
2123                                                }
2124
2125                                                if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
2126                                                {
2127                                                        echo serialize(array(
2128                                                                'msg' => lang('Invalid Date'),
2129                                                                'status' => 'invalid_data'
2130                                                        ));
2131                                                        return;
2132                                                }
2133
2134                                                $data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
2135                                                break;
2136
2137                                        case 'sex':
2138                                                if ($data[$field] !== 'M' and $data[$field] !== 'F')
2139                                                {
2140                                                        echo serialize(array(
2141                                                                'msg' => lang('Invalid Sex'),
2142                                                                'status' => 'invalid_data'
2143                                                        ));
2144                                                        return;
2145                                                }
2146                                                break;
2147
2148
2149                                        case 'addresses':
2150                                                /* Insert new cities/states */
2151                                                if (isset($value['new_states']))
2152                                                {
2153                                                        foreach($value['new_states'] as $type => $state_info)
2154                                                        {
2155                                                                $index = 'address'.$type;
2156
2157                                                                $id_state = $this->bo->catalog->add_state($state_info);
2158                                                                $data['addresses'][$index]['id_state'] = $id_state;
2159
2160                                                                if ($value['new_cities'][$type])
2161                                                                {
2162                                                                        $value['new_cities'][$type]['id_state'] = $id_state;
2163                                                                }
2164                                                        }
2165
2166                                                        unset($data['addresses']['new_states']);
2167                                                }
2168
2169                                                if (isset($value['new_cities']))
2170                                                {
2171                                                        foreach($value['new_cities'] as $type => $city_info)
2172                                                        {
2173                                                                $index = 'address'.$type;
2174
2175                                                                $id_city = $this->bo->catalog->add_city($city_info);
2176                                                                $data['addresses'][$index]['id_city'] = $id_city;
2177                                                        }
2178
2179                                                        unset($data['addresses']['new_cities']);
2180                                                }
2181
2182                                        break;
2183
2184                                        case 'connections':
2185                                                /* Does nothing... */
2186                                                break;
2187
2188                                        default:
2189                                                echo serialize(array(
2190                                                        'msg' => lang('Invalid field: ').$field,
2191                                                        'status' => 'invalid_data'
2192                                                ));
2193                                                return;
2194                                }
2195                        }
2196
2197                        $code = '$id = $this->bo->catalog->';
2198
2199                        if (!is_null($id) and $id !== '')
2200                        {
2201                                $code .= $code.'update_single_info($id, $data);';
2202                                $result = array(
2203                                        'msg' => lang('Updated Successfully!'),
2204                                        'status' => 'ok'
2205                                );
2206                        }
2207                        else
2208                        {
2209                                $code .= 'add_single_entry($data);';
2210                                $result = array(
2211                                        'msg' => lang('Entry Added Successfully!'),
2212                                        'status' => 'ok'
2213                                );
2214                        }
2215
2216                        eval($code);
2217
2218                        if (!($id))
2219                        {
2220                                $result = array(
2221                                        'msg' => lang('Some problem occured when trying to insert/update contact information.<br>'.
2222                                                   'Report the problem to the Administrator.'),
2223                                        'status' => 'fail'
2224                                );
2225                        }
2226
2227                        echo serialize($result);
2228                }
2229
2230
2231                function post_full_add_shared()
2232                {
2233                        $data =  $_POST['data'];
2234                        // Exceptions!!! utf8 special chars.
2235                        $data = preg_replace("/\%u2(\d+)(\d+)(\d+)/","-",$data);
2236                        $data = unserialize(str_replace('\\"', '"', $data));
2237                        $this -> bo -> catalog = CreateObject('contactcenter.bo_shared_people_manager');
2238
2239                        if (!is_array($data))
2240                        {
2241                                echo serialize(array(
2242                                        'msg' => lang('<p>Some problem receiving data from browser. This is probably a bug in ContactCenter<br>'.
2243                                                  'Please go to eGroupWare Bug Reporting page and report this bug.<br>'.
2244                                                          'Sorry for the inconvenient!<br><br>'.
2245                                                          '<b><i>ContactCenter Developer Team</i></b></p>'),
2246                                        'status' => 'fatal'
2247                                ));
2248                                return;
2249                        }
2250//                      print_r($data);
2251//                      echo '<br><br>';
2252
2253                        $replacer = $data['commercialAnd'];
2254                        unset($data['commercialAnd']);
2255                        if (!is_string($replacer) or strpos($replacer, "'") or strpos($replacer, '"'))
2256                        {
2257                                echo serialize(array(
2258                                        'msg' => lang('Invalid \'&\' replacer! This may be an attempt to bypass Security! Action aborted!'),
2259                                        'status' => 'fatal'
2260                                ));
2261
2262                                return;
2263                        }
2264
2265                        if ($data['id_contact'])
2266                        {
2267                                $id = $data['id_contact'];
2268                                $id_photo = $id;
2269                                unset($data['id_contact']);
2270                        }
2271                        else
2272                        {
2273                                $id_photo = '_new_';
2274                        }
2275
2276                        if ($data['owner'])
2277                        {
2278                                $owner = $data['owner'];
2279                                unset($data['owner']);
2280                        }
2281                        /*
2282                         * Process Photo, if available
2283                         */
2284                        $sleep_count = 0;
2285                        $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
2286                        while($photo_ok[0]{0} !== 'o' and $photo_ok[1]{0} === 'y')
2287                        {
2288                                sleep(1);
2289                                $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
2290                                $sleep_count++;
2291
2292                                if ($sleep_count > 35)
2293                                {
2294                                        // TODO
2295                                        return;
2296                                }
2297                        }
2298                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'n'));
2299
2300                        if (isset($this->page_info['photos'][$id_photo]))
2301                        {
2302                                if (array_search($this->page_info['photos'][$id_photo]['status'], array('changed', 'sync')) === false)
2303                                {
2304                                        echo serialize(array(
2305                                                'msg' => $this->page_info['photos'][$id_photo]['msg'],
2306                                                'status' => $this->page_info['photos'][$id_photo]['status']
2307                                        ));
2308
2309                                        return;
2310                                }
2311
2312                                $data['photo'] = $this->page_info['photos'][$id_photo]['content'];
2313                                unset($this->page_info['photos'][$id_photo]);
2314                                $this->save_session();
2315                        }
2316
2317                        /*
2318                         * Arrange Date so it gets inserted correctly
2319                         */
2320
2321                        $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
2322
2323                        $j = 0;
2324                        for ($i = 0; $i < 5; $i+=2)
2325                        {
2326                                switch($dateformat{$i})
2327                                {
2328                                        case 'Y':
2329                                                $date[$j]['size'] = 4;
2330                                                $date[$j]['digit'] = 'Y';
2331                                                break;
2332
2333                                        case 'm':
2334                                        case 'M':
2335                                                $date[$j]['size'] = 2;
2336                                                $date[$j]['digit'] = 'M';
2337                                                break;
2338
2339                                        case 'd':
2340                                                $date[$j]['size'] = 2;
2341                                                $date[$j]['digit'] = 'D';
2342                                }
2343                                $j++;
2344                        }
2345                        $datecount = 0;
2346
2347                        /* Verify Data and performs insertion/update */
2348                        foreach($data as $field => &$value)
2349                        {
2350                                if ($value == '' or is_null($value))
2351                                {
2352                                        unset($data[$field]);
2353                                        continue;
2354                                }
2355
2356                                switch($field)
2357                                {
2358                                        case 'alias':
2359                                        case 'given_names':
2360                                        case 'family_names':
2361                                        case 'names_ordered':
2362                                        case 'pgp_key':
2363                                        case 'notes':
2364                                        case 'photo':
2365                                                $value = urldecode( $value );
2366                                                /* Do Nothing. This is just to make sure no invalid field is passed */
2367                                                break;
2368
2369                                        case 'id_status':
2370                                        case 'id_prefix':
2371                                        case 'id_suffix':
2372                                                if ($data[$field] == 0)
2373                                                {
2374                                                        unset($data[$field]);
2375                                                }
2376                                                break;
2377
2378                                        case 'birthdate_0':
2379                                        case 'birthdate_1':
2380                                        case 'birthdate_2':
2381
2382                                                switch($date[$datecount]['digit'])
2383                                                {
2384                                                        case 'Y':
2385                                                                $date['value'][2] = (int) $data[$field];
2386                                                                break;
2387
2388                                                        case 'M':
2389                                                                $date['value'][0] = (int) $data[$field];
2390                                                                break;
2391
2392                                                        case 'D':
2393                                                                $date['value'][1] = (int) $data[$field];
2394                                                                break;
2395                                                }
2396                                                unset($data[$field]);
2397                                                $datecount++;
2398
2399                                                if ($datecount != 3)
2400                                                {
2401                                                        break;
2402                                                }
2403
2404                                                if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
2405                                                {
2406                                                        echo serialize(array(
2407                                                                'msg' => lang('Invalid Date'),
2408                                                                'status' => 'invalid_data'
2409                                                        ));
2410                                                        return;
2411                                                }
2412
2413                                                $data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
2414                                                break;
2415
2416                                        case 'sex':
2417                                                if ($data[$field] !== 'M' and $data[$field] !== 'F')
2418                                                {
2419                                                        echo serialize(array(
2420                                                                'msg' => lang('Invalid Sex'),
2421                                                                'status' => 'invalid_data'
2422                                                        ));
2423                                                        return;
2424                                                }
2425                                                break;
2426
2427
2428                                        case 'addresses':
2429                                                /* Insert new cities/states */
2430                                                if (isset($value['new_states']))
2431                                                {
2432                                                        foreach($value['new_states'] as $type => $state_info)
2433                                                        {
2434                                                                $index = 'address'.$type;
2435
2436                                                                $id_state = $this->bo->catalog->add_state($state_info);
2437                                                                $data['addresses'][$index]['id_state'] = $id_state;
2438
2439                                                                if ($value['new_cities'][$type])
2440                                                                {
2441                                                                        $value['new_cities'][$type]['id_state'] = $id_state;
2442                                                                }
2443                                                        }
2444
2445                                                        unset($data['addresses']['new_states']);
2446                                                }
2447
2448                                                if (isset($value['new_cities']))
2449                                                {
2450                                                        foreach($value['new_cities'] as $type => $city_info)
2451                                                        {
2452                                                                $index = 'address'.$type;
2453
2454                                                                $id_city = $this->bo->catalog->add_city($city_info);
2455                                                                $data['addresses'][$index]['id_city'] = $id_city;
2456                                                        }
2457
2458                                                        unset($data['addresses']['new_cities']);
2459                                                }
2460
2461                                        break;
2462
2463                                        case 'connections':
2464                                                /* Does nothing... */
2465                                                break;
2466
2467                                        default:
2468                                                echo serialize(array(
2469                                                        'msg' => lang('Invalid field: ').$field,
2470                                                        'status' => 'invalid_data'
2471                                                ));
2472                                                return;
2473                                }
2474                        }
2475
2476                        $code = '$id = $this->bo->catalog->';
2477
2478                        if (!is_null($id) and $id !== '')
2479                        {
2480                                $code .= $code.'update_single_info($id, $data);';
2481                                $result = array(
2482                                        'msg' => lang('Updated Successfully!'),
2483                                        'status' => 'ok'
2484                                );
2485                        }
2486                        else
2487                        {
2488                                $code .= 'add_single_entry($data,'.$owner.');';
2489                                $result = array(
2490                                        'msg' => lang('Entry Added Successfully!'),
2491                                        'status' => 'ok'
2492                                );
2493                        }
2494
2495                        eval($code);
2496
2497                        if (!($id))
2498                        {
2499                                $result = array(
2500                                        'msg' => lang('Some problem occured when trying to insert/update contact information.<br>'.
2501                                                   'Report the problem to the Administrator.'),
2502                                        'status' => 'fail'
2503                                );
2504                        }
2505
2506                        echo serialize($result);
2507}
2508                /*!
2509
2510                        @function post_photo
2511                        @abstract Wrapper to post a photo without reload a page.
2512                        @author Raphael Derosso Pereira
2513
2514                */
2515                function post_photo($id)
2516                {
2517                        //print_r($_FILES);
2518                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'y'));
2519
2520                        if (!is_array($_FILES) and is_array(!$_FILES['cc_pd_photo']))
2521                        {
2522                                $this->page_info['photos'][$id]['status'] = 'no_upload';
2523                                $this->page_info['photos'][$id]['msg'] = lang('No Photos uploaded to Server.');
2524
2525                                $this->save_session();
2526                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2527                                return;
2528                        }
2529
2530                        if (!function_exists('imagecreate'))
2531                        {
2532                                $this->page_info['photos'][$id]['status'] = 'no_GD_lib';
2533                                $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.');
2534
2535                                $this->save_session();
2536                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2537                                return;
2538                        }
2539
2540                        // TODO: Get Max Size from preferences!
2541                        if ($_FILES['cc_pd_photo']['size'] > 1000000)
2542                        {
2543                                $this->page_info['photos'][$id]['status'] = 'too_large';
2544                                $this->page_info['photos'][$id]['msg'] = lang('Image too large! ContactCenter limits the image size to 1 Mb');
2545
2546                                $this->save_session();
2547                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2548                                return;
2549                        }
2550
2551                        if ($_FILES['cc_pd_photo']['error'])
2552                        {
2553                                $this->page_info['photos'][$id]['status'] = 'error';
2554                                $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'];
2555
2556                                $this->save_session();
2557                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2558                                return;
2559                        }
2560
2561                        switch($_FILES['cc_pd_photo']['type'])
2562                        {
2563                                case 'image/jpeg':
2564                                case 'image/pjpeg':
2565                                        $src_img = imagecreatefromjpeg($_FILES['cc_pd_photo']['tmp_name']);
2566                                        if ($src_img == '')
2567                                        {
2568                                                $bogus = true;
2569                                        }
2570                                        break;
2571
2572                                case 'image/png':
2573                                case 'image/x-png':
2574                                        $src_img = imagecreatefrompng($_FILES['cc_pd_photo']['tmp_name']);
2575                                        if ($src_img == '')
2576                                        {
2577                                                $bogus = true;
2578                                        }
2579                                        break;
2580
2581                                case 'image/gif':
2582                                        $src_img = imagecreatefromgif($_FILES['cc_pd_photo']['tmp_name']);
2583                                        if ($src_img == '')
2584                                        {
2585                                                $bogus = true;
2586                                        }
2587                                        break;
2588
2589                                default:
2590
2591                                        $this->page_info['photos'][$id]['status'] = 'invalid_image';
2592                                        $this->page_info['photos'][$id]['msg'] = lang('The file must be an JPEG, PNG or GIF Image.');
2593
2594                                        $this->save_session();
2595                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2596                                        return;
2597                        }
2598
2599                        if ($bogus)
2600                        {
2601                                        $this->page_info['photos'][$id]['status'] = 'invalid_file';
2602                                        $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
2603
2604                                        $this->save_session();
2605                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2606                                        return;
2607                        }
2608
2609                        $img_size = getimagesize($_FILES['cc_pd_photo']['tmp_name']);
2610                        $dst_img = imagecreatetruecolor(60, 80);
2611
2612                        if (!imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, 60, 80, $img_size[0], $img_size[1]))
2613                        {
2614                                $this->page_info['photos'][$id]['status'] = 'invalid_file';
2615                                $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
2616
2617                                $this->save_session();
2618                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2619                                return;
2620                        }
2621
2622                        ob_start();
2623                        imagepng($dst_img);
2624                        $this->page_info['photos'][$id]['content'] = ob_get_contents();
2625                        ob_end_clean();
2626
2627                        $this->page_info['photos'][$id]['status'] = 'changed';
2628                        $this->page_info['photos'][$id]['msg'] = lang('Photo Successfully Updated!');
2629
2630                        $this->save_session();
2631
2632                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2633
2634                        imagedestroy($src_img);
2635                        imagedestroy($dst_img);
2636                        echo 'ok';
2637                        return;
2638                }
2639
2640
2641                /*!
2642
2643                        @function get_photo
2644                        @abstract Returns the photo to the browser
2645                        @author Raphael Derosso Pereira
2646
2647                */
2648                function get_photo($id)
2649                {
2650                        $fields = $this->bo->catalog->get_fields(false);
2651                        $fields['photo'] = true;
2652
2653                        $contact = $this->bo->catalog->get_single_entry($id, $fields);
2654
2655                        if (!$contact['photo'])
2656                        {
2657                                header('Content-type: image/png');
2658                                echo file_get_contents(PHPGW_INCLUDE_ROOT.'/contactcenter/templates/default/images/photo_celepar.png');
2659                                return;
2660                        }
2661
2662                        header('Content-type: image/jpeg');
2663                        $photo = imagecreatefromstring ($contact['photo']);
2664                        $width = imagesx($photo);
2665                        $height = imagesy($photo);
2666                        $twidth = 70;
2667                        $theight = 90;
2668                        $small_photo = imagecreatetruecolor ($twidth, $theight);
2669                        imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
2670                        imagejpeg($small_photo,"",100);
2671                        return;
2672                }
2673
2674                /*!
2675
2676                        @function get_states
2677                        @abstract Echos a serialized array containing all the states for the given country
2678                        @author Raphael Derosso Pereira
2679
2680                        @params $id_country The ID of the Country that contains the requested states
2681
2682                */
2683                function get_states($id_country)
2684                {
2685                        $states = $this->bo->catalog->get_all_states($id_country);
2686
2687                        if (!$states)
2688                        {
2689                                $result = array(
2690                                        'msg'    => lang('No States found for this Country.'),
2691                                        'status' => 'empty'
2692                                );
2693
2694                                echo serialize($result);
2695                                return;
2696                        }
2697
2698                        $result = array(
2699                                'msg'    => lang('States Successfully retrieved!'),
2700                                'status' => 'ok'
2701                        );
2702
2703                        foreach ($states as $state_info)
2704                        {
2705                                $result['data'][$state_info['id_state']] = $state_info['name'];
2706
2707                                if ($state_info['symbol'])
2708                                {
2709                                        $result['data'][$state_info['id_state']] .= ', '.$state_info['symbol'];
2710                                }
2711                        }
2712
2713                        echo serialize($result);
2714                }
2715
2716                /*!
2717
2718                        @function get_cities
2719                        @abstract Echos a serialized array containing all the cities of a given state
2720                        @author Raphael Derosso Pereira
2721
2722                        @param $id_country The ID of the Country that has the specified Cities (in case the
2723                                Country doesn't have any States)
2724                        @param $id_state The ID of the State that has the Cities requested
2725
2726                */
2727                function get_cities($id_country, $id_state=false)
2728                {
2729                        $cities = $this->bo->catalog->get_all_cities($id_country, $id_state);
2730
2731                        if (!$cities)
2732                        {
2733                                $result = array(
2734                                        'msg'    => lang('No Cities found for this State.'),
2735                                        'status' => 'empty'
2736                                );
2737
2738                                echo serialize($result);
2739                                return;
2740                        }
2741
2742                        $result = array(
2743                                'msg'    => lang('Cities Successfully retrieved!'),
2744                                'status' => 'ok'
2745                        );
2746
2747                        foreach ($cities as $city_info)
2748                        {
2749                                $result['data'][$city_info['id_city']] = $city_info['name'];
2750                        }
2751
2752                        echo serialize($result);
2753                }
2754
2755
2756                /*!
2757
2758                        @function search
2759                        @abstract Echos a serialized array containing the IDs
2760                                of the entries that matches the search argument
2761                        @author Raphael Derosso Pereira
2762                        @author Mï¿œrio Cï¿œsar Kolling (external catalogs)
2763
2764                        @param string $str_data A serialized array with two informations:
2765                                $data = array(
2766                                        'search_for' => (string),
2767                                        'recursive'  => (boolean),
2768                                );
2769
2770                */
2771                // SERPRO
2772                function search($str_data)
2773                {
2774                        $data = unserialize($str_data);
2775                        // It's an external catalog?
2776                        $external = $this->bo->is_external($this->page_info['actual_catalog']);
2777
2778                        if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
2779                        {
2780                                echo serialize(array(
2781                                        'msg'    => lang('Invalid parameters'),
2782                                        'status' => 'abort'
2783                                ));
2784
2785                                return array('error' => lang('Invalid parameters'));
2786                        }
2787
2788
2789                        /*
2790                         * TODO: look into the database to discover the database's encoding and convert the search_for field accordingly
2791                         */
2792                        // Support search parameters with accentuation
2793                        if ($this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
2794/**rev 104**/
2795                                //$this->page_info['actual_catalog']['class'] != 'bo_group_manager')
2796                                $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
2797                                $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
2798                                $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
2799/****/
2800                        {
2801
2802                                $data['search_for'] = utf8_encode($data['search_for']);
2803                        }
2804
2805                        $rules  = array();
2806
2807                        if ($data['search_for'] === '*')
2808                        {
2809                                $rules = array(
2810                                        0 => array(
2811                                                'field' => $data['fields']['search'],
2812                                                'type'  => 'LIKE',
2813                                                'value' => '%'
2814                                        )
2815                                );
2816                        }
2817                        else
2818                        {
2819                                $names = explode(' ', $data['search_for']);
2820
2821                                if (!is_array($names))
2822                                {
2823                                        echo serialize(array(
2824                                                'msg'    => lang('Invalid Search Parameter'),
2825                                                'status' => 'abort'
2826                                        ));
2827
2828                                }
2829
2830                                if (!$external && $this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
2831/**rev 104**/
2832                                        //$this->page_info['actual_catalog']['class'] != 'bo_group_manager')
2833                                        $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
2834                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
2835                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager' )
2836/*****/
2837                                {
2838                                        /*
2839                                         * Restrict the returned contacts search to objectClass = phpgwAccount,
2840                                         * must have attibute phpgwAccountStatus, phpgwAccountVisible != -1
2841                                         */
2842                                        $rules = array(
2843                                                0 => array(
2844                                                        'field' => 'contact.object_class',
2845                                                        'type'  => '=',
2846                                                        'value' => 'phpgwAccount'
2847                                                ),
2848                                                1 => array(
2849                                                        'field' => 'contact.account_status',
2850                                                        'type'  => 'iLIKE',
2851                                                        'value' => '%'
2852                                                ),
2853/**rev 104**/
2854                                                ///
2855                                                //1 => array(
2856                                                2 => array(
2857/*****/
2858                                                        'field' => 'contact.account_visible',
2859                                                        'type'  => '!=',
2860                                                        'value' => '-1'
2861/**rev 104**/
2862        /*                                      ),
2863                                                2 => array(
2864                                                        'field' => 'contact.object_class',
2865                                                        'type'  => '=',
2866                                                        'value' => 'inetOrgPerson'
2867/****/
2868                                                ),
2869                                        );
2870                                }
2871
2872                                foreach ($names as $name)
2873                                {
2874                                        if ($name != '')
2875                                        {
2876                                                array_push($rules, array(
2877                                                        'field' => $data['fields']['search'],
2878                                                        'type'  => 'iLIKE',
2879                                                        'value' => '%'.$name.'%'
2880                                                ));
2881                                        }
2882                                }
2883                        }
2884
2885                        if ($external || $this->page_info['actual_catalog']['class'] == 'bo_people_catalog' ||
2886/**rev 104**/
2887                                //$this->page_info['actual_catalog']['class'] == 'bo_group_manager')
2888                                $this->page_info['actual_catalog']['class'] == 'bo_group_manager' ||
2889                                $this->page_info['actual_catalog']['class'] == 'bo_shared_people_manager' ||
2890                                $this->page_info['actual_catalog']['class'] == 'bo_shared_group_manager')
2891
2892
2893/***/
2894                        {
2895                                // Get only this attributes: dn, cn for external catalogs,
2896                                // used to restrict the attributes used in filters
2897                                $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
2898                        }
2899                        else
2900                        {
2901                                // Get only this attributes: dn, cn, phpgwAccountType, objectClass, phpgwAccountStatus, phpghAccountVisible
2902                                // for non-external catalogs, used to restrict the attributes used in filters
2903                                $ids = $this->bo->find(array(
2904                                        $data['fields']['id'],
2905                                        $data['fields']['search'],
2906                                        'contact.object_class',
2907                                        //'contact.account_status',
2908                                        'contact.account_visible'
2909                                        ), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'), $data['search_for_area'] );
2910                        }
2911
2912                        if (!is_array($ids) || !count($ids))
2913                        {
2914                                $this->last_search_ids = null;
2915                                $this->save_session();
2916                                return null;
2917                        }
2918
2919                        $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
2920
2921                        $ids_f = array();
2922
2923                        foreach ($ids as $e_info)
2924                        {
2925/**rev 104**/
2926                                //$ids_f[] = $e_info[$id_field];
2927                                if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
2928                                {
2929                                        $ids_f[] = $e_info[$id_field];
2930                                } else{
2931                                        $ids_f[] = array(0=>$e_info[$id_field],1=>$e_info['perms']);
2932                                }
2933/****/
2934                        }
2935
2936                        return $ids_f;
2937                }
2938
2939                // CELEPAR
2940                /*
2941        function search($str_data)
2942        {
2943            $data = unserialize($str_data);
2944
2945            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
2946            {
2947                echo serialize(array(
2948                    'msg'    => lang('Invalid parameters'),
2949                    'status' => 'abort'
2950                ));
2951
2952                return;
2953            }
2954
2955            $rules  = array();
2956
2957            if ($data['search_for'] === '*')
2958            {
2959                $rules = array(
2960                    0 => array(
2961                        'field' => $data['fields']['search'],
2962                        'type'  => 'LIKE',
2963                        'value' => '%'
2964                    )
2965                );
2966            }
2967            else
2968            {
2969                $names = explode(' ', $data['search_for']);
2970
2971                if (!is_array($names))
2972                {
2973                    echo serialize(array(
2974                        'msg'    => lang('Invalid Search Parameter'),
2975                        'status' => 'abort'
2976                    ));
2977
2978                    return;
2979                }
2980
2981                foreach ($names as $name)
2982                {
2983                    if ($name != '')
2984                    {
2985                        array_push($rules, array(
2986                            'field' => $data['fields']['search'],
2987                            'type'  => 'iLIKE',
2988                            'value' => '%'.$name.'%'
2989                        ));
2990                    }
2991                }
2992            }
2993
2994
2995
2996            //$catalog = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
2997
2998            //if ($catalog['class'] === 'bo_people_catalog')
2999            //{
3000            //    array_push($rules, array(
3001            //        'field' => 'contact.id_owner',
3002            //        'type'  => '=',
3003            //        'value' => $GLOBALS['phpgw_info']['user']['account_id']
3004            //    ));
3005            //}
3006
3007
3008            $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
3009
3010            if (!is_array($ids) || !count($ids))
3011            {
3012                echo serialize(array(
3013                    'msg'    => lang('No Entries Found!'),
3014                    'status' => 'empty'
3015                ));
3016
3017                return;
3018            }
3019            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
3020
3021            $ids_f = array();
3022            foreach ($ids as $e_info)
3023            {
3024                $ids_f[] = $e_info[$id_field];
3025            }
3026
3027            echo serialize(array(
3028                'data'   => $ids_f,
3029                'msg'    => lang('Found %1 Entries', count($ids)),
3030                'status' => 'ok'
3031            ));
3032
3033                        return;
3034        }*/
3035                /*!
3036
3037                        @function get_multiple_entries
3038                        @abstract Returns an array containing the specifiend data in the default
3039                                CC UI format
3040                        @author Raphael Derosso Pereira
3041
3042                        @param array str_data A serialized array containing the ID's of the entries
3043                                to be taken, the fields to be taken and the rules to be used on the
3044                                retrieval:
3045                                $data = array(
3046                                        'ids'    => array(...),
3047                                        'fields' => array(...),
3048                                        'rules'  => array(...)
3049                                );
3050
3051                */
3052                function get_multiple_entries($str_data)
3053                {
3054                        $data = unserialize($str_data);
3055
3056                        if (!is_array($data) or !count($data) or !count($data['fields']) or !count($data['ids']))
3057                        {
3058                                return array(
3059                                        'msg'    => lang('Invalid Parameters'),
3060                                        'status' => 'abort'
3061                                );
3062                        }
3063
3064                        $entries = $this->bo->catalog->get_multiple_entries($data['ids'], $data['fields']);
3065
3066                        if (!is_array($entries) or !count($entries))
3067                        {
3068                                return array(
3069                                        'msg'    => lang('No Entries Found!'),
3070                                        'status' => 'empty'
3071                                );
3072                        }
3073
3074                        return array(
3075                                'msg'    => lang('Found %1 Entries!', count($entries)),
3076                                'status' => 'ok',
3077                                'data'   => $entries
3078                        );
3079                }
3080
3081                /*
3082
3083                        @function get_all_entries
3084                        @abstract Returns the specified fields for all catalog's entries
3085                                in the default CC UI format
3086                        @author Raphael Derosso Pereira
3087
3088                        @params array str_data A serialized array containing the fields to
3089                                be grabbed, the maximum number of entries to be returned and a
3090                                boolean specifying if the calls refers to a new grab or to an
3091                                unfinished one.
3092
3093                */
3094                function get_all_entries($str_data)
3095                {
3096                        $data = unserialize($str_data);
3097
3098                        if (!is_array($data) or
3099                            !count($data) or
3100                                !count($data['fields']) or
3101                                !$data['maxlength'] or
3102                                (!$data['new'] and !$data['offset']))
3103                        {
3104                                return array(
3105                                        'msg'    => lang('Invalid Parameters'),
3106                                        'status' => 'abort'
3107                                );
3108                        }
3109
3110                        if ($data['new'])
3111                        {
3112                                $this->all_entries = $this->bo->catalog->get_all_entries_ids();
3113
3114                                $this->save_session();
3115
3116                                if (!is_array($this->all_entries) or !count($this->all_entries))
3117                                {
3118                                        return array(
3119                                                'msg'    => lang('No Entries Found!'),
3120                                                'status' => 'empty'
3121                                        );
3122                                }
3123
3124                                $data['offset'] = 0;
3125                        }
3126
3127                        if ($data['maxlength'] != -1)
3128                        {
3129                                $result = $this->bo->catalog->get_multiple_entries(array_slice($this->all_entries, $data['offset'], $data['maxlength']), $data['fields']);
3130                        }
3131                        else
3132                        {
3133                                $result = $this->bo->catalog->get_multiple_entries($this->all_entries, $data['fields']);
3134                        }
3135
3136                        $prefs = ExecMethod('contactcenter.ui_preferences.get_preferences');
3137
3138                        $jsCode = array();
3139                        $count = 0;
3140                        foreach ($result as $each)
3141                        {
3142                                if (!is_array($each))
3143                                {
3144                                        continue;
3145                                }
3146
3147                                if($this-> typeContact == 'groups') {
3148
3149                                        foreach ($each as $field => $value)     {
3150
3151                                                if ($field === 'title') {
3152                                                        $optionName = '\\"'.$value.'\\"';
3153
3154                                                }
3155                                                else if ($field === 'short_name')       {
3156
3157                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$optionName.' ('.$value.')", "'.$count.'");';
3158                                                        $count++;
3159                                                }
3160                                        }
3161                                }
3162
3163                                else  {
3164                                        foreach ($each as $field => $value)     {
3165                                                if ($field === 'names_ordered') {
3166                                                         if(is_array($value))
3167                                $value = $value[0];
3168                                                        $name = '\\"'.$value.'\\"';
3169                                                }
3170                                                else if ($field === 'connections')      {
3171
3172                                                        foreach ($value as $connection)         {
3173                                                                if ($connection['id_type'] == $prefs['personCardEmail'])        {
3174                                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$name.' <'.$connection['connection_value'].'>", "'.$count.'");';
3175                                                                        $count++;
3176                                                                }
3177                                                        }
3178                                                }
3179                                        }
3180                                }
3181                        }
3182
3183                        $jsCodeFinal = implode("\n", $jsCode);
3184
3185                        $nEntries = count($result);
3186
3187                        if (!$nEntries)
3188                        {
3189                                return array(
3190                                        'msg'    => lang('Error while getting user information...'),
3191                                        'status' => 'abort'
3192                                );
3193                        }
3194
3195                        return array(
3196                                'msg'      => lang('Found %1 Entries!', $nEntries),
3197                                'status'   => 'ok',
3198                                'typeContact'   => $this -> typeContact,
3199                                'final'    => $nEntries + $data['offset'] < count($this->all_entries) ? false : true,
3200                                'offset'   => $data['offset'] + $nEntries,
3201                                'data'     => $jsCodeFinal
3202                        );
3203                }
3204
3205                /*********************************************************************\
3206                 *                      Auxiliar Methods                             *
3207                \*********************************************************************/
3208
3209                /*!
3210
3211                        @function save_session
3212                        @abstract Saves the data on the session
3213                        @author Raphael Derosso Pereira
3214
3215                */
3216                function save_session()
3217                {
3218                        $GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter',$this->page_info);
3219                        $GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter',$this->all_entries);
3220                }
3221
3222                /*!
3223
3224                        @function convert_tree
3225                        @abstract Converts the tree array in the BO format to a JS tree array compatible
3226                                with the one available in eGW
3227                        @author Raphael Derosso Pereira
3228
3229                        @param (array)  $tree    The tree in the BO format
3230                        @param (string) $name    The tree name
3231                        @param (string) $iconDir The dir where the icons are
3232                        @param (string) $parent  The parent
3233                */
3234
3235                function convert_tree($tree, &$iconDir, $parent='0')
3236                {
3237//                      echo "Entrou<br>\tPai: $parent <br>";
3238                        $rtree = array();
3239
3240                        if ($parent === '0')
3241                        {
3242//                              echo 'Root!<br>';
3243                                $rtree['0'] = array(
3244                                        'type'       => 'catalog_group',
3245                                        'id'         => '0',
3246                                        'pid'        => 'none',
3247                                        'caption'    => lang('Catalogues'),
3248                                        'class'      => 'bo_catalog_group_catalog',
3249                                        'class_args' => array('_ROOT_', '$this', '$this->get_branch_by_level($this->catalog_level[0])')
3250                                );
3251                        }
3252
3253                        foreach($tree as $id => $value)
3254                        {
3255//                              echo 'ID: '.$id.'<br>';
3256                                $rtree[$parent.'.'.$id] = array(
3257                                        'type'    => $value['type'],
3258                                        'id'      => $parent.'.'.$id,
3259                                        'pid'     => $parent,
3260                                        'caption' => $value['name']
3261                                );
3262
3263                                switch($value['type'])
3264                                {
3265                                        case 'catalog_group':
3266                                        case 'mixed_catalog_group':
3267                                                $rtree = $rtree + $this->convert_tree($value['sub_branch'],$iconDir,$parent.'.'.$id);
3268                                                break;
3269                                }
3270                        }
3271
3272                        if (count($rtree))
3273                        {
3274                                return $rtree;
3275                        }
3276                }
3277
3278                function get_catalog_add_contact($id){
3279
3280                        $array_participants = array();
3281                        if(!$this->bo->catalog->src_info) {
3282                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3283                                $this->bo->catalog->src_info = $ldap->srcs[1];
3284                        }
3285
3286                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3287                        $dn=$this->bo->catalog->src_info['dn'];
3288                        $justThese = array("givenname","givenname","sn","telephonenumber","mail");
3289                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);
3290                        $info = ldap_get_entries($ds, $sr);
3291                        for($z = 0; $z < 5; $z++) {
3292                                $participant = $info[0][$justThese[$z]];
3293                                array_push($array_participants, $participant);
3294                        }
3295
3296                        ldap_close($ds);
3297                        echo serialize($array_participants);
3298                }
3299
3300                function get_catalog_participants_group($id)
3301                {
3302                        if(!$this->bo->catalog->src_info) {
3303                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3304                                $this->bo->catalog->src_info = $ldap->srcs[1];
3305                        }
3306                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3307                        $justThese = array("description","memberuid");
3308                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);
3309                        $info = ldap_get_entries($ds, $sr);
3310                        $member_uids = $info[0]['memberuid'];
3311                        $contact['names_ordered'] = $info[0]['description'];
3312                        $filter = "";
3313                        for($z = 0; $z < count($member_uids); $z++) {
3314                                if($member_uids[$z])
3315                                        $filter.="(uid=".$member_uids[$z].")";
3316                        }
3317                        $array_participants = array();
3318                        if($filter) {
3319                                $filter = "(|".$filter.")";
3320                                $valarray = explode(',',$id);
3321                                array_shift($valarray);
3322                                $dn = implode(',',$valarray);
3323                                $justThese = array("cn","mail");
3324                                $sr = ldap_search($ds,$dn, $filter,$justThese);
3325                                $info = ldap_get_entries($ds, $sr);
3326                                for($z = 0; $z < $info['count']; $z++) {
3327                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3328                                    $array_emails[$info[$z]['mail'][0]] = null;
3329                                        array_push($array_participants, $participant);
3330                                }
3331                                ldap_close($ds);
3332                        }
3333                        sort($array_participants);
3334                        $innerHTML = '';
3335                        foreach($array_participants as $index => $participant){
3336                                $innerHTML .= $participant;
3337                        }
3338                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
3339                        echo serialize($return);
3340                }
3341
3342                function get_catalog_participants_list($id)
3343                {
3344
3345                        $fields = $this->bo->catalog->get_fields(false);
3346                        $fields['names_ordered'] = true;
3347                        $fields['mail_forwarding_address'] = true;
3348                        $contact = $this->bo->catalog->get_single_entry($id,$fields);
3349
3350                        $array_participants = array();
3351                        $array_emails = array();
3352
3353                        $filter = null;
3354                        for($z = 0; $z < $contact['mail_forwarding_address']['count']; $z++) {
3355                                        if(strstr($contact['mail_forwarding_address'][$z],'@')) {
3356                                                $filter.="(mail=".$contact['mail_forwarding_address'][$z].")";
3357                                                $array_emails[$contact['mail_forwarding_address'][$z]] = "<font color=black>".$contact['mail_forwarding_address'][$z]."</font>";
3358                                        }
3359                                        else
3360                                                $array_participants[$z] = "<font color=red>".$contact['mail_forwarding_address'][$z]."</font>";
3361                        }
3362
3363                        if($filter) {
3364                                $filter = "(|".$filter.")";
3365                                if(!$this->bo->catalog->src_info) {
3366                                        $ldap = CreateObject('contactcenter.bo_ldap_manager');
3367                                        $this->bo->catalog->src_info = $ldap->srcs[1];
3368                                }
3369                                $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3370                                $dn=$this->bo->catalog->src_info['dn'];
3371                                $justThese = array("cn","mail");
3372                                $sr = ldap_search($ds,$dn, $filter,$justThese);
3373                                $info = ldap_get_entries($ds, $sr);
3374                                for($z = 0; $z < $info['count']; $z++) {
3375                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3376                                        $array_emails[$info[$z]['mail'][0]] = null;
3377                                        array_push($array_participants, $participant);
3378                                }
3379
3380                                foreach($array_emails as $index => $email)
3381                                        if($email)
3382                                                array_push($array_participants, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$email."<br>");
3383
3384                                ldap_close($ds);
3385                        }
3386                        sort($array_participants);
3387                        $innerHTML = '';
3388                        foreach($array_participants as $index => $participant){
3389                                $innerHTML .= $participant;
3390                        }
3391                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
3392                        echo serialize($return);
3393                }
3394
3395                function export_contacts($typeExport){
3396
3397                        $boGroup = CreateObject('contactcenter.bo_group');
3398                        $contacts = $boGroup->get_all_contacts();
3399                        $streamBuffer = '';
3400
3401                        if(!count($contacts))
3402                                echo null;
3403
3404/**rev 104**/
3405                        // Essa iteraᅵᅵo transforma uma esturuta com contatos redundantes e separados por email ou tel.
3406                        // em outra com apenas 1 elemento pra cada contato
3407        /*              $i=0;
3408                        foreach($contacts as $object){
3409                                $i=($object['id_contact'] - 1);
3410                                $all_contacts[$i]['name']=$object['names_ordered'];
3411                                if ($object['id_typeof_contact_connection'] == 1)
3412                                        $all_contacts[$i]['email']=$object['connection_value'];
3413                                else
3414                                        $all_contacts[$i]['phone']=$object['connection_value'];
3415                        }
3416        */
3417/*****/
3418
3419                        switch($typeExport) {
3420
3421                                case 'outlook_en':
3422                                        $streamBuffer = "Name;E-mail Address;Notes;Mobile Phone;Pager;Company;".
3423/**rev 104**/
3424        /*                                              "Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";
3425                                        foreach($all_contacts as $index => $object){
3426                                                $streamBuffer.= $object['name'].";".$object['email'].";;;;;;".$object['phone'].";;;\r\n";
3427                                        }
3428        */
3429                                                        "Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";                                                       
3430                                        foreach($contacts as $index => $object){
3431                                                $streamBuffer.= $object['names_ordered'].";".$object['connection_value'].";;;;;;".$object['phone'].";;;\r\n";
3432                                        }
3433/*****/
3434                                break;
3435
3436                                case 'outlook_pt-BR':
3437                                        $streamBuffer = "Nome;End. de email;Endereï¿œo residencial;".
3438                                        "Cidade do endereï¿œo residencial;CEP do endereï¿œo residencial;".
3439                                        "Estado;Paï¿œs/regiï¿œo do endereï¿œo residencial;Telefone residencial;".
3440                                        "Rua do endereï¿œo comercial;Cidade do endereï¿œo comercial;".
3441                                        "CEP do endereï¿œo comercial;Estado do endereï¿œo comercial;".
3442                                        "Paï¿œs/regiï¿œo do endereï¿œo comercial;Telefone comercial;Empresa;Cargo\r\n";
3443/**rev 104**/
3444                                //      foreach($all_contacts as $index => $object){
3445                                //              $streamBuffer.= $object['name'].";".$object['email'].";;;;;;".$object['phone'].";;;;;;;;\r\n";
3446                                        foreach($contacts as $index => $object){
3447                                                $streamBuffer.= $object['names_ordered'].";".$object['connection_value'].";;;;;;".$object['phone'].";;;;;;;;\r\n";
3448/******/
3449                                        }
3450                                break;
3451
3452                                case 'outlook2000_pt-BR':
3453                                        $streamBuffer = "\"Tratamento\",\"Nome\",\"Segundo Nome\",\"Sobrenome\",\"Sufixo\",".
3454                                        "\"Empresa\",\"Departamento\",\"Cargo\",\"Rua do endereï¿œo comercial\",\"Rua do endereï¿œo comercial 2\",".
3455                                        "\"Rua do endereï¿œo comercial 3\",\"Cidade do endereï¿œo comercial\",\"Estado do endereï¿œo comercial\",".
3456                                        "\"CEP do endereï¿œo comercial\",\"Paï¿œs do endereï¿œo comercial\",\"Endereï¿œo residencial\",\"Rua residencial 2\",".
3457                                        "\"Rua residencial 3\",\"Cidade do endereï¿œo residencial\",\"Estado\",\"CEP do endereï¿œo residencial\",\"Paï¿œs do endereï¿œo residencial\",".
3458                                        "\"Outro endereï¿œo\",\"Outro endereï¿œo 2\",\"Outro endereï¿œo 3\",\"Cidade\",\"Estado\",\"CEP\",\"Paï¿œs\",".
3459                                        "\"Telefone do assistente\",\"Fax comercial\",\"Telefone comercial\",\"Telefone comercial 2\",\"Retorno de chamada\",".
3460                                        "\"Telefone do carro\",\"Telefone principal da empresa\",\"Fax residencial\",\"Telefone residencial\",".
3461                                        "\"Telefone residencial 2\",\"ISDN\",\"Telefone celular\",\"Outro fax\",\"Outro telefone\",\"Pager\",\"Telefone principal\",".
3462                                        "\"Radiofone\",\"Telefone TTY/TDD\",\"Telex\",\"Aniversï¿œrio\",\"Anotaᅵᅵes\",\"Caixa postal\",\"Categorias\",".
3463                                        "\"Cï¿œdigo da empresa\",\"Cï¿œdigo do governo\",\"Cï¿œnjuge\",\"Conta\",\"Endereï¿œo de correio eletrï¿œnico\",".
3464                                        "\"Nome de exibiᅵᅵo do correio eletr.\",\"Endereï¿œo de correio eletrï¿œnico 2\",".
3465                                        "\"Nome de exibiᅵᅵo do correio eletr.2\",\"Endereï¿œo de correio eletrï¿œnico 3\",".
3466                                        "\"Nome de exibiᅵᅵo do correio eletr.3\",\"Datas especiais\",\"Disponibilidade da Internet\",".
3467                                        "\"Filhos\",\"Hobby\",\"Idioma\",\"Indicaᅵᅵo\",\"Informaᅵᅵes para cobranï¿œa\",\"Iniciais\",\"Local\",".
3468                                        "\"Nome do assistente\",\"Nome do gerenciador\",\"Pï¿œgina da Web\",\"Palavras-chave\",\"Particular\",\"Personalizado 1\",\"Personalizado 2\",".
3469                                        "\"Personalizado 3\",\"Personalizado 4\",\"Prioridade\",\"Profissï¿œo\",\"Quilometragem\",\"Sala\",\"Sensibilidade\",\"Servidor de diretï¿œrio\",".
3470                                        "\"Sexo\"\r\n";
3471
3472/**rev 104**/
3473                                        //foreach($all_contacts as $index => $object){
3474                                        //      $streamBuffer.= ",\"".$object['name']."\",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,".$object['phone'].",,,,,,,,,,,,\"".$object['email']."\",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3475                                        foreach($contacts as $index => $object){
3476                                                $streamBuffer.= ",\"".$object['names_ordered']."\",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,".$object['phone'].",,,,,,,,,,,,\"".$object['connection_value']."\",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3477/******/
3478                                        }
3479                                break;
3480
3481                                case 'outlook2000_en':
3482                                        $streamBuffer = "Title,First Name,Middle Name,Last Name,Suffix,Company,Department,Job Title,".
3483                                        "Business Street,Business Street 2,Business Street 3,Business City,Business State,Business Postal Code,".
3484                                        "Business Country,Home Street,Home Street 2,Home Street 3,Home City,Home State,Home Postal Code,Home Country,".
3485                                        "Other Street,Other Street 2,Other Street 3,Other City,Other State,Other Postal Code,Other Country,".
3486                                        "Assistant's Phone,Business Fax,Business Phone,Business Phone 2,Callback,Car Phone,Company Main Phone,Home Fax,".
3487                                        "Home Phone,Home Phone 2,ISDN,Mobile Phone,Other Fax,Other Phone,Pager,Primary Phone,Radio Phone,TTY/TDD Phone,Telex,".
3488                                        "Account,Anniversary,Assistant's Name,Billing Information,Birthday,Categories,Children,Directory Server,E-mail Address,".
3489                                        "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,".
3490                                        "Gender,Government ID Number,Hobby,Initials,Internet Free Busy,Keywords,Language,Location,Manager's Name,Mileage,Notes,".
3491                                        "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";
3492
3493/**rev 104**/
3494                                        //foreach($all_contacts as $index => $object){
3495                                        //      $streamBuffer.= ",".$object['name'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,".$object['phone'].",,,,,,,,,,,,".$object['email'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3496                                        foreach($contacts as $index => $object){
3497                                                $streamBuffer.= ",".$object['names_ordered'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,".$object['phone'].",,,,,,,,,,,,".$object['connection_value'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3498/*******/
3499                                        }
3500                                break;
3501
3502                                case 'thunderbird':
3503                                        $streamBuffer = "\n";
3504
3505/**rev 104**/
3506                                        //foreach($all_contacts as $index => $object){
3507                                        //      $streamBuffer.= ",,".$object['name'].",,".$object['email'].",,".$object['phone'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3508                                        foreach($contacts as $index => $object){
3509                                                $streamBuffer.= ",,".$object['names_ordered'].",,".$object['connection_value'].",,".$object['phone'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
3510
3511/******/
3512                                        }
3513                                break;
3514
3515                                case 'expresso':
3516                                        $streamBuffer = "Nome,Email,Telefone\r\n";
3517
3518/**rev 104**/
3519                                        //foreach($all_contacts as $index => $object){
3520                                        //      $streamBuffer.= $object['name'].",".$object['email'].",".$object['phone']."\r\n";
3521                                        foreach($contacts as $index => $object){
3522                                                $streamBuffer.= $object['names_ordered'].",".$object['connection_value'].",".$object['phone']."\r\n";
3523 
3524/******/
3525                                        }
3526                                break;
3527
3528                        }
3529
3530                        $file = "contacts_".md5(microtime()).".swp";
3531                        $tempDir = ini_get("session.save_path");
3532                        $f = fopen($tempDir.'/'.$file,"w");
3533                        if(!$f)
3534                                echo null;
3535
3536                        fputs($f,$streamBuffer);
3537                        fclose($f);
3538
3539                        echo $tempDir.'/'.$file;
3540                }
3541
3542                // Get the csv field and put into array, from php.net
3543                function parse_line($input_text, $delimiter = ',', $text_qualifier = '"') {
3544                        $text = trim($input_text);
3545                          if(is_string($delimiter) && is_string($text_qualifier)) {
3546                         $re_d = '\x' . dechex(ord($delimiter));            //format for regexp
3547                        $re_tq = '\x' . dechex(ord($text_qualifier));    //format for regexp
3548
3549                        $fields = array();
3550                        $field_num = 0;
3551                        while(strlen($text) > 0) {
3552                        if($text{0} == $text_qualifier) {
3553                                preg_match('/^' . $re_tq . '((?:[^' . $re_tq . ']|(?<=\x5c)' . $re_tq . ')*)' . $re_tq . $re_d . '?(.*)$/', $text, $matches);
3554
3555                                $value = str_replace('\\' . $text_qualifier, $text_qualifier, $matches[1]);
3556                                $text = trim($matches[2]);
3557
3558                                $fields[$field_num++] = $value;
3559                        } else {
3560                                preg_match('/^([^' . $re_d . ']*)' . $re_d . '?(.*)$/', $text, $matches);
3561
3562                                $value = $matches[1];
3563                                $text = trim($matches[2]);
3564
3565                                $fields[$field_num++] = $value;
3566                }
3567                }
3568                        return $fields;
3569                    } else
3570                        return false;
3571                }
3572
3573                //funcao alterada para importar outros campos alem de nome, telefone e email, de arquivo csv (Outlook 2000)
3574                //em 08/04/2009 - Rommel Cysne (rommel.cysne@serpro.gov.br);
3575                //Foi adicionada uma funcao (escapesheelcmd()) nas variaveis para que caracteres especiais sejam ignorados
3576                //durante a importacao dos contatos; o processo estava travando por causa de caracteres em campos como nome,
3577                //sobrenome, notas e e-mail;
3578                //em 19/06/2009 - Rommel Cysne (rommel.cysne@serpro.gov.br);
3579                function import_contacts($typeImport){
3580
3581                        if($file = $_SESSION['contactcenter']['importCSV']) {
3582                                unset($_SESSION['contactcenter']['importCSV']);
3583                                $len = filesize($file);
3584                                $count = 0;
3585                                $return = array('error' => false, '_new' => 0, '_existing' => 0, '_failure' => 0);
3586                                $handle = @fopen($file, "r") or die(serialize($return['error'] = true));
3587
3588                                $input_header = fgets($handle);
3589                                if ($typeImport == 'outlook')
3590                                        $delim = ';';
3591                                else if ($typeImport == 'auto')
3592                                $delim = strstr($input_header,',') ? ',' : ';';
3593                                else
3594                                        $delim = ',';
3595                                $csv_header = $this->parse_line($input_header,$delim);
3596                                $firstContact = fgets($handle);
3597                                preg_match("/\"(.+)\"[,;]/sU",$firstContact,$matches); // yahoo csv
3598                                rewind($handle);
3599
3600                                $header = @fgetcsv($handle, $len, $delim) or die(serialize($return['error'] = true));
3601                                if(count($header)  < 2 || count($header) > 100) {
3602                                        $return['error'] = true;
3603                                        $return['sizeheader'] = count($header);
3604                                        echo serialize($return);
3605                                        return;
3606                                }
3607
3608                                if ($matches[0][strlen($matches[0])-1] == ';')
3609                                        $delim = ';';
3610
3611                        $boGroup = CreateObject('contactcenter.bo_group');
3612                        $boPeople = CreateObject('contactcenter.bo_people_catalog');
3613                                switch($typeImport){
3614                                        case 'outlook2000':
3615                                                $name_pos=1;
3616                                                $name2_pos=2;
3617                                                $name3_pos=3;
3618                                                $addr1_pos=8;
3619                                                $cep_pos=13;
3620                                                $addr2_pos=22;
3621                                                $fax_pos=30;
3622                                                $phone_pos=31;
3623                                                $resPhone_pos=37;
3624                                                $cellPhone_pos=40;
3625                                                $pager_pos=43;
3626                                                $birth_pos=48;
3627                                                $notes_pos=49;
3628                                                $email_pos=56;
3629                                                $altEmail_pos=59;
3630
3631                                                break;
3632                                        case 'outlook':
3633                                                $name_pos=3;
3634                                                $email_pos=4;
3635                                                $phone_pos=7;
3636                                                $resPhone_pos=10;
3637                                                $cellPhone_pos=12;
3638                                                $addr1_pos=13;
3639                                                $cep_pos=15;
3640                                                $phone_pos=18;
3641                                                $fax_pos=19;
3642                                                $pager_pos=20;
3643                                                $notes_pos=25;
3644                                                break;
3645                                        case 'thunderbird':
3646                                                $name_pos=2;
3647                                                $email_pos=4;
3648                                                $phone_pos=7;
3649                                                break;
3650                                        case 'expresso':
3651                                                $name_pos=0;
3652                                                $email_pos=1;
3653                                                $phone_pos=2;
3654                                                break;
3655                                        default:
3656                                                foreach($csv_header as $index => $fieldName)
3657                                                {
3658                                                        switch($fieldName){
3659                                                        case 'Name':
3660                                                        case 'Nome':
3661                                                        case 'First Name':
3662                                                                $name_pos = $index;
3663                                                                break;
3664                                                        case 'Second name':
3665                                                        case 'Segundo nome':
3666                                                                $name2_pos = $index;
3667                                                                break;
3668                                                        case 'Sobrenome':
3669                                                        case 'Surname':
3670                                                                $name3_pos = $index;
3671                                                                break;
3672                                                        case 'Business Street':
3673                                                        case 'Rua do endereço comercial':
3674                                                                $addr1_pos = $index;
3675                                                                break;
3676                                                        case 'Rua do endereço comercial 2':
3677                                                        case 'Outro endereço':
3678                                                                $addr2_pos = $index;
3679                                                                break;
3680                                                        case 'Business Postal Code':
3681                                                        case 'CEP do endereço comercial':
3682                                                                $cep_pos = $index;
3683                                                                break;
3684                                                        case 'Business Fax':
3685                                                        case 'Fax comercial':
3686                                                        case 'Fax':
3687                                                                $fax_pos = $index;
3688                                                                break;
3689                                                        case 'Home Phone':
3690                                                        case 'Telefone residencial':
3691                                                                $resPhone_pos = $index;
3692                                                                break;
3693                                                        case 'Mobile phone':
3694                                                        case 'Telefone celular':
3695                                                                $cellPhone_pos = $index;
3696                                                                break;
3697                                                        case 'Pager':
3698                                                                $pager_pos = $index;
3699                                                                break;
3700                                                        case 'Phone':
3701                                                        case 'Business Phone':
3702                                                        case 'Telefone':
3703                                                        case 'Telefone principal':
3704                                                        case 'Telefone comercial':
3705                                                                $phone_pos = $index;
3706                                                                break;
3707                                                        case 'Aniversário':
3708                                                        case 'Birthdate':
3709                                                                $birth_pos = $index;
3710                                                        case 'Anotações':
3711                                                        case 'Notes':
3712                                                                $notes_pos = $index;
3713                                                        case 'E-mail':
3714                                                        case 'Email':
3715                                                        case 'E-mail Address':
3716                                                        case 'Endereï¿œo de correio eletrï¿œnico':
3717                                                        case 'End. de email':
3718                                                                $email_pos = $index;
3719                                                                break;
3720                                                        case 'Endereï¿œo de correio eletrï¿œnico 2':
3721                                                                $altEmail_pos = $index;
3722                                                                break;
3723                                                        }
3724                                                }
3725                                                break;
3726                                }
3727
3728                                while (($data = fgetcsv($handle, $len, $delim))) {
3729                                foreach ($header as $key=>$heading)
3730                                $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
3731
3732                                        $sdata = array();
3733                                        $full_name      = trim($row[$header[$name_pos]]);
3734                                        $email          = trim($row[$header[$email_pos]]);
3735                                        $phone          = trim($row[$header[$phone_pos]]);
3736                                        $name2          = trim($row[$header[$name2_pos]]);
3737                                        $name3          = trim($row[$header[$name3_pos]]);
3738
3739                                        $addr1          = trim($row[$header[$addr1_pos]]);
3740                                        $addr2          = trim($row[$header[$addr2_pos]]);
3741                                        $cep            = trim($row[$header[$cep_pos]]);
3742                                        $fax            = trim($row[$header[$fax_pos]]);
3743                                        $resPhone       = trim($row[$header[$resPhone_pos]]);
3744                                        $cellPhone      = trim($row[$header[$cellPhone_pos]]);
3745                                        $pager          = trim($row[$header[$pager_pos]]);
3746                                        $birth          = trim($row[$header[$birth_pos]]);
3747                                        $notes          = trim($row[$header[$notes_pos]]);
3748                                        $altEmail       = trim($row[$header[$altEmail_pos]]);
3749
3750                                        $full_name = escapeshellcmd($full_name);
3751                                        $array_name = explode(' ', str_replace('"','',(str_replace('\'','',$full_name))));
3752                                        $sdata['given_names'] = escapeshellcmd($array_name[0]);
3753                                        $array_name[0] = null;
3754                                        $sdata['family_names'] = trim(implode(' ',$array_name));
3755                                        if($sdata['family_names'] == '')
3756                                        {
3757                                                $sdata['family_names'] = escapeshellcmd($name2) . " " . escapeshellcmd($name3);
3758                                        }
3759
3760                                        $sdata['connections']['default_email']['connection_name'] = lang('Main');
3761                                        $sdata['connections']['default_email']['connection_value'] = escapeshellcmd($email);
3762
3763                                        $sdata['connections']['default_phone']['connection_name'] = lang('Main');
3764                                        $sdata['connections']['default_phone']['connection_value'] = escapeshellcmd($phone);
3765
3766                                        $sdata['connections']['fax']['connection_name'] = lang('Fax');
3767                                        $sdata['connections']['fax']['connection_value'] = escapeshellcmd($fax);
3768
3769                                        $sdata['connections']['residencial_phone']['connection_name'] = lang('Residencial');
3770                                        $sdata['connections']['residencial_phone']['connection_value'] = escapeshellcmd($resPhone);
3771
3772                                        $sdata['connections']['cellular_phone']['connection_name'] = lang('Cellphone');
3773                                        $sdata['connections']['cellular_phone']['connection_value'] = escapeshellcmd($cellPhone);
3774
3775                                        $sdata['connections']['pager']['connection_name'] = lang('Pager');
3776                                        $sdata['connections']['pager']['connection_value'] = escapeshellcmd($pager);
3777
3778                                        $sdata['connections']['alternative_email']['connection_name'] = lang('Alternative');
3779                                        $sdata['connections']['alternative_email']['connection_value'] = escapeshellcmd($altEmail);
3780
3781                                        $sdata['addresses']['addr1']['address_value'] = escapeshellcmd($addr1);
3782                                        $sdata['addresses']['addr2']['address_value'] = escapeshellcmd($addr2);
3783                                        $sdata['addresses']['cep']['address_value'] = escapeshellcmd($cep);
3784
3785                                        $array_birth = explode("/",$birth);
3786
3787                                        $sdata['birthdate'] = escapeshellcmd(date('Y-m-d', mktime(0,0,0,$array_birth[1],$array_birth[0],$array_birth[2])));
3788
3789                                        $sdata['notes'] = escapeshellcmd($notes);
3790                                        $sdata['is_quick_add'] = true;
3791                                        $sdata['connections']['default_phone']['connection_value'] = $phone;
3792
3793                                        //      verifica se email já existe!
3794                                        $email = escapeshellcmd($email);
3795                                        $contact = $boGroup->verify_contact($email);
3796
3797                                        if(!$sdata['given_names'] && $email){
3798                                                        $a_email = explode("@",$email);
3799                                                        $sdata['given_names'] = escapeshellcmd($a_email[0]);
3800                                        }
3801
3802                                        $line_iteration = $return['_failure'] + $return['_existing'] + $return['_new'];
3803
3804                                        if($contact){
3805                                                $return['_existing']++;
3806                                        }
3807                                        else if(!eregi("^[/_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
3808                                                $return['_failure']++;
3809                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid E-Mail address: " . $email ."<br>";
3810                                        }
3811                                        else if (!$sdata['given_names'] || !$email || !$boPeople ->quick_add($sdata)){
3812                                                $return['_failure']++;
3813                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid Name: " . $sdata['given_names'] ."<br>";
3814                                        }
3815                                        else
3816                                                $return['_new']++;
3817                        }
3818                                fclose($handle);
3819                                unlink($file);
3820                        }
3821                        else
3822                                $return['error'] = true;
3823
3824                        echo serialize($return);
3825                }
3826        }
3827
3828?>
Note: See TracBrowser for help on using the repository browser.