source: sandbox/2.2.0.2/contactcenter/inc/class.ui_data.inc.php @ 4509

Revision 4509, 148.7 KB checked in by airton, 13 years ago (diff)

Ticket #1933 - Falha na visualizacao dos grupos de um contato no catalogo compartilhado

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