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

Revision 4505, 148.3 KB checked in by airton, 13 years ago (diff)

Ticket #1930 - Problema no upload e sincronização de imagem de um contato do Expresso

  • 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                        $predata[] = $boGroup->get_groups_by_user();
1861                        //$predata[] = $this->bo->catalog->get_all_relations_types();
1862
1863                        $i = 0;
1864                        foreach($predata as $data_)
1865                        {
1866                                if ($data_)
1867                                {
1868                                        $data[$i] = $data_;
1869                                }
1870
1871                                $i++;
1872                        }
1873
1874                        if (count($data))
1875                        {
1876                                echo serialize($data);
1877                                return;
1878                        }
1879
1880                        echo 0;
1881                }
1882
1883                /*!
1884
1885                        @function quick_add
1886                        @abstract Adds a new Contact using the Quick Add interface
1887                        @author Raphael Derosso Pereira
1888
1889                        @param string $sdata Serialized data
1890                */
1891                function quick_add($sdata, $echo=true)
1892                {
1893
1894                        $sdata = str_replace('\\"', '"', $sdata);
1895                        $new_array = unserialize($sdata);
1896                        $tdata = array();
1897
1898                        foreach($new_array as $tmp)
1899                                $tdata[] = $tmp;
1900
1901                        if (!$tdata)
1902                        {
1903                            if ($echo)
1904                            {
1905                                echo serialize(array(
1906                                        'msg'    => lang('Problems on adding your Contact. Invalid Data came from client. No Contact added!'),
1907                                        'status' => 'abort'
1908                                ));
1909                           
1910                                return;
1911                            }
1912                            else
1913                                {
1914                                    return serialize(array(
1915                                        'msg'    => lang('Problems on adding your Contact. Invalid Data came from client. No Contact added!'),
1916                                        'status' => 'abort'
1917                                    ));
1918                                }
1919                        }
1920
1921                        // verifica se email já existe!
1922                        $boGroup = CreateObject('contactcenter.bo_group');
1923                        $contact = $boGroup->verify_contact($tdata[4]);
1924
1925                        if($contact)
1926                        {
1927                                $str_contact = "\r\n - ".implode("\r\n - ",$contact);
1928
1929                            if ($echo)
1930                            {
1931                                echo serialize(array(
1932                                        'msg'    => lang('Problems on adding your Contact. The email "%1" already exists in: %2',$tdata[4], $str_contact),
1933                                        'status' => 'alreadyExists'
1934                                ));
1935
1936                                return;
1937                            }
1938                            else
1939                                {
1940                                    return serialize(array(
1941                                        'msg'       => lang('Problems on adding your Contact. The email "%1" already exists in: %2',$tdata[4], $str_contact),
1942                                        'status'    => 'alreadyExists',
1943                                        'id_connection'  => $contact[1]
1944                                    ));
1945                                }
1946                        }
1947
1948                        $data['alias'] = addslashes($tdata[0]);
1949                        $data['given_names'] = addslashes($tdata[1]);
1950                        $data['family_names'] = addslashes($tdata[2]);
1951                        $data['connections']['default_phone']['connection_name'] = lang('Main');
1952                        $data['connections']['default_phone']['connection_value'] = $tdata[3];
1953                        $data['connections']['default_email']['connection_name'] = lang('Main');
1954                        $data['connections']['default_email']['connection_value'] = $tdata[4];
1955                        $data['is_quick_add'] = true;
1956                        $boPeople = CreateObject('contactcenter.bo_people_catalog');
1957
1958                        $result = $boPeople->quick_add($data);
1959                        if ($result)
1960                        {
1961                            $this->page_info['changed'] = true;
1962
1963                            if ($echo)
1964                            {
1965                                echo serialize(array(
1966                                    'msg'    => lang('Entry added with success!'),
1967                                    'status' => 'ok'
1968                                ));
1969                            }
1970                            else
1971                                {
1972                                    return serialize(array(
1973                                        'msg'    => lang('Entry added with success!'),
1974                                        'status' => 'ok',
1975                                        'conn'   => $boPeople->get_connections($result)
1976                                    ));
1977                                }
1978                        }
1979                        else
1980                        {
1981                            if ($echo)
1982                            {
1983                                echo serialize(array(
1984                                    'msg'    => lang('Problems on adding your Contact. No Contact added!'),
1985                                    'status' => 'error'
1986                                ));
1987                            }
1988                            else
1989                                {
1990                                    echo serialize(array(
1991                                        'msg'    => lang('Problems on adding your Contact. No Contact added!'),
1992                                        'status' => 'error'
1993                                    ));
1994                                }
1995                        }
1996
1997                        $this->save_session();
1998
1999                }
2000
2001                /*!
2002
2003                        @function add_group
2004                        @abstract Adds a new Group using the Add Group interface
2005                        @author Nilton Emilio Buhrer Neto
2006
2007                        @param string $sdata Serialized data
2008                */
2009                function add_group($sdata)
2010                {
2011                        $sdata = str_replace('\\"', '"', $sdata);
2012                        $tdata = unserialize($sdata);
2013                        $new_tdata = array();
2014
2015                        if (!$tdata)
2016                        {
2017                                echo serialize(array(
2018                                        'msg'    => lang('Problems on adding your Contact. Invalid Data came from client. No Contact added!'),
2019                                        'status' => 'abort'
2020                                ));
2021
2022                                return;
2023                        }
2024
2025                        foreach($tdata as $tmp)
2026                                $new_tdata[] = $tmp;
2027
2028                        $data['title'] = $new_tdata[0];
2029                        $data['contact_in_list'] = $new_tdata[1];
2030                        $data['id_group'] = $new_tdata[2];
2031                        $data['old_contacts_in_list'] = $new_tdata[3];
2032                       
2033                        foreach ($data['old_contacts_in_list'] as $id_connection)
2034                        {
2035                                $boConn = CreateObject('contactcenter.bo_connection');
2036
2037                                $id_contact = $boConn->get_contact_id_by_connection($id_connection);
2038                                $contact = CreateObject('contactcenter.so_contact', $id_contact);
2039                                $contact->set_field("last_status", 'U');
2040                                $contact->set_field("last_update",time()."000");
2041                                $contact->commit();
2042                        }
2043                                               
2044                        $contactWOemail = false;
2045
2046                        foreach ($data['contact_in_list'] as $id_connection)
2047                        {
2048                                $boConn = CreateObject('contactcenter.bo_connection');
2049                               
2050                                $id_contact = $boConn->get_contact_id_by_connection($id_connection);
2051                                $contact = CreateObject('contactcenter.so_contact', $id_contact);
2052                                $contact->set_field("last_status", 'U');
2053                                $contact->set_field("last_update",time()."000");
2054                                $contact->commit();
2055                               
2056                                if (!$contactWOemail)
2057                                {
2058                                        $type = $boConn->get_connection_type_by_conn_id($id_connection);
2059                                        if ($type != 1)
2060                                        {
2061                                                $contactWOemail = true;
2062                                        }
2063                                }
2064                        }
2065
2066 
2067                        $acumulatedErrors = '';
2068
2069                        $actualCatalog = $this->get_actual_catalog();
2070                        for ($i = 0; $i < count($data['contact_in_list']); $i++)
2071                        {
2072                            if (preg_match('/ldap:.*:.*/', $data['contact_in_list'][$i])) // from ldap
2073                            {
2074                                list(, $level, $dn) = explode(':', $data['contact_in_list'][$i]);
2075
2076                                // pesquisa os dados, insere no catálogo e modifica
2077                                // a entrada em $data['contact_in_list'][$i]
2078                                $set_catalog = $this->set_catalog($level, false);
2079                                $contact_data = unserialize($this->get_catalog_add_contact($dn, false));
2080                                $tmp_contact[] = $contact_data[0][0];
2081                                $tmp_contact[] = $contact_data[1][0];
2082                                $tmp_contact[] = $contact_data[2][0];
2083                                $tmp_contact[] = $contact_data[3][0];
2084                                $tmp_contact[] = $contact_data[4][0];
2085
2086                                // Determinar o id_connection
2087                                $id_contact = unserialize($this->quick_add(serialize($tmp_contact), false));
2088
2089                                switch ($id_contact['status'])
2090                                {
2091                                    case 'ok' :
2092                                        foreach ($id_contact['conn'] as $connection)
2093                                        {
2094                                            if ($connection['id_type'] == 1)
2095                                            {
2096                                                $data['contact_in_list'][$i] = $connection['id_connection'];
2097                                            }
2098                                        }
2099                                        break;
2100
2101                                    case 'alreadyExists': // if e-mail exists get their id_connection from people_catalog
2102                                        $data['contact_in_list'][$i] = $id_contact['id_connection'];
2103
2104                                    default:
2105                                        $acumulatedErrors += $id_contact['msg']."\n";
2106                                }
2107                                unset($tmp_contact);
2108
2109                            }
2110                        }
2111                        $set_catalog = $this->set_catalog($actualCatalog['data'], false); // retorna ao catálogo original.
2112                        $boGroup = CreateObject('contactcenter.bo_group_manager');
2113                        $id = $boGroup -> add_group($data);
2114
2115                        if ($id)
2116                        {
2117                                $this->page_info['changed'] = true;
2118                               
2119                                if (!$contactWOemail)
2120                                        echo serialize(array(
2121                                                'msg'    => lang('Entry added with success!'),
2122                                                'status' => 'ok'
2123                                                ));
2124                                else
2125                                        echo serialize(array(
2126                                                'msg'    => lang('Entry added with success. But some contacts will not receive or send messages.'),
2127                                                'status' => 'warning'
2128                                                ));
2129                        }
2130                        else
2131                        {
2132                                echo serialize(array(
2133                                        'msg'    => lang('Problems on adding your Contact. No Contact added!'),
2134                                        'status' => 'error'
2135                                ));
2136                        }
2137
2138                        $this->save_session();
2139                }
2140
2141                /*!
2142
2143                        @function remove_group
2144                        @abstract Removes a group if the user has the right to do it
2145                        @author Nilton Emilio Buhrer Neto
2146                        @param (integer) $id The id to be removed
2147
2148                */
2149                function remove_group($id)
2150                {
2151                                $soGroup = CreateObject('contactcenter.so_group');
2152                                $data = array ('id_group' => $id);
2153                                if($soGroup -> delete($data)) {
2154                                        echo serialize(array(
2155                                                'msg'    => lang('Removed Entry ID '.$id.'!'),
2156                                                'status' => 'ok'
2157                                        ));
2158                                }
2159                                else {
2160                                        echo serialize(array(
2161                                                'msg'    => lang('Problems on adding your Contact. No Contact added!'),
2162                                                'status' => 'error'
2163                                        ));
2164                                }
2165
2166                        $this->save_session();
2167                }
2168
2169
2170                function remove_all_entries (){
2171
2172                        $error = false;
2173                        $this->all_entries = $this->bo->catalog->get_all_entries_ids();
2174
2175                        foreach($this->all_entries as $index => $id) {
2176                                $result = $this->bo->catalog->remove_single_entry($id);
2177                                if(!$result) {
2178                                        $error = true;
2179                                        break;
2180                                }
2181                        }
2182
2183                        if(!$error) {
2184                                echo serialize(array(
2185                                        'msg'    => lang('Removed Entry ID '.$id.'!'),
2186                                        'status' => 'ok'
2187                                ));
2188                        }
2189                        else {
2190                                echo serialize(array(
2191                                        'msg'    => lang('Couldn\'t remove this entry. Inform the Site Admin!'),
2192                                        'status' => 'fail'
2193                                ));
2194                        }
2195
2196                        $this->save_session();
2197                }
2198
2199                /*!
2200
2201                        @function remove_entry
2202                        @abstract Removes an entry if the user has the right to do it
2203                        @author Raphael Derosso Pereira
2204
2205                        @param (integer) $id The id to be removed
2206
2207                */
2208                function remove_entry ($id)
2209                {
2210                        if (!is_int($id))
2211                        {
2212                                echo lang('Couldn\'t remove entry! Problem passing data to the server. Please inform admin!');
2213                                return;
2214                        }
2215
2216                        $this->page_info['changed'] = true;
2217                        $result = $this->bo->catalog->remove_single_entry($id);
2218
2219                        if ($result)
2220                        {
2221                                if ($pos = array_search($id, $this->page_info['actual_entries']))
2222                                {
2223                                        unset($this->page_info['actual_entries'][$pos]);
2224                                }
2225
2226                                $temp = false;
2227                                reset($this->page_info['actual_entries']);
2228                                foreach($this->page_info['actual_entries'] as $t)
2229                                {
2230                                        $temp[] = $t;
2231                                }
2232
2233                                $this->page_info['actual_entries'] = $temp;
2234
2235                                echo serialize(array(
2236                                        'msg'    => lang('Removed Entry ID '.$id.'!'),
2237                                        'status' => 'ok'
2238                                ));
2239                        }
2240                        else
2241                        {
2242                                echo serialize(array(
2243                                        'msg'    => lang('Couldn\'t remove this entry. Inform the Site Admin!'),
2244                                        'status' => 'fail'
2245                                ));
2246                        }
2247
2248                        $this->save_session();
2249                }
2250
2251
2252                /*!
2253
2254                        @function post_full_add
2255                        @abstract Saves all the information altered/entered in the Full Add
2256                                window
2257                        @author Raphael Derosso Pereira
2258
2259                */
2260                function post_full_add()
2261                {
2262                        $data =  $_POST['data'];
2263                        // Exceptions!!! utf8 special chars.
2264                        $data = preg_replace("/\%u2(\d+)(\d+)(\d+)/","-",$data);
2265                        $data = unserialize(str_replace('\\"', '"', $data));
2266                        $this -> bo -> catalog = CreateObject('contactcenter.bo_people_catalog');
2267
2268                        if (!is_array($data))
2269                        {
2270                                echo serialize(array(
2271                                        'msg' => lang('<p>Some problem receiving data from browser. This is probably a bug in ContactCenter<br>'.
2272                                                  'Please go to eGroupWare Bug Reporting page and report this bug.<br>'.
2273                                                          'Sorry for the inconvenient!<br><br>'.
2274                                                          '<b><i>ContactCenter Developer Team</i></b></p>'),
2275                                        'status' => 'fatal'
2276                                ));
2277                                return;
2278                        }
2279//                      print_r($data);
2280//                      echo '<br><br>';
2281
2282                        $replacer = $data['commercialAnd'];
2283                        unset($data['commercialAnd']);
2284                        if (!is_string($replacer) or strpos($replacer, "'") or strpos($replacer, '"'))
2285                        {
2286                                echo serialize(array(
2287                                        'msg' => lang('Invalid \'&\' replacer! This may be an attempt to bypass Security! Action aborted!'),
2288                                        'status' => 'fatal'
2289                                ));
2290
2291                                return;
2292                        }
2293
2294                        if ($data['id_contact'])
2295                        {
2296                                $id = $data['id_contact'];
2297                                $id_photo = $id;
2298                                unset($data['id_contact']);
2299                        }
2300                        else
2301                        {
2302                                $id_photo = '_new_';
2303                        }
2304
2305                        /*
2306                         * Process Photo, if available
2307                         */
2308                        $sleep_count = 0;
2309                        $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
2310                        while($photo_ok[0]{0} !== 'o' and $photo_ok[1]{0} === 'y')
2311                        {
2312                                sleep(1);
2313                                $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
2314                                $sleep_count++;
2315
2316                                if ($sleep_count > 35)
2317                                {
2318                                        // TODO
2319                                        return;
2320                                }
2321                        }
2322                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'n'));
2323
2324                        if (isset($this->page_info['photos'][$id_photo]))
2325                        {
2326                                if (array_search($this->page_info['photos'][$id_photo]['status'], array('changed', 'sync')) === false)
2327                                {
2328                                        echo serialize(array(
2329                                                'msg' => $this->page_info['photos'][$id_photo]['msg'],
2330                                                'status' => $this->page_info['photos'][$id_photo]['status']
2331                                        ));
2332
2333                                        return;
2334                                }
2335
2336                                $data['photo'] = $this->page_info['photos'][$id_photo]['content'];
2337                                unset($this->page_info['photos'][$id_photo]);
2338                                $this->save_session();
2339                        }
2340
2341                        /*
2342                         * Arrange Date so it gets inserted correctly
2343                         */
2344
2345                        $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
2346
2347                        $j = 0;
2348                        for ($i = 0; $i < 5; $i+=2)
2349                        {
2350                                switch($dateformat{$i})
2351                                {
2352                                        case 'Y':
2353                                                $date[$j]['size'] = 4;
2354                                                $date[$j]['digit'] = 'Y';
2355                                                break;
2356
2357                                        case 'm':
2358                                        case 'M':
2359                                                $date[$j]['size'] = 2;
2360                                                $date[$j]['digit'] = 'M';
2361                                                break;
2362
2363                                        case 'd':
2364                                                $date[$j]['size'] = 2;
2365                                                $date[$j]['digit'] = 'D';
2366                                }
2367                                $j++;
2368                        }
2369                        $datecount = 0;
2370
2371                        /* Verify Data and performs insertion/update */
2372                        foreach($data as $field => $value)
2373                        {
2374
2375                                switch($field)
2376                                {
2377                                        case 'names_ordered':
2378                                                $data[$field] = addslashes(rawurldecode($value));
2379                                        case 'corporate_name':
2380                                        case 'job_title':
2381                                        case 'department':
2382                                        case 'web_page':
2383                                        case 'alias':
2384                                        case 'given_names':
2385                                        case 'family_names':
2386                                        case 'pgp_key':
2387                                        case 'notes':
2388                                                $data[$field] = addslashes(rawurldecode($data[$field]));
2389                                                break;
2390
2391                                        case 'id_status':
2392                                        case 'id_prefix':
2393                                        case 'id_suffix':
2394                                                if ($data[$field] == 0)
2395                                                {
2396                                                        unset($data[$field]);
2397                                                }
2398                                                break;
2399
2400                                        case 'birthdate_0':
2401                                        case 'birthdate_1':
2402                                        case 'birthdate_2':
2403                                        case 'birthdate':
2404                                       
2405                                                if($field == 'birthdate'){
2406                                                        $array_birth = explode("/",$data[$field]);                                                     
2407                                                        $date['value'][2] = $array_birth[2];
2408                                                        $date['value'][1] = $array_birth[1];
2409                                                        $date['value'][0] = $array_birth[0];                                           
2410                                                }else{                                 
2411                                                        switch($date[$datecount]['digit'])
2412                                                        {
2413                                                                case 'Y':
2414                                                                        $date['value'][2] = (int) $data[$field];
2415                                                                        break;
2416       
2417                                                                case 'M':
2418                                                                        $date['value'][0] = (int) $data[$field];
2419                                                                        break;
2420       
2421                                                                case 'D':
2422                                                                        $date['value'][1] = (int) $data[$field];
2423                                                                        break;
2424                                                        }
2425                                                        unset($data[$field]);
2426                                                }
2427                                               
2428                                                $datecount++;
2429
2430                                                if ($datecount != 3)
2431                                                {
2432                                                        break;
2433                                                }
2434
2435                                                if($date['value'][0] =='' && $date['value'][1] =='' && $date['value'][2] ==''){
2436                                                        $data['birthdate'] = null;
2437                                                        break;
2438                                                }
2439                                                if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
2440                                                {
2441                                                        echo serialize(array(
2442                                                                'msg' => lang('Invalid Date'),
2443                                                                'status' => 'invalid_data'
2444                                                        ));
2445                                                        return;
2446                                                }
2447                                                if( $date['value'][2] != "" && $date['value'][0] != "" && $date['value'][1] != ""){
2448                                                        $data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
2449                                                }
2450                                                break;
2451
2452                                        case 'sex':
2453                                                if ($data[$field] !== 'M' and $data[$field] !== 'F')
2454                                                {
2455                                                        echo serialize(array(
2456                                                                'msg' => lang('Invalid Sex'),
2457                                                                'status' => 'invalid_data'
2458                                                        ));
2459                                                        return;
2460                                                }
2461                                                break;
2462
2463
2464                                        case 'addresses':
2465                                                /* Insert new cities/states */
2466                                                if (isset($value['new_states']))
2467                                                {
2468                                                        foreach($value['new_states'] as $type => $state_info)
2469                                                        {
2470                                                                $index = 'address'.$type;
2471
2472                                                                $id_state = $this->bo->catalog->add_state($state_info);
2473                                                                $data['addresses'][$index]['id_state'] = $id_state;
2474
2475                                                                if ($value['new_cities'][$type])
2476                                                                {
2477                                                                        $data[$field]['new_cities'][$type]['id_state'] = $id_state;
2478                                                                }
2479                                                        }
2480
2481                                                        unset($data['addresses']['new_states']);
2482                                                }
2483
2484                                                if (isset($value['new_cities']))
2485                                                {
2486                                                        foreach($value['new_cities'] as $type => $city_info)
2487                                                        {
2488                                                                $index = 'address'.$type;
2489
2490                                                                $id_city = $this->bo->catalog->add_city($city_info);
2491                                                                $data['addresses'][$index]['id_city'] = $id_city;
2492                                                        }
2493
2494                                                        unset($data['addresses']['new_cities']);
2495                                                }
2496
2497                                        break;
2498
2499                                        case 'birthdate':
2500                                        case 'connections':
2501                                        case 'photo':
2502                                                /* Does nothing... */
2503                                                break;
2504                                        case 'groups':
2505                                                $groups = $data['groups'];
2506                                                unset($data['groups']);
2507                                                break;
2508
2509                                        default:
2510                                                echo serialize(array(
2511                                                        'msg' => lang('Invalid field: ').$field,
2512                                                        'status' => 'invalid_data'
2513                                                ));
2514                                                return;
2515                                }
2516                        }
2517
2518                        if (!is_null($id) and $id !== '')
2519                        {
2520                                $old_connections = $this->bo->catalog->get_connections($id);
2521                                $id = $this->bo->catalog->update_single_info($id, $data);
2522                                $result = array(
2523                                        'msg' => lang('Updated Successfully!'),
2524                                        'status' => 'ok'
2525                                );
2526                        }
2527                        else
2528                        {
2529                                $id = $this->bo->catalog->add_single_entry($data);
2530                                $result = array(
2531                                        'msg' => lang('Entry Added Successfully!'),
2532                                        'status' => 'ok'
2533                                );
2534                        }
2535
2536                        if (!($id))
2537                        {
2538                                $result = array(
2539                                        'msg' => lang('Some problem occured when trying to insert/update contact information.<br>'.
2540                                                   'Report the problem to the Administrator.'),
2541                                        'status' => 'fail'
2542                                );
2543                        }
2544                        else
2545                        {
2546                                if (isset($old_connections))
2547                                        $this->bo->catalog->update_contact_groups($id, $groups, $old_connections);
2548                                else
2549                                        $this->bo->catalog->update_contact_groups($id, $groups);
2550                        }
2551
2552                        echo serialize($result);
2553                }
2554
2555
2556                function post_full_add_shared()
2557                {
2558                        $data =  $_POST['data'];
2559                        // Exceptions!!! utf8 special chars.
2560                        $data = preg_replace("/\%u2(\d+)(\d+)(\d+)/","-",$data);
2561                        $data = unserialize(str_replace('\\"', '"', $data));
2562                        $this -> bo -> catalog = CreateObject('contactcenter.bo_shared_people_manager');
2563
2564                        if (!is_array($data))
2565                        {
2566                                echo serialize(array(
2567                                        'msg' => lang('<p>Some problem receiving data from browser. This is probably a bug in ContactCenter<br>'.
2568                                                  'Please go to eGroupWare Bug Reporting page and report this bug.<br>'.
2569                                                          'Sorry for the inconvenient!<br><br>'.
2570                                                          '<b><i>ContactCenter Developer Team</i></b></p>'),
2571                                        'status' => 'fatal'
2572                                ));
2573                                return;
2574                        }
2575//                      print_r($data);
2576//                      echo '<br><br>';
2577
2578                        $replacer = $data['commercialAnd'];
2579                        unset($data['commercialAnd']);
2580                        if (!is_string($replacer) or strpos($replacer, "'") or strpos($replacer, '"'))
2581                        {
2582                                echo serialize(array(
2583                                        'msg' => lang('Invalid \'&\' replacer! This may be an attempt to bypass Security! Action aborted!'),
2584                                        'status' => 'fatal'
2585                                ));
2586
2587                                return;
2588                        }
2589
2590                        if ($data['id_contact'])
2591                        {
2592                                $id = $data['id_contact'];
2593                                $id_photo = $id;
2594                                unset($data['id_contact']);
2595                        }
2596                        else
2597                        {
2598                                $id_photo = '_new_';
2599                        }
2600
2601                        if ($data['owner'])
2602                        {
2603                                $owner = $data['owner'];
2604                                unset($data['owner']);
2605                        }
2606                        /*
2607                         * Process Photo, if available
2608                         */
2609                        $sleep_count = 0;
2610                        $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
2611                        while($photo_ok[0]{0} !== 'o' and $photo_ok[1]{0} === 'y')
2612                        {
2613                                sleep(1);
2614                                $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
2615                                $sleep_count++;
2616
2617                                if ($sleep_count > 35)
2618                                {
2619                                        // TODO
2620                                        return;
2621                                }
2622                        }
2623                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'n'));
2624
2625                        if (isset($this->page_info['photos'][$id_photo]))
2626                        {
2627                                if (array_search($this->page_info['photos'][$id_photo]['status'], array('changed', 'sync')) === false)
2628                                {
2629                                        echo serialize(array(
2630                                                'msg' => $this->page_info['photos'][$id_photo]['msg'],
2631                                                'status' => $this->page_info['photos'][$id_photo]['status']
2632                                        ));
2633
2634                                        return;
2635                                }
2636
2637                                $data['photo'] = $this->page_info['photos'][$id_photo]['content'];
2638                                unset($this->page_info['photos'][$id_photo]);
2639                                $this->save_session();
2640                        }
2641
2642                        /*
2643                         * Arrange Date so it gets inserted correctly
2644                         */
2645
2646                        $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
2647
2648                        $j = 0;
2649                        for ($i = 0; $i < 5; $i+=2)
2650                        {
2651                                switch($dateformat{$i})
2652                                {
2653                                        case 'Y':
2654                                                $date[$j]['size'] = 4;
2655                                                $date[$j]['digit'] = 'Y';
2656                                                break;
2657
2658                                        case 'm':
2659                                        case 'M':
2660                                                $date[$j]['size'] = 2;
2661                                                $date[$j]['digit'] = 'M';
2662                                                break;
2663
2664                                        case 'd':
2665                                                $date[$j]['size'] = 2;
2666                                                $date[$j]['digit'] = 'D';
2667                                }
2668                                $j++;
2669                        }
2670                        $datecount = 0;
2671
2672                        /* Verify Data and performs insertion/update */
2673                        foreach($data as $field => &$value)
2674                        {
2675                                if ($value == '' or is_null($value))
2676                                {
2677                                        unset($data[$field]);
2678                                        continue;
2679                                }
2680
2681                                switch($field)
2682                                {
2683                                        case 'corporate_name':
2684                                        case 'job_title':
2685                                        case 'department':
2686                                        case 'web_page':
2687                                        case 'alias':
2688                                        case 'given_names':
2689                                        case 'family_names':
2690                                        case 'names_ordered':
2691                                        case 'pgp_key':
2692                                        case 'notes':
2693                                        case 'photo':
2694                                                $data[$field] = urldecode( $value );
2695                                                break;
2696
2697                                        case 'id_status':
2698                                        case 'id_prefix':
2699                                        case 'id_suffix':
2700                                                if ($data[$field] == 0)
2701                                                {
2702                                                        unset($data[$field]);
2703                                                }
2704                                                break;
2705
2706                                        case 'birthdate_0':
2707                                        case 'birthdate_1':
2708                                        case 'birthdate_2':
2709
2710                                                switch($date[$datecount]['digit'])
2711                                                {
2712                                                        case 'Y':
2713                                                                $date['value'][2] = (int) $data[$field];
2714                                                                break;
2715
2716                                                        case 'M':
2717                                                                $date['value'][0] = (int) $data[$field];
2718                                                                break;
2719
2720                                                        case 'D':
2721                                                                $date['value'][1] = (int) $data[$field];
2722                                                                break;
2723                                                }
2724                                                unset($data[$field]);
2725                                                $datecount++;
2726
2727                                                if ($datecount != 3)
2728                                                {
2729                                                        break;
2730                                                }
2731
2732                                                if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
2733                                                {
2734                                                        echo serialize(array(
2735                                                                'msg' => lang('Invalid Date'),
2736                                                                'status' => 'invalid_data'
2737                                                        ));
2738                                                        return;
2739                                                }
2740
2741                                                $data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
2742                                                break;
2743
2744                                        case 'sex':
2745                                                if ($data[$field] !== 'M' and $data[$field] !== 'F')
2746                                                {
2747                                                        echo serialize(array(
2748                                                                'msg' => lang('Invalid Sex'),
2749                                                                'status' => 'invalid_data'
2750                                                        ));
2751                                                        return;
2752                                                }
2753                                                break;
2754
2755
2756                                        case 'addresses':
2757                                                /* Insert new cities/states */
2758                                                if (isset($value['new_states']))
2759                                                {
2760                                                        foreach($value['new_states'] as $type => $state_info)
2761                                                        {
2762                                                                $index = 'address'.$type;
2763
2764                                                                $id_state = $this->bo->catalog->add_state($state_info);
2765                                                                $data['addresses'][$index]['id_state'] = $id_state;
2766
2767                                                                if ($value['new_cities'][$type])
2768                                                                {
2769                                                                        $value['new_cities'][$type]['id_state'] = $id_state;
2770                                                                }
2771                                                        }
2772
2773                                                        unset($data['addresses']['new_states']);
2774                                                }
2775
2776                                                if (isset($value['new_cities']))
2777                                                {
2778                                                        foreach($value['new_cities'] as $type => $city_info)
2779                                                        {
2780                                                                $index = 'address'.$type;
2781
2782                                                                $id_city = $this->bo->catalog->add_city($city_info);
2783                                                                $data['addresses'][$index]['id_city'] = $id_city;
2784                                                        }
2785
2786                                                        unset($data['addresses']['new_cities']);
2787                                                }
2788
2789                                        break;
2790
2791                                        case 'connections':
2792                                                /* Does nothing... */
2793                                                break;
2794
2795                                        default:
2796                                                echo serialize(array(
2797                                                        'msg' => lang('Invalid field: ').$field,
2798                                                        'status' => 'invalid_data'
2799                                                ));
2800                                                return;
2801                                }
2802                        }
2803
2804                        $code = '$id = $this->bo->catalog->';
2805
2806                        if (!is_null($id) and $id !== '')
2807                        {
2808                                $code .= $code.'update_single_info($id, $data);';
2809                                $result = array(
2810                                        'msg' => lang('Updated Successfully!'),
2811                                        'status' => 'ok'
2812                                );
2813                        }
2814                        else
2815                        {
2816                                $code .= 'add_single_entry($data,'.$owner.');';
2817                                $result = array(
2818                                        'msg' => lang('Entry Added Successfully!'),
2819                                        'status' => 'ok'
2820                                );
2821                        }
2822
2823                        eval($code);
2824
2825                        if (!($id))
2826                        {
2827                                $result = array(
2828                                        'msg' => lang('Some problem occured when trying to insert/update contact information.<br>'.
2829                                                   'Report the problem to the Administrator.'),
2830                                        'status' => 'fail'
2831                                );
2832                        }
2833
2834                        echo serialize($result);
2835}
2836                /*!
2837
2838                        @function post_photo
2839                        @abstract Wrapper to post a photo without reload a page.
2840                        @author Raphael Derosso Pereira
2841
2842                */
2843                function post_photo($id)
2844                {
2845                        //print_r($_FILES);
2846                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'y'));
2847
2848                        if (!is_array($_FILES) and is_array(!$_FILES['cc_pd_photo']))
2849                        {
2850                                $this->page_info['photos'][$id]['status'] = 'no_upload';
2851                                $this->page_info['photos'][$id]['msg'] = lang('No Photos uploaded to Server.');
2852
2853                                $this->save_session();
2854                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2855                                return;
2856                        }
2857
2858                        if (!function_exists('imagecreate'))
2859                        {
2860                                $this->page_info['photos'][$id]['status'] = 'no_GD_lib';
2861                                $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.');
2862
2863                                $this->save_session();
2864                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2865                                return;
2866                        }
2867
2868                        // TODO: Get Max Size from preferences!
2869                        if ($_FILES['cc_pd_photo']['size'] > 1000000)
2870                        {
2871                                $this->page_info['photos'][$id]['status'] = 'too_large';
2872                                $this->page_info['photos'][$id]['msg'] = lang('Image too large! ContactCenter limits the image size to 1 Mb');
2873
2874                                $this->save_session();
2875                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2876                                return;
2877                        }
2878
2879                        if ($_FILES['cc_pd_photo']['error'])
2880                        {
2881                                $this->page_info['photos'][$id]['status'] = 'error';
2882                                $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'];
2883
2884                                $this->save_session();
2885                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2886                                return;
2887                        }
2888
2889                        switch($_FILES['cc_pd_photo']['type'])
2890                        {
2891                                case 'image/jpeg':
2892                                case 'image/pjpeg':
2893                                        $src_img = imagecreatefromjpeg($_FILES['cc_pd_photo']['tmp_name']);
2894                                        if ($src_img == '')
2895                                        {
2896                                                $bogus = true;
2897                                        }
2898                                        break;
2899
2900                                case 'image/png':
2901                                case 'image/x-png':
2902                                        $src_img = imagecreatefrompng($_FILES['cc_pd_photo']['tmp_name']);
2903                                        if ($src_img == '')
2904                                        {
2905                                                $bogus = true;
2906                                        }
2907                                        break;
2908
2909                                case 'image/gif':
2910                                        $src_img = imagecreatefromgif($_FILES['cc_pd_photo']['tmp_name']);
2911                                        if ($src_img == '')
2912                                        {
2913                                                $bogus = true;
2914                                        }
2915                                        break;
2916
2917                                default:
2918
2919                                        $this->page_info['photos'][$id]['status'] = 'invalid_image';
2920                                        $this->page_info['photos'][$id]['msg'] = lang('The file must be an JPEG, PNG or GIF Image.');
2921
2922                                        $this->save_session();
2923                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2924                                        return;
2925                        }
2926
2927                        if ($bogus)
2928                        {
2929                                        $this->page_info['photos'][$id]['status'] = 'invalid_file';
2930                                        $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
2931
2932                                        $this->save_session();
2933                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2934                                        return;
2935                        }
2936
2937                        $img_size = getimagesize($_FILES['cc_pd_photo']['tmp_name']);
2938                        $dst_img = imagecreatetruecolor(60, 80);
2939
2940                        if (!imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, 60, 80, $img_size[0], $img_size[1]))
2941                        {
2942                                $this->page_info['photos'][$id]['status'] = 'invalid_file';
2943                                $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
2944
2945                                $this->save_session();
2946                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2947                                return;
2948                        }
2949
2950                        ob_start();
2951                        imagepng($dst_img);
2952                        $this->page_info['photos'][$id]['content'] = ob_get_contents();
2953                        ob_end_clean();
2954
2955                        $this->page_info['photos'][$id]['status'] = 'changed';
2956                        $this->page_info['photos'][$id]['msg'] = lang('Photo Successfully Updated!');
2957
2958                        $this->save_session();
2959
2960                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2961
2962                        imagedestroy($src_img);
2963                        imagedestroy($dst_img);
2964                        echo 'ok';
2965                        return;
2966                }
2967
2968
2969                /*!
2970
2971                        @function get_photo
2972                        @abstract Returns the photo to the browser
2973                        @author Raphael Derosso Pereira
2974
2975                */
2976                function get_photo($id)
2977                {
2978                        $fields = $this->bo->catalog->get_fields(false);
2979                        $fields['photo'] = true;
2980
2981                        $contact = $this->bo->catalog->get_single_entry($id, $fields);
2982
2983                        if (!$contact['photo'])
2984                        {
2985                                header('Content-type: image/png');
2986                                echo file_get_contents(PHPGW_INCLUDE_ROOT.'/contactcenter/templates/default/images/photo_celepar.png');
2987                                return;
2988                        }
2989
2990                        header('Content-type: image/jpeg');
2991
2992                        $tmpDir = $GLOBALS['phpgw_info']['server']['temp_dir'];
2993                        $imagem_temp = fopen("$tmpDir/img_tmp","wb+");
2994                        fwrite($imagem_temp,$contact['photo']);
2995                        fclose($imagem_temp);                   
2996                        $exif = exif_read_data("$tmpDir/img_tmp","IDF0");
2997                        $ort = 1;
2998                        if ($exif['Orientation'] != '') {
2999                                $ort = $exif['Orientation'];
3000                        }
3001                        unlink("$tmpDir/img_tmp");                     
3002
3003                        $photo = imagecreatefromstring ($contact['photo']);
3004                        $width = imagesx($photo);
3005                        $height = imagesy($photo);
3006                        $twidth = 70;
3007                        $theight = 90;
3008                        $small_photo = imagecreatetruecolor ($twidth, $theight);
3009                        imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
3010                       
3011                        if ($ort != 1){
3012                                switch($ort)
3013                                {
3014                                        case 3:
3015                                                $rotate = imagerotate($small_photo, 180, 0);
3016                                                break;
3017                                        case 6:
3018                                                $rotate = imagerotate($small_photo, 270, 0);
3019                                                break;
3020                                        case 8:
3021                                                $rotate = imagerotate($small_photo, 90, 0);
3022                                                break;
3023                                }
3024                        } else $rotate = imagerotate($small_photo, 0, 0);
3025       
3026                        imagejpeg($rotate,"",100);
3027                        ImageDestroy($rotate);
3028                        ImageDestroy($small_photo);
3029
3030                        return;
3031                }
3032
3033                /*!
3034
3035                        @function get_states
3036                        @abstract Echos a serialized array containing all the states for the given country
3037                        @author Raphael Derosso Pereira
3038
3039                        @params $id_country The ID of the Country that contains the requested states
3040
3041                */
3042                function get_states($id_country)
3043                {
3044                        $states = $this->bo->catalog->get_all_states($id_country);
3045
3046                        if (!$states)
3047                        {
3048                                $result = array(
3049                                        'msg'    => lang('No States found for this Country.'),
3050                                        'status' => 'empty'
3051                                );
3052
3053                                echo serialize($result);
3054                                return;
3055                        }
3056
3057                        $result = array(
3058                                'msg'    => lang('States Successfully retrieved!'),
3059                                'status' => 'ok'
3060                        );
3061
3062                        foreach ($states as $state_info)
3063                        {
3064                                $result['data'][$state_info['id_state']] = $state_info['name'];
3065
3066                                if ($state_info['symbol'])
3067                                {
3068                                        $result['data'][$state_info['id_state']] .= ', '.$state_info['symbol'];
3069                                }
3070                        }
3071
3072                        echo serialize($result);
3073                }
3074
3075                /*!
3076
3077                        @function get_cities
3078                        @abstract Echos a serialized array containing all the cities of a given state
3079                        @author Raphael Derosso Pereira
3080
3081                        @param $id_country The ID of the Country that has the specified Cities (in case the
3082                                Country doesn't have any States)
3083                        @param $id_state The ID of the State that has the Cities requested
3084
3085                */
3086                function get_cities($id_country, $id_state=false)
3087                {
3088                        $cities = $this->bo->catalog->get_all_cities($id_country, $id_state);
3089
3090                        if (!$cities)
3091                        {
3092                                $result = array(
3093                                        'msg'    => lang('No Cities found for this State.'),
3094                                        'status' => 'empty'
3095                                );
3096
3097                                echo serialize($result);
3098                                return;
3099                        }
3100
3101                        $result = array(
3102                                'msg'    => lang('Cities Successfully retrieved!'),
3103                                'status' => 'ok'
3104                        );
3105
3106                        foreach ($cities as $city_info)
3107                        {
3108                                $result['data'][$city_info['id_city']] = $city_info['name'];
3109                        }
3110
3111                        echo serialize($result);
3112                }
3113
3114                //Traduz o campo na busca completa por entradas no catálogo do usuário.
3115                function aux_full_search ($field,$isldap) {
3116                        $retorno = '';
3117                        if($isldap) {
3118                                switch($field) {
3119                                        case 'mail':
3120                                                $retorno = 'contact.connection.mail';
3121                                                break;
3122                                        case 'phone':
3123                                                $retorno = 'contact.connection.phone';
3124                                                break;
3125                                }
3126                        }
3127                        else {
3128                                switch($field) {
3129                                        case 'corporate':
3130                                                $retorno = 'contact.corporate_name';
3131                                                break;
3132                                        case 'mail':
3133                                        case 'phone':
3134                                                $retorno = 'contact.contact_connection.connection.connection_value';
3135                                                break;
3136                                }
3137                        }
3138                        return $retorno;
3139                }
3140
3141                /*!
3142
3143                        @function search
3144                        @abstract Echos a serialized array containing the IDs
3145                                of the entries that matches the search argument
3146                        @author Raphael Derosso Pereira
3147                        @author Mário César Kolling (external catalogs)
3148
3149                        @param string $str_data A serialized array with two informations:
3150                                $data = array(
3151                                        'search_for' => (string),
3152                                        'recursive'  => (boolean),
3153                                );
3154
3155                */
3156                // SERPRO
3157                function search($str_data)
3158                {
3159                        $data = unserialize($str_data);
3160                        // It's an external catalog?
3161                        $external = $this->bo->is_external($this->page_info['actual_catalog']);
3162                        $full_search = isset($data['full_search'])?$data['full_search']:false;
3163                       
3164                        if (!is_array($data) || (!$data['search_for'] && !$full_search) || !is_array($data['fields']))
3165                        {
3166                                echo serialize(array(
3167                                        'msg'    => lang('Invalid parameters'),
3168                                        'status' => 'abort'
3169                                ));
3170
3171                                return array('error' => lang('Invalid parameters'));
3172                        }
3173
3174
3175                        /*
3176                         * TODO: look into the database to discover the database's encoding and convert the search_for field accordingly
3177                         */
3178                        // Support search parameters with accentuation
3179                        if ($this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
3180/**rev 104**/
3181                                //$this->page_info['actual_catalog']['class'] != 'bo_group_manager')
3182                                $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
3183                                $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
3184                                $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
3185/****/
3186                        {
3187
3188                                $data['search_for'] = utf8_encode($data['search_for']);
3189                        }
3190
3191                        $rules  = array();
3192
3193                        if ($data['search_for'] === '*')
3194                        {
3195                                $rules = array(
3196                                        0 => array(
3197                                                'field' => $data['fields']['search'],
3198                                                'type'  => 'LIKE',
3199                                                'value' => '%'
3200                                        )
3201                                );
3202                        }
3203                        else
3204                        {
3205                                $names = explode(' ', $data['search_for']);
3206
3207                                if (!is_array($names))
3208                                {
3209                                        if(!$full_search) {
3210                                                echo serialize(array(
3211                                                        'msg'    => lang('Invalid Search Parameter'),
3212                                                        'status' => 'abort'
3213                                                ));
3214                                                exit;
3215                                        }
3216                                        else
3217                                                $names = array();
3218
3219                                }
3220
3221                                if (!$external && $this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
3222/**rev 104**/
3223                                        //$this->page_info['actual_catalog']['class'] != 'bo_group_manager')
3224                                        $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
3225                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
3226                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager' )
3227/*****/
3228                                {
3229                                        /*
3230                                         * Restrict the returned contacts search to objectClass = phpgwAccount,
3231                                         * must have attibute phpgwAccountStatus, phpgwAccountVisible != -1
3232                                         */
3233                                       
3234                                        $rules = array(
3235                                                0 => array(
3236                                                        'field' => 'contact.object_class',
3237                                                        'type'  => '=',
3238                                                        'value' => 'phpgwAccount'
3239                                                ),
3240                                                1 => array(
3241                                                        'field' => 'contact.account_status',
3242                                                        'type'  => 'iLIKE',
3243                                                        'value' => '%'
3244                                                ),
3245/**rev 104**/
3246                                                ///
3247                                                //1 => array(
3248                                                2 => array(
3249/*****/
3250                                                        'field' => 'contact.account_visible',
3251                                                        'type'  => '!=',
3252                                                        'value' => '-1'
3253/**rev 104**/
3254        /*                                      ),
3255                                                2 => array(
3256                                                        'field' => 'contact.object_class',
3257                                                        'type'  => '=',
3258                                                        'value' => 'inetOrgPerson'
3259/****/
3260                                                ),
3261                                        );
3262
3263                                        if($full_search) {
3264                                                foreach($full_search as $field => $value) {
3265                                                        if(trim($value)!='')
3266                                                                array_push($rules,array(
3267                                                                                                'field' => $this->aux_full_search($field,true),
3268                                                                                                'type' => 'LIKE',
3269                                                                                                'value' => '*'.$value.'*'
3270                                                                                                ));
3271                                                }
3272                                        }
3273
3274                                }
3275                                else if(!$external && $full_search) {
3276                                       
3277                                        foreach($full_search as $field => $value) {
3278                                                if(trim($value)!='')
3279                                                        array_push($rules,array(
3280                                                                                        'field' => $this->aux_full_search($field,false),
3281                                                                                        'type' => 'iLIKE',
3282                                                                                        'value' => '%'.$value.'%'
3283                                                                                        ));
3284                                        }
3285                               
3286                                }
3287
3288                                foreach ($names as $name)
3289                                {
3290                                        if ($name != '')
3291                                        {
3292                                                array_push($rules, array(
3293                                                        'field' => $data['fields']['search'],
3294                                                        'type'  => 'iLIKE',
3295                                                        'value' => '%'.$name.'%'
3296                                                ));
3297                                        }
3298                                }
3299                        }
3300
3301                        if ($external || $this->page_info['actual_catalog']['class'] == 'bo_people_catalog' ||
3302/**rev 104**/
3303                                //$this->page_info['actual_catalog']['class'] == 'bo_group_manager')
3304                                $this->page_info['actual_catalog']['class'] == 'bo_group_manager' ||
3305                                $this->page_info['actual_catalog']['class'] == 'bo_shared_people_manager' ||
3306                                $this->page_info['actual_catalog']['class'] == 'bo_shared_group_manager')
3307
3308
3309/***/
3310                        {
3311                                // Get only this attributes: dn, cn for external catalogs,
3312                                // used to restrict the attributes used in filters
3313                                $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'), $data['search_for'] != null);
3314                        }
3315                        else
3316                        {
3317                                // Get only this attributes: dn, cn, phpgwAccountType, objectClass, phpgwAccountStatus, phpghAccountVisible
3318                                // for non-external catalogs, used to restrict the attributes used in filters
3319                                $ids = $this->bo->find(array(
3320                                        $data['fields']['id'],
3321                                        $data['fields']['search'],
3322                                        'contact.object_class',
3323                                        //'contact.account_status',
3324                                        'contact.account_visible',
3325                                        'contact.connection.mail',
3326                                        'contact.connection.phone'
3327                                        ), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'), $data['search_for_area'], $data['search_for'] != null );
3328                        }
3329
3330                        if (!is_array($ids) || !count($ids))
3331                        {
3332                                $this->last_search_ids = null;
3333                                $this->save_session();
3334                                return null;
3335                        }
3336
3337                        $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
3338
3339                        $ids_f = array();
3340
3341                        foreach ($ids as $e_info)
3342                        {
3343/**rev 104**/
3344                                //$ids_f[] = $e_info[$id_field];
3345                                if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
3346                                {
3347                                        $ids_f[] = $e_info[$id_field];
3348                                } else{
3349                                        $ids_f[] = array(0=>$e_info[$id_field],1=>$e_info['perms'],2=>$e_info['owner']);
3350                                }
3351/****/
3352                        }
3353
3354                        return $ids_f;
3355                }
3356
3357                // CELEPAR
3358                /*
3359        function search($str_data)
3360        {
3361            $data = unserialize($str_data);
3362
3363            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
3364            {
3365                echo serialize(array(
3366                    'msg'    => lang('Invalid parameters'),
3367                    'status' => 'abort'
3368                ));
3369
3370                return;
3371            }
3372
3373            $rules  = array();
3374
3375            if ($data['search_for'] === '*')
3376            {
3377                $rules = array(
3378                    0 => array(
3379                        'field' => $data['fields']['search'],
3380                        'type'  => 'LIKE',
3381                        'value' => '%'
3382                    )
3383                );
3384            }
3385            else
3386            {
3387                $names = explode(' ', $data['search_for']);
3388
3389                if (!is_array($names))
3390                {
3391                    echo serialize(array(
3392                        'msg'    => lang('Invalid Search Parameter'),
3393                        'status' => 'abort'
3394                    ));
3395
3396                    return;
3397                }
3398
3399                foreach ($names as $name)
3400                {
3401                    if ($name != '')
3402                    {
3403                        array_push($rules, array(
3404                            'field' => $data['fields']['search'],
3405                            'type'  => 'iLIKE',
3406                            'value' => '%'.$name.'%'
3407                        ));
3408                    }
3409                }
3410            }
3411
3412
3413
3414            //$catalog = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
3415
3416            //if ($catalog['class'] === 'bo_people_catalog')
3417            //{
3418            //    array_push($rules, array(
3419            //        'field' => 'contact.id_owner',
3420            //        'type'  => '=',
3421            //        'value' => $GLOBALS['phpgw_info']['user']['account_id']
3422            //    ));
3423            //}
3424
3425
3426            $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
3427
3428            if (!is_array($ids) || !count($ids))
3429            {
3430                echo serialize(array(
3431                    'msg'    => lang('No Entries Found!'),
3432                    'status' => 'empty'
3433                ));
3434
3435                return;
3436            }
3437            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
3438
3439            $ids_f = array();
3440            foreach ($ids as $e_info)
3441            {
3442                $ids_f[] = $e_info[$id_field];
3443            }
3444
3445            echo serialize(array(
3446                'data'   => $ids_f,
3447                'msg'    => lang('Found %1 Entries', count($ids)),
3448                'status' => 'ok'
3449            ));
3450
3451                        return;
3452        }*/
3453                /*!
3454
3455                        @function get_multiple_entries
3456                        @abstract Returns an array containing the specifiend data in the default
3457                                CC UI format
3458                        @author Raphael Derosso Pereira
3459
3460                        @param array str_data A serialized array containing the ID's of the entries
3461                                to be taken, the fields to be taken and the rules to be used on the
3462                                retrieval:
3463                                $data = array(
3464                                        'ids'    => array(...),
3465                                        'fields' => array(...),
3466                                        'rules'  => array(...)
3467                                );
3468
3469                */
3470                function get_multiple_entries($str_data)
3471                {
3472                        $data = unserialize($str_data);
3473
3474                        if (!is_array($data) or !count($data) or !count($data['fields']) or !count($data['ids']))
3475                        {
3476                                return array(
3477                                        'msg'    => lang('Invalid Parameters'),
3478                                        'status' => 'abort'
3479                                );
3480                        }
3481
3482                        $entries = $this->bo->catalog->get_multiple_entries($data['ids'], $data['fields']);
3483
3484                        if (!is_array($entries) or !count($entries))
3485                        {
3486                                return array(
3487                                        'msg'    => lang('No Entries Found!'),
3488                                        'status' => 'empty'
3489                                );
3490                        }
3491
3492                        return array(
3493                                'msg'    => lang('Found %1 Entries!', count($entries)),
3494                                'status' => 'ok',
3495                                'data'   => $entries
3496                        );
3497                }
3498
3499                /*
3500
3501                        @function get_all_entries
3502                        @abstract Returns the specified fields for all catalog's entries
3503                                in the default CC UI format
3504                        @author Raphael Derosso Pereira
3505
3506                        @params array str_data A serialized array containing the fields to
3507                                be grabbed, the maximum number of entries to be returned and a
3508                                boolean specifying if the calls refers to a new grab or to an
3509                                unfinished one.
3510
3511                */
3512                function get_all_entries($str_data)
3513                {
3514                        $data = unserialize($str_data);
3515
3516                        if (!is_array($data) or
3517                            !count($data) or
3518                                !count($data['fields']) or
3519                                !$data['maxlength'] or
3520                                (!$data['new'] and !$data['offset']))
3521                        {
3522                                return array(
3523                                        'msg'    => lang('Invalid Parameters'),
3524                                        'status' => 'abort'
3525                                );
3526                        }
3527
3528                        if ($data['new'])
3529                        {
3530                                $this->all_entries = $this->bo->catalog->get_all_entries_ids();
3531
3532                                $this->save_session();
3533
3534                                if (!is_array($this->all_entries) or !count($this->all_entries))
3535                                {
3536                                        return array(
3537                                                'msg'    => lang('No Entries Found!'),
3538                                                'status' => 'empty'
3539                                        );
3540                                }
3541
3542                                $data['offset'] = 0;
3543                        }
3544
3545                        if ($data['maxlength'] != -1)
3546                        {
3547                                $result = $this->bo->catalog->get_multiple_entries(array_slice($this->all_entries, $data['offset'], $data['maxlength']), $data['fields']);
3548                        }
3549                        else
3550                        {
3551                                $result = $this->bo->catalog->get_multiple_entries($this->all_entries, $data['fields']);
3552                        }
3553
3554                        $jsCode = array();
3555                        $count = 0;
3556                        foreach ($result as $each)
3557                        {
3558                                if (!is_array($each))
3559                                {
3560                                        continue;
3561                                }
3562
3563                                if($this-> typeContact == 'groups') {
3564
3565                                        foreach ($each as $field => $value)     {
3566
3567                                                if ($field === 'title') {
3568                                                        $optionName = '\\"'.$value.'\\"';
3569
3570                                                }
3571                                                else if ($field === 'short_name')       {
3572
3573                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$optionName.' ('.$value.')", "'.$count.'");';
3574                                                        $count++;
3575                                                }
3576                                        }
3577                                }
3578
3579                                else  {
3580                                        foreach ($each as $field => $value)     {
3581                                                if ($field === 'names_ordered') {
3582                                                         if(is_array($value))
3583                                $value = $value[0];
3584                                                        $name = '\\"'.$value.'\\"';
3585                                                }
3586                                                else if ($field === 'connections')      {
3587
3588                                                        foreach ($value as $connection)         {
3589                                                                if ($connection['id_type'] == $this->preferences['personCardEmail'])    {
3590                                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$name.' <'.$connection['connection_value'].'>", "'.$count.'");';
3591                                                                        $count++;
3592                                                                }
3593                                                        }
3594                                                }
3595                                        }
3596                                }
3597                        }
3598
3599                        $jsCodeFinal = implode("\n", $jsCode);
3600
3601                        $nEntries = count($result);
3602
3603                        if (!$nEntries)
3604                        {
3605                                return array(
3606                                        'msg'    => lang('Error while getting user information...'),
3607                                        'status' => 'abort'
3608                                );
3609                        }
3610
3611                        return array(
3612                                'msg'      => lang('Found %1 Entries!', $nEntries),
3613                                'status'   => 'ok',
3614                                'typeContact'   => $this -> typeContact,
3615                                'final'    => $nEntries + $data['offset'] < count($this->all_entries) ? false : true,
3616                                'offset'   => $data['offset'] + $nEntries,
3617                                'data'     => $jsCodeFinal
3618                        );
3619                }
3620
3621                /*********************************************************************\
3622                 *                      Auxiliar Methods                             *
3623                \*********************************************************************/
3624
3625                /*!
3626
3627                        @function save_session
3628                        @abstract Saves the data on the session
3629                        @author Raphael Derosso Pereira
3630
3631                */
3632                function save_session()
3633                {
3634                        $GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter',$this->page_info);
3635                        $GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter',$this->all_entries);
3636                }
3637
3638                /*!
3639
3640                        @function convert_tree
3641                        @abstract Converts the tree array in the BO format to a JS tree array compatible
3642                                with the one available in eGW
3643                        @author Raphael Derosso Pereira
3644
3645                        @param (array)  $tree    The tree in the BO format
3646                        @param (string) $name    The tree name
3647                        @param (string) $iconDir The dir where the icons are
3648                        @param (string) $parent  The parent
3649                */
3650
3651                function convert_tree($tree, &$iconDir, $parent='0')
3652                {
3653//                      echo "Entrou<br>\tPai: $parent <br>";
3654                        $rtree = array();
3655
3656                        if ($parent === '0')
3657                        {
3658//                              echo 'Root!<br>';
3659                                $rtree['0'] = array(
3660                                        'type'       => 'catalog_group',
3661                                        'id'         => '0',
3662                                        'pid'        => 'none',
3663                                        'caption'    => lang('Catalogues'),
3664                                        'class'      => 'bo_catalog_group_catalog',
3665                                        'class_args' => array('_ROOT_', '$this', '$this->get_branch_by_level($this->catalog_level[0])')
3666                                );
3667                        }
3668
3669                        foreach($tree as $id => $value)
3670                        {
3671//                              echo 'ID: '.$id.'<br>';
3672                                $rtree[$parent.'.'.$id] = array(
3673                                        'type'    => $value['type'],
3674                                        'id'      => $parent.'.'.$id,
3675                                        'pid'     => $parent,
3676                                        'caption' => $value['name']
3677                                );
3678
3679                                switch($value['type'])
3680                                {
3681                                        case 'catalog_group':
3682                                        case 'mixed_catalog_group':
3683                                                $rtree = $rtree + $this->convert_tree($value['sub_branch'],$iconDir,$parent.'.'.$id);
3684                                                break;
3685                                }
3686                        }
3687
3688                        if (count($rtree))
3689                        {
3690                                return $rtree;
3691                        }
3692                }
3693
3694                function get_catalog_add_contact($id, $echo=true){
3695
3696                        $array_participants = array();
3697                        if(!$this->bo->catalog->src_info) {
3698                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3699                                $this->bo->catalog->src_info = $ldap->srcs[1];
3700                        }
3701
3702                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3703                        $dn=$this->bo->catalog->src_info['dn'];
3704                        $justThese = array("givenname","givenname","sn","telephonenumber","mail");
3705                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);
3706                        $info = ldap_get_entries($ds, $sr);
3707                        for($z = 0; $z < 5; $z++) {
3708                                $participant = $info[0][$justThese[$z]];
3709                                $participant[0] = utf8_decode($participant[0]);
3710                                array_push($array_participants, $participant);
3711                        }
3712
3713                        ldap_close($ds);
3714                        if ($echo)
3715                        {
3716                            echo serialize($array_participants);
3717                        }
3718                        else
3719                            {
3720                                return serialize($array_participants);
3721                            }
3722                }
3723
3724                function get_catalog_participants_group($id)
3725                {
3726                        if(!$this->bo->catalog->src_info) {
3727                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3728                                $this->bo->catalog->src_info = $ldap->srcs[1];
3729                        }
3730                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3731                        $justThese = array("description","memberuid");
3732                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);
3733                        $info = ldap_get_entries($ds, $sr);
3734                        $member_uids = $info[0]['memberuid'];
3735                        $contact['names_ordered'] = $info[0]['description'];
3736                        $filter = "";
3737                        for($z = 0; $z < count($member_uids); $z++) {
3738                                if($member_uids[$z])
3739                                        $filter.="(uid=".$member_uids[$z].")";
3740                        }
3741                        $array_participants = array();
3742                        if($filter) {
3743                                $filter = "(|".$filter.")";
3744                                $valarray = explode(',',$id);
3745                                array_shift($valarray);
3746                                $dn = implode(',',$valarray);
3747                                $justThese = array("cn","mail");
3748                                $sr = ldap_search($ds,$dn, $filter,$justThese);
3749                                $info = ldap_get_entries($ds, $sr);
3750                                for($z = 0; $z < $info['count']; $z++) {
3751                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3752                                    $array_emails[$info[$z]['mail'][0]] = null;
3753                                        array_push($array_participants, $participant);
3754                                }
3755                                ldap_close($ds);
3756                        }
3757                        sort($array_participants);
3758                        $innerHTML = '';
3759                        foreach($array_participants as $index => $participant){
3760                                $innerHTML .= $participant;
3761                        }
3762                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
3763                        echo serialize($return);
3764                }
3765
3766                function get_catalog_participants_list($id)
3767                {
3768
3769                        $fields = $this->bo->catalog->get_fields(false);
3770                        $fields['names_ordered'] = true;
3771                        $fields['mail_forwarding_address'] = true;
3772                        $contact = $this->bo->catalog->get_single_entry($id,$fields);
3773
3774                        $array_participants = array();
3775                        $array_emails = array();
3776
3777                        $filter = null;
3778                        for($z = 0; $z < $contact['mail_forwarding_address']['count']; $z++) {
3779                                        if(strstr($contact['mail_forwarding_address'][$z],'@')) {
3780                                                $filter.="(mail=".$contact['mail_forwarding_address'][$z].")";
3781                                                $array_emails[$contact['mail_forwarding_address'][$z]] = "<font color=black>".$contact['mail_forwarding_address'][$z]."</font>";
3782                                        }
3783                                        else
3784                                                $array_participants[$z] = "<font color=red>".$contact['mail_forwarding_address'][$z]."</font>";
3785                        }
3786
3787                        if($filter) {
3788                                $filter = "(|".$filter.")";
3789                                if(!$this->bo->catalog->src_info) {
3790                                        $ldap = CreateObject('contactcenter.bo_ldap_manager');
3791                                        $this->bo->catalog->src_info = $ldap->srcs[1];
3792                                }
3793                                $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3794                                $dn=$this->bo->catalog->src_info['dn'];
3795                                $justThese = array("cn","mail");
3796                                $sr = ldap_search($ds,$dn, $filter,$justThese);
3797                                $info = ldap_get_entries($ds, $sr);
3798                                for($z = 0; $z < $info['count']; $z++) {
3799                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3800                                        $array_emails[$info[$z]['mail'][0]] = null;
3801                                        array_push($array_participants, $participant);
3802                                }
3803
3804                                foreach($array_emails as $index => $email)
3805                                        if($email)
3806                                                array_push($array_participants, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$email."<br>");
3807
3808                                ldap_close($ds);
3809                        }
3810                        sort($array_participants);
3811                        $innerHTML = '';
3812                        foreach($array_participants as $index => $participant){
3813                                $innerHTML .= $participant;
3814                        }
3815                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
3816                        echo serialize($return);
3817                }
3818
3819                function export_contacts($typeExport){
3820
3821                        $boGroup = CreateObject('contactcenter.bo_group');
3822                        $contacts = $boGroup->get_all_contacts();
3823                        $streamBuffer = '';
3824
3825                        if(!count($contacts))
3826                                echo null;
3827
3828                        switch($typeExport) {
3829
3830                                case 'outlook_en':
3831                                        $streamBuffer = "Name;E-mail Address;Notes;Mobile Phone;Pager;Company;".
3832                                                        "Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";                                                       
3833                                        foreach($contacts as $index => $object){
3834                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\";"
3835                                                        . "\"".$object[ 'main-mail' ] . "\";"
3836                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\";"
3837                                                        . "\"".$object[ 'mobile' ] . "\";"
3838                                                        . "\"".$object[ 'business-pager' ] . "\";"
3839                                                        . "\"".$object[ 'corporate_name' ] . "\";"
3840                                                        . "\"".$object[ 'job_title' ] . "\";"
3841                                                        . "\"".$object[ 'home-phone' ] . "\";"
3842                                                        . "\"".$object[ 'home-fax' ] . "\";"
3843                                                        . "\"".$object[ 'business-phone' ] . "\";"
3844                                                        . "\"".$object[ 'business-fax' ] . "\"\r\n";
3845                                        }
3846                                        break;
3847
3848                                case 'outlook_pt-BR':
3849                                        $streamBuffer = "Nome;Sobrenome;Segundo nome;Nome;Apelido;End. de email;Endereço residencial;"
3850                                                                        ."Cidade do endereço residencial;CEP do endereço residencial;Estado;País/região do endereço residencial;"
3851                                                                        ."Telefone residencial;Fax residencial;Telefone celular;Página pessoal da Web;Rua do endereço comercial;"
3852                                                                        ."Cidade do endereço comercial;CEP do endereço comercial;Estado do endereço comercial;"
3853                                                                        ."País/região do endereço comercial;Página comercial da Web;Telefone comercial;Fax comercial;Pager;Empresa;"
3854                                                                        ."Cargo;Departamento;End. comercial;Observações\r\n";
3855
3856                                        foreach($contacts as $index => $object){
3857                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\";"
3858                                                        .";;;"
3859                                                        . "\"".$object[ 'alias' ] . "\";"
3860                                                        . "\"".$object[ 'main-mail' ] . "\";"
3861                                                        . "\"".$object[ 'home-address' ] . "\";"
3862                                                        . "\"".$object[ 'home-city_name' ] . "\";"
3863                                                        . "\"".$object[ 'home-postal_code' ] . "\";"
3864                                                        . "\"".$object[ 'home-state_name' ] . "\";"
3865                                                        . "\"".$object[ 'home-id_country' ] . "\";"
3866                                                        . "\"".$object[ 'home-phone' ] . "\";"
3867                                                        . "\"".$object[ 'home-fax' ] . "\";"
3868                                                        . "\"".$object[ 'mobile' ] . "\";"
3869                                                        . "\"".$object[ 'web_page' ] . "\";"
3870                                                        . "\"".$object[ 'business-address' ] . "\";"
3871                                                        . "\"".$object[ 'business-city_name' ] . "\";"
3872                                                        . "\"".$object[ 'business-postal_code' ] . "\";"
3873                                                        . "\"".$object[ 'business-state_name' ] . "\";"
3874                                                        . "\"".$object[ 'business-id_country' ] . "\";"
3875                                                        . "\"".$object[ 'web_page' ] . "\";"
3876                                                        . "\"".$object[ 'business-phone' ] . "\";"
3877                                                        . "\"".$object[ 'business-fax' ] . "\";"
3878                                                        . "\"".$object[ 'business-pager' ] . "\";"
3879                                                        . "\"".$object[ 'corporate_name' ] . "\";"
3880                                                        . "\"".$object[ 'job_title' ] . "\";"
3881                                                        . "\"".$object[ 'department' ] . "\";"
3882                                                        .";"
3883                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\"\r\n";
3884                                        }
3885
3886                                break;
3887
3888                                case 'outlook2000_pt-BR':
3889                                        $streamBuffer = "\"Tratamento\",\"Nome\",\"Segundo Nome\",\"Sobrenome\",\"Sufixo\",".
3890                                        "\"Empresa\",\"Departamento\",\"Cargo\",\"Rua do endereço comercial\",\"Rua do endereço comercial 2\",".
3891                                        "\"Rua do endereço comercial 3\",\"Cidade do endereço comercial\",\"Estado do endereço comercial\",".
3892                                        "\"CEP do endereço comercial\",\"País do endereço comercial\",\"Endereço residencial\",\"Rua residencial 2\",".
3893                                        "\"Rua residencial 3\",\"Cidade do endereço residencial\",\"Estado\",\"CEP do endereço residencial\",\"País do endereço residencial\",".
3894                                        "\"Outro endereço\",\"Outro endereço 2\",\"Outro endereço 3\",\"Cidade\",\"Estado\",\"CEP\",\"País\",".
3895                                        "\"Telefone do assistente\",\"Fax comercial\",\"Telefone comercial\",\"Telefone comercial 2\",\"Retorno de chamada\",".
3896                                        "\"Telefone do carro\",\"Telefone principal da empresa\",\"Fax residencial\",\"Telefone residencial\",".
3897                                        "\"Telefone residencial 2\",\"ISDN\",\"Telefone celular\",\"Outro fax\",\"Outro telefone\",\"Pager\",\"Telefone principal\",".
3898                                        "\"Radiofone\",\"Telefone TTY/TDD\",\"Telex\",\"Aniversário\",\"Anotações\",\"Caixa postal\",\"Categorias\",".
3899                                        "\"Código da empresa\",\"Código do governo\",\"Cônjuge\",\"Conta\",\"Endereço de correio eletrônico\",".
3900                                        "\"Nome de exibição do correio eletr.\",\"Endereço de correio eletrônico 2\",".
3901                                        "\"Nome de exibição do correio eletr.2\",\"Endereço de correio eletrônico 3\",".
3902                                        "\"Nome de exibição do correio eletr.3\",\"Datas especiais\",\"Disponibilidade da Internet\",".
3903                                        "\"Filhos\",\"Hobby\",\"Idioma\",\"Indicação\",\"Informações para cobrança\",\"Iniciais\",\"Local\",".
3904                                        "\"Nome do assistente\",\"Nome do gerenciador\",\"Página da Web\",\"Palavras-chave\",\"Particular\",\"Personalizado 1\",\"Personalizado 2\",".
3905                                        "\"Personalizado 3\",\"Personalizado 4\",\"Prioridade\",\"Profissão\",\"Quilometragem\",\"Sala\",\"Sensibilidade\",\"Servidor de diretório\",".
3906                                        "\"Sexo\"\r\n";
3907
3908
3909
3910                                        foreach($contacts as $index => $object){
3911                                $streamBuffer .= "\"".$object[ 'alias' ] . "\","                                   
3912                                                                . "\"".$object[ 'names_ordered' ] . "\","
3913                                                                .",,,"
3914                                                                . "\"".$object[ 'corporate_name' ] . "\","
3915                                                                . "\"".$object[ 'department' ] . "\","
3916                                                                . "\"".$object[ 'job_title' ] . "\","
3917                                                                . "\"".$object[ 'business-address' ] . "\","
3918                                                                . "\"".$object[ 'business-address-2' ] . "\","
3919                                                                .","
3920                                                                . "\"".$object[ 'business-city_name' ] . "\","
3921                                                                . "\"".$object[ 'business-state' ] . "\","
3922                                                                . "\"".$object[ 'business-postal_code' ] . "\","
3923                                                                . "\"".$object[ 'business-id_country' ] . "\","
3924                                                                . "\"".$object[ 'home-address' ] . "\","
3925                                                                . "\"".$object[ 'home-address-2' ] . "\","
3926                                                                .","
3927                                                                . "\"".$object[ 'home-city_name' ] . "\","
3928                                                                . "\"".$object[ 'home-state_name' ] . "\","
3929                                                                . "\"".$object[ 'home-postal_code' ] . "\","
3930                                                                . "\"".$object[ 'home-id_country' ] . "\","
3931                                                                .",,,,,,,,"
3932                                                                . "\"".$object[ 'business-fax' ] . "\","
3933                                                                . "\"".$object[ 'business-phone' ] . "\","
3934                                                                . "\"".$object[ 'business-mobile' ] . "\","
3935                                                                .",,,"
3936                                                                . "\"".$object[ 'home-fax' ] . "\","
3937                                                                . "\"".$object[ 'home-phone' ] . "\","
3938                                                                .",,"
3939                                                                . "\"".$object[ 'mobile' ] . "\","
3940                                                                .",,"
3941                                                                . "\"".$object[ 'home-pager' ] . "\","
3942                                                                . "\"".$object[ 'business-phone' ] . "\","
3943                                                                .",,,"
3944                                                                . "\"".$object[ 'birthdate' ] . "\","
3945                                                                . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
3946                                                                .",,,,,,"
3947                                                                . "\"".$object[ 'main-mail' ] . "\","
3948                                                                .","
3949                                                                . "\"".$object[ 'alternative-mail' ] . "\","
3950                                                                .",,,,,,,,,,,,,,"
3951                                                                . "\"".$object[ 'web_page' ] . "\","
3952                                                                .",,,,,,,,,,,,"
3953                                                                . "\"".$object[ 'sex' ] . "\"\r\n";                                                             
3954                            }
3955                                break;
3956
3957                                case 'outlook2000_en':
3958                                        $streamBuffer = "Title,First Name,Middle Name,Last Name,Suffix,Company,Department,Job Title,".
3959                                        "Business Street,Business Street 2,Business Street 3,Business City,Business State,Business Postal Code,".
3960                                        "Business Country,Home Street,Home Street 2,Home Street 3,Home City,Home State,Home Postal Code,Home Country,".
3961                                        "Other Street,Other Street 2,Other Street 3,Other City,Other State,Other Postal Code,Other Country,".
3962                                        "Assistant's Phone,Business Fax,Business Phone,Business Phone 2,Callback,Car Phone,Company Main Phone,Home Fax,".
3963                                        "Home Phone,Home Phone 2,ISDN,Mobile Phone,Other Fax,Other Phone,Pager,Primary Phone,Radio Phone,TTY/TDD Phone,Telex,".
3964                                        "Account,Anniversary,Assistant's Name,Billing Information,Birthday,Categories,Children,Directory Server,E-mail Address,".
3965                                        "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,".
3966                                        "Gender,Government ID Number,Hobby,Initials,Internet Free Busy,Keywords,Language,Location,Manager's Name,Mileage,Notes,".
3967                                        "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";
3968
3969                                        foreach($contacts as $index => $object){
3970                                                if( array_key_exists("phone", $object) )
3971                                                        $phone = $object['phone'];
3972                                                else
3973                            $phone = $object['business-phone'];
3974                                       
3975                                                $streamBuffer.= "\"".$object[ 'alias' ] . "\","
3976                                                        . "\"".$object[ 'names_ordered'] . "\","
3977                                                        .",,,"
3978                                                        . "\"".$object[ 'corporate_name' ] . "\","
3979                                                        . "\"".$object[ 'department' ] . "\","
3980                                                        . "\"".$object[ 'job_title' ] . "\","
3981                                                        . "\"".$object[ 'business-address' ] . "\","
3982                                                        . "\"".$object[ 'business-address-2' ] . "\","
3983                                                        .","
3984                                                        . "\"".$object[ 'business-city_name' ] . "\","
3985                                                        . "\"".$object[ 'business-state' ] . "\","
3986                                                        . "\"".$object[ 'business-postal_code' ] . "\","
3987                                                        . "\"".$object[ 'business-id_country' ] . "\","
3988                                                        . "\"".$object[ 'home-address' ] . "\","
3989                                                        . "\"".$object[ 'home-address-2' ] . "\","
3990                                                        .","
3991                                                        . "\"".$object[ 'home-city_name' ] . "\","
3992                                                        . "\"".$object[ 'home-state_name' ] . "\","
3993                                                        . "\"".$object[ 'home-postal_code' ] . "\","
3994                                                        . "\"".$object[ 'home-id_country' ] . "\","
3995                                                        .",,,,,,,,"
3996                                                        . "\"".$object[ 'business-fax' ] . "\","
3997                                                        . "\"".$phone . "\","
3998                                                        . "\"".$object[ 'business-mobile' ] . "\","
3999                                                        .",,,"
4000                                                        . "\"".$object[ 'home-fax' ] . "\","
4001                                                        . "\"".$object[ 'home-phone' ] . "\","
4002                                                        .",,"
4003                                                        . "\"".$object[ 'mobile' ] . "\","
4004                                                        .",,"
4005                                                        . "\"".$object[ 'business-pager' ] . "\","
4006                                                        . "\"".$object[ 'home-pager' ] . "\","
4007                                                        .",,,,,,,,"
4008                                                        . "\"".$object[ 'birthdate' ] . "\","
4009                                                        .",,,"
4010                                                        . "\"".$object[ 'main-mail' ] . "\","
4011                                                        .",,"
4012                                                        . "\"".$object[ 'alternative-mail' ] . "\","
4013                                                        .",,,,,,,,,,,,,,,"
4014                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
4015                                                        .",,,,,,,,,,,,,"
4016                                                        . "\"".$object[ 'web_page' ] . "\"\r\n";
4017
4018                                        }
4019                                break;
4020
4021                                case 'thunderbird':
4022                                        $streamBuffer = "First Name,Last Name,Display Name,Nickname,Primary Email,Secondary Email,"
4023                                                ."Screen Name,Work Phone,Home Phone,Fax Number,Pager Number,Mobile Number,Home Address,"
4024                                                ."Home Address 2,Home City,Home State,Home ZipCode,Home Country,Work Address,Work Address 2,"
4025                                                ."Work City,Work State,Work ZipCode,Work Country,Job Title,Department,Organization,Web Page 1,"
4026                                                ."Web Page 2,Birth Year,Birth Month,Birth Day,Custom 1,Custom 2,Custom 3,Custom 4,Notes,\n";
4027
4028                                        foreach($contacts as $index => $object){
4029                                                $array_birth = explode("-",$object[ 'birthdate' ]);
4030                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\","
4031                                                        .",,"
4032                                                        . "\"".$object[ 'alias' ] . "\","
4033                                                        . "\"".$object[ 'main-mail' ] . "\","
4034                                                        . "\"".$object[ 'alternative-mail' ] . "\","
4035                                                        .","
4036                                                        . "\"".$phone . "\","
4037                                                        . "\"".$object[ 'home-phone' ] . "\","
4038                                                        . "\"".$object[ 'business-fax' ] . "\","
4039                                                        . "\"".$object[ 'business-pager' ] . "\","
4040                                                        . "\"".$object[ 'mobile' ] . "\","
4041                                                        . "\"".$object[ 'home-address' ] . "\","
4042                                                        . "\"".$object[ 'home-address-2' ] . "\","
4043                                                        . "\"".$object[ 'home-city_name' ] . "\","
4044                                                        . "\"".$object[ 'home-state_name' ] . "\","
4045                                                        . "\"".$object[ 'home-postal_code' ] . "\","
4046                                                        . "\"".$object[ 'home-id_country' ] . "\","
4047                                                        . "\"".$object[ 'business-address' ] . "\","
4048                                                        . "\"".$object[ 'business-address-2' ] . "\","
4049                                                        . "\"".$object[ 'business-city_name' ] . "\","
4050                                                        . "\"".$object[ 'business-state_name' ] . "\","
4051                                                        . "\"".$object[ 'business-postal_code' ] . "\","
4052                                                        . "\"".$object[ 'business-id_country' ] . "\","
4053                                                        . "\"".$object[ 'job_title' ] . "\","
4054                                                        . "\"".$object[ 'department' ] . "\","
4055                                                        . "\"".$object[ 'corporate_name' ] . "\","
4056                                                        . "\"".$object[ 'web_page' ] . "\","
4057                                                        . "\"".$object[ 'web_page' ] . "\","
4058                                                        . "\"".$array_birth[0] . "\","
4059                                                        . "\"".$array_birth[1] . "\","
4060                                                        . "\"".$array_birth[2] . "\","
4061                                                        .",,,,"
4062                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\",\r\n";
4063
4064                                        }
4065                                break;
4066
4067                                case 'expresso':
4068                            $streamBuffer = 'Nome,Apelido,E-mail Principal,E-mail Alternativo,Celular,'
4069                                . 'Telefone Comercial,Endereço Comercial,Complemento End. Comercial,CEP Comercial,Cidade End. Comercial,Estado End. Comercial,País End. Comercial,'
4070                                . 'Telefone Residencial,Endereço Residencial,Complemento End. Residencial,CEP Residencial,Cidade End. Residencial,Estado End. Residencial,País End. Residencial,'
4071                                . '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'
4072                                                        . "\r\n";
4073
4074                            foreach($contacts as $index => $object){
4075                                $streamBuffer .= "\"".$object[ 'names_ordered'] . "\","
4076                                    . "\"".$object[ 'alias' ] . "\","
4077                                    . "\"".$object[ 'main-mail' ] . "\","
4078                                    . "\"".$object[ 'alternative-mail' ] . "\","
4079                                    . "\"".$object[ 'mobile' ] . "\","
4080                                    . "\"".$object[ 'business-phone' ] . "\","
4081                                    . "\"".$object[ 'business-address' ] . "\","
4082                                    . "\"".$object[ 'business-complement' ] . "\","
4083                                    . "\"".$object[ 'business-postal_code' ] . "\","
4084                                    . "\"".$object[ 'business-city_name' ] . "\","
4085                                    . "\"".$object[ 'business-state_name' ] . "\","
4086                                    . "\"".$object[ 'business-id_country' ] . "\","
4087                                    . "\"".$object[ 'home-phone' ] . "\","
4088                                    . "\"".$object[ 'home-address' ] . "\","
4089                                    . "\"".$object[ 'home-complement' ] . "\","
4090                                    . "\"".$object[ 'home-postal_code' ] . "\","
4091                                    . "\"".$object[ 'home-city_name' ] . "\","
4092                                    . "\"".$object[ 'home-state_name' ] . "\","
4093                                    . "\"".$object[ 'home-id_country' ] . "\","
4094                                                                . "\"".$object[ 'birthdate' ] . "\","
4095                                                                . "\"".$object[ 'sex' ] . "\","
4096                                                                . "\"".$object[ 'pgp_key' ] . "\","
4097                                                                . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
4098                                                                . "\"".$object[ 'web_page' ] . "\","
4099                                                                . "\"".$object[ 'corporate_name' ] . "\","
4100                                                                . "\"".$object[ 'job_title' ] . "\","
4101                                                                . "\"".$object[ 'department' ] . "\","
4102                                                                . "\"".$object[ 'business-fax' ] . "\","
4103                                                                . "\"".$object[ 'business-pager' ] . "\","
4104                                                                . "\"".$object[ 'business-mobile' ] . "\","
4105                                                                . "\"".$object[ 'home-fax' ] . "\","
4106                                                                . "\"".$object[ 'home-pager' ] . "\","
4107                                                                . "\"".$object[ 'business-address-2' ] . "\","
4108                                                                . "\"".$object[ 'home-address-2' ] . "\"\r\n";
4109                            }
4110                        break;
4111
4112                        }
4113
4114                        $file = "contacts_".md5(microtime()).".swp";
4115                        $tempDir = ini_get("session.save_path");
4116                        $f = fopen($tempDir.'/'.$file,"w");
4117                        if(!$f)
4118                                echo null;
4119
4120                        fputs($f,$streamBuffer);
4121                        fclose($f);
4122
4123                        echo $tempDir.'/'.$file;
4124                }
4125
4126                // Get the csv field and put into array, from php.net
4127                function parse_line($input_text, $delimiter = ',', $text_qualifier = '"') {
4128                        $text = trim($input_text);
4129                          if(is_string($delimiter) && is_string($text_qualifier)) {
4130                         $re_d = '\x' . dechex(ord($delimiter));            //format for regexp
4131                        $re_tq = '\x' . dechex(ord($text_qualifier));    //format for regexp
4132
4133                        $fields = array();
4134                        $field_num = 0;
4135                        while(strlen($text) > 0) {
4136                        if($text{0} == $text_qualifier) {
4137                                preg_match('/^' . $re_tq . '((?:[^' . $re_tq . ']|(?<=\x5c)' . $re_tq . ')*)' . $re_tq . $re_d . '?(.*)$/', $text, $matches);
4138
4139                                $value = str_replace('\\' . $text_qualifier, $text_qualifier, $matches[1]);
4140                                $text = trim($matches[2]);
4141
4142                                $fields[$field_num++] = $value;
4143                        } else {
4144                                preg_match('/^([^' . $re_d . ']*)' . $re_d . '?(.*)$/', $text, $matches);
4145
4146                                $value = $matches[1];
4147                                $text = trim($matches[2]);
4148
4149                                $fields[$field_num++] = $value;
4150                }
4151                }
4152                        return $fields;
4153                    } else
4154                        return false;
4155                }
4156
4157                //funcao alterada para importar outros campos alem de nome, telefone e email, de arquivo csv (Outlook 2000)
4158                //em 08/04/2009 - Rommel Cysne (rommel.cysne@serpro.gov.br);
4159                //Foi adicionada uma funcao (escapesheelcmd()) nas variaveis para que caracteres especiais sejam ignorados
4160                //durante a importacao dos contatos; o processo estava travando por causa de caracteres em campos como nome,
4161                //sobrenome, notas e e-mail;
4162                //em 19/06/2009 - Rommel Cysne (rommel.cysne@serpro.gov.br);
4163                function import_contacts($typeImport){
4164                        $this->so_group = CreateObject('contactcenter.so_group');
4165                        if($file = $_SESSION['contactcenter']['importCSV']) {
4166                                unset($_SESSION['contactcenter']['importCSV']);
4167                                $len = filesize($file);
4168                                $count = 0;
4169                                $return = array('error' => false, '_new' => 0, '_existing' => 0, '_failure' => 0);
4170                                $handle = @fopen($file, "r") or die(serialize($return['error'] = true));
4171
4172                                $input_header = fgets($handle);
4173                                if ($typeImport == 'outlook')
4174                                        $delim = ';';
4175                                else if ($typeImport == 'auto')
4176                                $delim = strstr($input_header,',') ? ',' : ';';
4177                                else
4178                                        $delim = ',';
4179                                $csv_header = $this->parse_line($input_header,$delim);
4180                                $firstContact = fgets($handle);
4181                                preg_match("/\"(.+)\"[,;]/sU",$firstContact,$matches); // yahoo csv
4182                                rewind($handle);
4183
4184                                $header = @fgetcsv($handle, $len, $delim) or die(serialize($return['error'] = true));
4185                                if(count($header)  < 2 || count($header) > 100) {
4186                                        $return['error'] = true;
4187                                        $return['sizeheader'] = count($header);
4188                                        echo serialize($return);
4189                                        return;
4190                                }
4191
4192                                if ($matches[0][strlen($matches[0])-1] == ';')
4193                                        $delim = ';';
4194
4195                                $boGroup = CreateObject('contactcenter.bo_group');
4196                                $boPeople = CreateObject('contactcenter.bo_people_catalog');
4197                                        switch($typeImport){
4198                                                case 'outlook2000':
4199                                                        $name_pos=1;
4200                                                        $name2_pos=2;
4201                                                        $name3_pos=3;
4202                                                        $corporate_street_pos=8;
4203                                                        $cep_pos=13;
4204                                                        $corporate_street_2_pos=22;
4205                                                        $fax_pos=30;
4206                                                        $phone_pos=31;
4207                                                        $home_phone_pos=37;
4208                                                        $personal_cell_pos=40;
4209                                                        $pager_pos=43;
4210                                                        $birth_pos=48;
4211                                                        $notes_pos=49;
4212                                                        $email_pos=56;
4213                                                        $aditionalEmail_pos=59;
4214
4215                                                        break;
4216                                                case 'outlook':
4217                                                        $name_pos=3;
4218                                                        $email_pos=4;
4219                                                        $phone_pos=7;
4220                                                        $home_phone_pos=10;
4221                                                        $personal_cell_pos=12;
4222                                                        $corporate_street_pos=13;
4223                                                        $cep_pos=15;
4224                                                        $phone_pos=18;
4225                                                        $fax_pos=19;
4226                                                        $pager_pos=20;
4227                                                        $notes_pos=25;
4228                                                        break;
4229                                                case 'thunderbird':
4230                                                        $name_pos=2;
4231                                                        $email_pos=4;
4232                                                        $phone_pos=7;
4233                                                        break;
4234                                                case 'expresso':
4235                                                        $name_pos=0;
4236                                                        $alias_pos=1;
4237                                                        $email_pos=2;
4238                                                        $aditionalEmail_pos=3;
4239                                                        $personal_cell_pos=4;
4240                                                        $corporate_phone_pos=5;
4241                                                        $corporate_street_pos=6;
4242                                                        $corporate_comp_pos=7;
4243                                                        $corporate_cep_pos=8;
4244                                                        $corporate_city_pos=9;
4245                                                        $corporate_state_pos=10;
4246                                                        $corporate_country_pos=11;
4247                                                        $home_phone_pos=12;
4248                                                        $street_pos=13;
4249                                                        $comp_pos=14;
4250                                                        $cep_pos=15;
4251                                                        $city_pos=16;
4252                                                        $state_pos=17;
4253                                                        $country_pos=18;
4254                                                        $birth_pos=19;
4255                                                        $sex_pos = 20;
4256                                                        $pgp_key_pos = 21;
4257                                                        $notes_pos=22;
4258                                                        $web_page_pos=23;
4259                                                        $corporate_name_pos=24;
4260                                                        $job_title_pos=25;
4261                                                        $department_pos=26;
4262                                                        $corporate_fax_pos=27;
4263                                                        $corporate_pager_pos=28;
4264                                                        $corporate_cell_pos=29;
4265                                                        $fax_pos=30;
4266                                                        $pager_pos=31;
4267                                                        $corporate_street_2_pos = 32;
4268                                                        $street_2_pos = 33;                                             
4269                                                        break;
4270                                        default:
4271                                                        foreach($csv_header as $index => $fieldName)
4272                                                        {
4273                                                                switch($fieldName){
4274                                                                case 'Name':
4275                                                                case 'Nome':
4276                                                                case 'First Name':
4277                                                                        $name_pos = $index;
4278                                                                        break;
4279                                                                case 'Second name':
4280                                                                case 'Segundo nome':
4281                                                                        $name2_pos = $index;
4282                                                                        break;
4283                                                                case 'Sobrenome':
4284                                                                case 'Surname':
4285                                                                        $name3_pos = $index;
4286                                                                        break;
4287                                                                case 'Business Street':
4288                                                                case 'Rua do endereço comercial':
4289                                                                        $corporate_street_pos = $index;
4290                                                                        break;
4291                                                                case 'Rua do endereço comercial 2':
4292                                                                case 'Outro endereço':
4293                                                                        $corporate_street_2_pos = $index;
4294                                                                        break;
4295                                                                case 'Business Postal Code':
4296                                                                case 'CEP do endereço comercial':
4297                                                                        $cep_pos = $index;
4298                                                                        break;
4299                                                                case 'Business Fax':
4300                                                                case 'Fax comercial':
4301                                                                case 'Fax':
4302                                                                        $fax_pos = $index;
4303                                                                        break;
4304                                                                case 'Home Phone':
4305                                                                case 'Telefone residencial':
4306                                                                        $home_phone_pos = $index;
4307                                                                        break;
4308                                                                case 'Mobile phone':
4309                                                                case 'Telefone celular':
4310                                                                        $personal_cell_pos = $index;
4311                                                                        break;
4312                                                                case 'Pager':
4313                                                                        $pager_pos = $index;
4314                                                                        break;
4315                                                                case 'Phone':
4316                                                                case 'Business Phone':
4317                                                                case 'Telefone':
4318                                                                case 'Telefone principal':
4319                                                                case 'Telefone comercial':
4320                                                                case 'Telefone Comercial':
4321                                                                        $phone_pos = $index;
4322                                                                        break;
4323                                                                case 'Aniversário':
4324                                                                case 'Birthdate':
4325                                                                        $birth_pos = $index;
4326                                                                case 'Anotações':
4327                                                                case 'Notes':
4328                                                                        $notes_pos = $index;
4329                                                                case 'E-mail':
4330                                                                case 'Email':
4331                                                                case 'E-mail Address':
4332                                                                case 'Endereço de correio eletrônico':
4333                                                                case 'End. de email':
4334                                                                        $email_pos = $index;
4335                                                                        break;
4336                                                                case 'Endereço de correio eletrônico 2':
4337                                                                        $aditionalEmail_pos = $index;
4338                                                                        break;
4339                                                                }
4340                                                        }
4341                                                        break;
4342                                }
4343
4344                                while (($data = fgetcsv($handle, $len, $delim))) {
4345                                        foreach ($header as $key=>$heading)
4346                                $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
4347
4348                                                $sdata = array();
4349                                                $full_name  = trim($row[$header[$name_pos]]);
4350                                                $email          = trim($row[$header[$email_pos]]);
4351                                                $phone          = trim($row[$header[$phone_pos]]);
4352                                                $name2          = trim($row[$header[$name2_pos]]);
4353                                                $name3          = trim($row[$header[$name3_pos]]);
4354
4355                                                $birth          = trim($row[$header[$birth_pos]]);
4356                                                $notes          = trim($row[$header[$notes_pos]]);
4357                                                $altEmail       = trim($row[$header[$altEmail_pos]]);
4358                                                $sdata['alias']                         = trim($row[$header[$alias_pos]]);
4359                                                $sdata['corporate_name']      = trim($row[$header[$corporate_name_pos]]);
4360                                                $sdata['job_title']             = trim($row[$header[$job_title_pos]]);
4361                                                $sdata['department']            = trim($row[$header[$department_pos]]);
4362                                                $sdata['web_page']                      = trim($row[$header[$web_page_pos]]);
4363                                               
4364                                                $sdata['sex']                   = trim($row[$header[$sex_pos]]);
4365                                                $sdata['pgp_key']      = trim($row[$header[$pgp_key_pos]]);
4366
4367
4368                                        $full_name = $full_name;
4369                                        $array_name = explode(' ', str_replace('"','',(str_replace('\'','',$full_name))));
4370                                        $sdata['given_names'] = addslashes($array_name[0]);
4371                                        $array_name[0] = null;
4372                                        $sdata['family_names'] = trim(implode(' ',$array_name));
4373                                        if($sdata['family_names'] == '')
4374                                        {
4375                                                $sdata['family_names'] = addslashes($name2) . " " . addslashes($name3);
4376                                        }
4377
4378                                                $sdata['connections']['default_email']['connection_name'] = lang('Main');
4379                                                $sdata['connections']['default_email']['connection_value'] = addslashes($email);
4380                                                $sdata['connections']['aditional_email']['connection_name'] = "Alternativo";
4381                                                $sdata['connections']['aditional_email']['connection_value'] = trim($row[$header[$aditionalEmail_pos]]);
4382
4383                                                $sdata['connections']['default_phone']['connection_name'] = lang('Main');
4384                                       
4385                                                $sdata['connections']['default_phone']['connection_value'] = $phone;
4386
4387                                                if( trim($row[$header[$home_phone_pos]]) != "" )
4388                                                {
4389                                                    $sdata['connections']['aditional_phone']['home_phone']['connection_name'] = 'Casa';
4390                                                    $sdata['connections']['aditional_phone']['home_phone']['connection_value'] = trim($row[$header[$home_phone_pos]]);
4391                                                }
4392
4393                                                if( trim($row[$header[$personal_cell_pos]]) != "" )
4394                                                {
4395                                                    $sdata['connections']['aditional_phone']['cellphone']['connection_name'] = 'Celular';
4396                                                    $sdata['connections']['aditional_phone']['cellphone']['connection_value'] = trim($row[$header[$personal_cell_pos]]);
4397                                                }
4398
4399                                                if( trim($row[$header[$corporate_phone_pos]]) != "")
4400                                                {
4401                                                    $sdata['connections']['aditional_phone']['corporate_phone']['connection_name'] = 'Trabalho';
4402                                                    $sdata['connections']['aditional_phone']['corporate_phone']['connection_value'] = trim($row[$header[$corporate_phone_pos]]);
4403                                                }
4404
4405                                                if( trim($row[$header[$fax_pos]]) != "" )
4406                                                {
4407                                                    $sdata['connections']['aditional_phone']['fax']['connection_name'] = 'Fax';
4408                                                    $sdata['connections']['aditional_phone']['fax']['connection_value'] = trim($row[$header[$fax_pos]]);
4409                                                }
4410
4411                                                if ($GLOBALS['phpgw_info']['server']['personal_contact_type'] == 'True')
4412                                                {
4413                                                    if( trim($row[$header[$pager_pos]]) != "" )
4414                                                    {
4415                                                        $sdata['connections']['aditional_phone']['pager']['connection_name'] = 'Pager';
4416                                                        $sdata['connections']['aditional_phone']['pager']['connection_value'] = trim($row[$header[$pager_pos]]);
4417                                                    }
4418
4419                                                    if( trim($row[$header[$corporate_fax_pos]]) != "" )
4420                                                    {
4421                                                        $sdata['connections']['aditional_phone']['corporate_fax']['connection_name'] = 'Fax Corporativo';
4422                                                        $sdata['connections']['aditional_phone']['corporate_fax']['connection_value'] = trim($row[$header[$corporate_fax_pos]]);
4423                                                    }
4424
4425                                                    if( trim($row[$header[$corporate_cell_pos]]) != "" )
4426                                                    {
4427                                                        $sdata['connections']['aditional_phone']['corporate_cell']['connection_name'] = 'Celular Corporativo';
4428                                                        $sdata['connections']['aditional_phone']['corporate_cell']['connection_value'] = trim($row[$header[$corporate_cell_pos]]);
4429                                                    }
4430
4431                                                    if( trim($row[$header[$corporate_pager_pos]]) != "" )
4432                                                    {
4433                                                        $sdata['connections']['aditional_phone']['corporate_pager']['connection_name'] = 'Pager Corporativo';
4434                                                        $sdata['connections']['aditional_phone']['corporate_pager']['connection_value'] = trim($row[$header[$corporate_pager_pos]]);
4435                                                    }
4436                                                }
4437                                       
4438                                                $sdata['addresses']['address_corporative']['address1'] = trim($row[$header[$corporate_street_pos]]);
4439                                                $sdata['addresses']['address_corporative']['address2'] = trim($row[$header[$corporate_street_2_pos]]);
4440                                                $sdata['addresses']['address_corporative']['complement'] = trim($row[$header[$corporate_comp_pos]]);
4441                                                $sdata['addresses']['address_corporative']['postal_code'] = trim($row[$header[$corporate_cep_pos]]);                                           
4442                                                $sdata['addresses']['address_corporative']['id_country'] = "BR";
4443                                                $sdata['addresses']['address_corporative']['id_state'] = trim($row[$header[$corporate_state_pos]]);     
4444                                                $sdata['addresses']['address_corporative']['id_city'] = trim($row[$header[$corporate_city_pos]]);
4445                                               
4446                                                                                                       
4447                                                $sdata['addresses']['address_personal']['address1'] = trim($row[$header[$street_pos]]);
4448                                                $sdata['addresses']['address_personal']['address2'] = trim($row[$header[$street_2_pos]]);
4449                                                $sdata['addresses']['address_personal']['complement'] = trim($row[$header[$comp_pos]]);
4450                                                $sdata['addresses']['address_personal']['postal_code'] = trim($row[$header[$cep_pos]]);
4451                                                $sdata['addresses']['address_personal']['id_country'] = "BR";                                                   
4452                                                $sdata['addresses']['address_personal']['id_state'] = trim($row[$header[$state_pos]]); 
4453                                                $sdata['addresses']['address_personal']['id_city'] =  trim($row[$header[$city_pos]]);
4454
4455                                        if(trim($birth)) {
4456                                                $array_birth = explode("/",trim($birth));
4457                                                $sdata['birthdate'] = date('Y-m-d', mktime(0,0,0,$array_birth[1],$array_birth[0],$array_birth[2]));
4458                                        }
4459
4460                                        $sdata['notes'] = addslashes($notes);
4461                                        //$sdata['is_quick_add'] = true;
4462                                        $sdata['connections']['default_phone']['connection_value'] = $phone;
4463
4464                                        //      verifica se email já existe!
4465                                        $email = addslashes($email);
4466                                        $contact = $boGroup->verify_contact($email);
4467
4468                                        if(!$sdata['given_names'] && $email){
4469                                                        $a_email = explode("@",$email);
4470                                                        $sdata['given_names'] = addslashes($a_email[0]);
4471                                        }
4472
4473                                        $line_iteration = $return['_failure'] + $return['_existing'] + $return['_new'];
4474
4475                                        if($contact){
4476                                                $return['_existing']++;
4477                                        }
4478                                        else if((!eregi("^[/_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) && $email) {
4479                                                $return['_failure']++;
4480                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid E-Mail address: " . $email ."<br>";
4481                                        }
4482                                        else if (!$sdata['given_names'] || !$boPeople ->quick_add($sdata)){
4483                                                $return['_failure']++;
4484                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid Name: " . $sdata['given_names'] ."<br>";
4485                                        }
4486                                        else{   
4487                                                        if($id_group != 0){                                                             
4488                                                                $this->so_group->add_user_by_name($id_group,$full_name);
4489                                                        }                                               
4490                                                        $return['_new']++;
4491                                                }
4492                        }
4493                                fclose($handle);
4494                                unlink($file);
4495                        }
4496                        else
4497                                $return['error'] = true;
4498
4499                        echo serialize($return);
4500                }
4501       
4502                /*!
4503                 * @function get_contact_details
4504                 * @abstract Retorna os detalhes extras de um contato
4505                 * @author Luiz Carlos Viana Melo - Prognus
4506                 * @param (string) O ID do usuário do LDAP
4507                 */
4508                function get_contact_details($id)
4509                {
4510                        $data = array();
4511                       
4512                        if(!$this->bo->catalog->src_info) {
4513                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
4514                                $this->bo->catalog->src_info = $ldap->srcs[1];
4515                        }
4516                       
4517                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);                             
4518                        $dn=$this->bo->catalog->src_info['dn'];
4519                       
4520                        //buscar os atributos do ldap
4521                        $configobj = CreateObject('phpgwapi.config', 'contactcenter');
4522                        $prefs = $configobj->read_repository();
4523                        $attr_names = array();
4524                        $attr_types = array();
4525                        $justThese = array();
4526                        foreach ($prefs as $pref_key => $pref_value)
4527                        {
4528                                if (stripos($pref_key, "cc_attribute_name_") !== false)
4529                                {
4530                                        $num = substr($pref_key, strlen("cc_attribute_name_"));
4531                                        $attr_names[] = $prefs["cc_attribute_name_$num"];
4532                                        $attr_types[] = $prefs["cc_attribute_type_$num"];
4533                                        $justThese[] = strtolower($prefs["cc_attribute_ldapname_$num"]);
4534                                }
4535                        }
4536                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);                                                   
4537                        $info = ldap_get_entries($ds, $sr);
4538                        if ($info)
4539                        {
4540                                for ($i = 0; $i < count($justThese); $i++)
4541                                {
4542                                        $attr = array();
4543                                        $attr['name'] = $attr_names[$i];
4544                                        if ($attr_types[$i] == 'multivalues')
4545                                        {
4546                                                $attr['type'] = 'multivalues';
4547                                                $attr['value'] = array();
4548                                                for ($j = 0; $j < $info[0][$justThese[$i]]['count']; $j++)
4549                                                        $attr['value'][] = utf8_decode($info[0][$justThese[$i]][$j]);
4550                                        }
4551                                        else
4552                                        {
4553                                                $attr['type'] = 'text';
4554                                                $attr['value'] = utf8_decode($info[0][$justThese[$i]][0]);
4555                                        }
4556                                        $data[] = $attr;
4557                                }
4558                        }
4559                        else
4560                                $data = 'error';
4561                        ldap_close($ds);
4562                       
4563                        echo serialize($data);
4564                }
4565        }
4566
4567?>
Note: See TracBrowser for help on using the repository browser.