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

Revision 4502, 147.6 KB checked in by airton, 13 years ago (diff)

Ticket #1928 - Falhas na associação de um contato com um grupo de contato

  • 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                        $photo = imagecreatefromstring ($contact['photo']);
2992                        $width = imagesx($photo);
2993                        $height = imagesy($photo);
2994                        $twidth = 70;
2995                        $theight = 90;
2996                        $small_photo = imagecreatetruecolor ($twidth, $theight);
2997                        imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
2998                        imagejpeg($small_photo,"",100);
2999                        return;
3000                }
3001
3002                /*!
3003
3004                        @function get_states
3005                        @abstract Echos a serialized array containing all the states for the given country
3006                        @author Raphael Derosso Pereira
3007
3008                        @params $id_country The ID of the Country that contains the requested states
3009
3010                */
3011                function get_states($id_country)
3012                {
3013                        $states = $this->bo->catalog->get_all_states($id_country);
3014
3015                        if (!$states)
3016                        {
3017                                $result = array(
3018                                        'msg'    => lang('No States found for this Country.'),
3019                                        'status' => 'empty'
3020                                );
3021
3022                                echo serialize($result);
3023                                return;
3024                        }
3025
3026                        $result = array(
3027                                'msg'    => lang('States Successfully retrieved!'),
3028                                'status' => 'ok'
3029                        );
3030
3031                        foreach ($states as $state_info)
3032                        {
3033                                $result['data'][$state_info['id_state']] = $state_info['name'];
3034
3035                                if ($state_info['symbol'])
3036                                {
3037                                        $result['data'][$state_info['id_state']] .= ', '.$state_info['symbol'];
3038                                }
3039                        }
3040
3041                        echo serialize($result);
3042                }
3043
3044                /*!
3045
3046                        @function get_cities
3047                        @abstract Echos a serialized array containing all the cities of a given state
3048                        @author Raphael Derosso Pereira
3049
3050                        @param $id_country The ID of the Country that has the specified Cities (in case the
3051                                Country doesn't have any States)
3052                        @param $id_state The ID of the State that has the Cities requested
3053
3054                */
3055                function get_cities($id_country, $id_state=false)
3056                {
3057                        $cities = $this->bo->catalog->get_all_cities($id_country, $id_state);
3058
3059                        if (!$cities)
3060                        {
3061                                $result = array(
3062                                        'msg'    => lang('No Cities found for this State.'),
3063                                        'status' => 'empty'
3064                                );
3065
3066                                echo serialize($result);
3067                                return;
3068                        }
3069
3070                        $result = array(
3071                                'msg'    => lang('Cities Successfully retrieved!'),
3072                                'status' => 'ok'
3073                        );
3074
3075                        foreach ($cities as $city_info)
3076                        {
3077                                $result['data'][$city_info['id_city']] = $city_info['name'];
3078                        }
3079
3080                        echo serialize($result);
3081                }
3082
3083                //Traduz o campo na busca completa por entradas no catálogo do usuário.
3084                function aux_full_search ($field,$isldap) {
3085                        $retorno = '';
3086                        if($isldap) {
3087                                switch($field) {
3088                                        case 'mail':
3089                                                $retorno = 'contact.connection.mail';
3090                                                break;
3091                                        case 'phone':
3092                                                $retorno = 'contact.connection.phone';
3093                                                break;
3094                                }
3095                        }
3096                        else {
3097                                switch($field) {
3098                                        case 'corporate':
3099                                                $retorno = 'contact.corporate_name';
3100                                                break;
3101                                        case 'mail':
3102                                        case 'phone':
3103                                                $retorno = 'contact.contact_connection.connection.connection_value';
3104                                                break;
3105                                }
3106                        }
3107                        return $retorno;
3108                }
3109
3110                /*!
3111
3112                        @function search
3113                        @abstract Echos a serialized array containing the IDs
3114                                of the entries that matches the search argument
3115                        @author Raphael Derosso Pereira
3116                        @author Mário César Kolling (external catalogs)
3117
3118                        @param string $str_data A serialized array with two informations:
3119                                $data = array(
3120                                        'search_for' => (string),
3121                                        'recursive'  => (boolean),
3122                                );
3123
3124                */
3125                // SERPRO
3126                function search($str_data)
3127                {
3128                        $data = unserialize($str_data);
3129                        // It's an external catalog?
3130                        $external = $this->bo->is_external($this->page_info['actual_catalog']);
3131                        $full_search = isset($data['full_search'])?$data['full_search']:false;
3132                       
3133                        if (!is_array($data) || (!$data['search_for'] && !$full_search) || !is_array($data['fields']))
3134                        {
3135                                echo serialize(array(
3136                                        'msg'    => lang('Invalid parameters'),
3137                                        'status' => 'abort'
3138                                ));
3139
3140                                return array('error' => lang('Invalid parameters'));
3141                        }
3142
3143
3144                        /*
3145                         * TODO: look into the database to discover the database's encoding and convert the search_for field accordingly
3146                         */
3147                        // Support search parameters with accentuation
3148                        if ($this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
3149/**rev 104**/
3150                                //$this->page_info['actual_catalog']['class'] != 'bo_group_manager')
3151                                $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
3152                                $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
3153                                $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
3154/****/
3155                        {
3156
3157                                $data['search_for'] = utf8_encode($data['search_for']);
3158                        }
3159
3160                        $rules  = array();
3161
3162                        if ($data['search_for'] === '*')
3163                        {
3164                                $rules = array(
3165                                        0 => array(
3166                                                'field' => $data['fields']['search'],
3167                                                'type'  => 'LIKE',
3168                                                'value' => '%'
3169                                        )
3170                                );
3171                        }
3172                        else
3173                        {
3174                                $names = explode(' ', $data['search_for']);
3175
3176                                if (!is_array($names))
3177                                {
3178                                        if(!$full_search) {
3179                                                echo serialize(array(
3180                                                        'msg'    => lang('Invalid Search Parameter'),
3181                                                        'status' => 'abort'
3182                                                ));
3183                                                exit;
3184                                        }
3185                                        else
3186                                                $names = array();
3187
3188                                }
3189
3190                                if (!$external && $this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
3191/**rev 104**/
3192                                        //$this->page_info['actual_catalog']['class'] != 'bo_group_manager')
3193                                        $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
3194                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
3195                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager' )
3196/*****/
3197                                {
3198                                        /*
3199                                         * Restrict the returned contacts search to objectClass = phpgwAccount,
3200                                         * must have attibute phpgwAccountStatus, phpgwAccountVisible != -1
3201                                         */
3202                                       
3203                                        $rules = array(
3204                                                0 => array(
3205                                                        'field' => 'contact.object_class',
3206                                                        'type'  => '=',
3207                                                        'value' => 'phpgwAccount'
3208                                                ),
3209                                                1 => array(
3210                                                        'field' => 'contact.account_status',
3211                                                        'type'  => 'iLIKE',
3212                                                        'value' => '%'
3213                                                ),
3214/**rev 104**/
3215                                                ///
3216                                                //1 => array(
3217                                                2 => array(
3218/*****/
3219                                                        'field' => 'contact.account_visible',
3220                                                        'type'  => '!=',
3221                                                        'value' => '-1'
3222/**rev 104**/
3223        /*                                      ),
3224                                                2 => array(
3225                                                        'field' => 'contact.object_class',
3226                                                        'type'  => '=',
3227                                                        'value' => 'inetOrgPerson'
3228/****/
3229                                                ),
3230                                        );
3231
3232                                        if($full_search) {
3233                                                foreach($full_search as $field => $value) {
3234                                                        if(trim($value)!='')
3235                                                                array_push($rules,array(
3236                                                                                                'field' => $this->aux_full_search($field,true),
3237                                                                                                'type' => 'LIKE',
3238                                                                                                'value' => '*'.$value.'*'
3239                                                                                                ));
3240                                                }
3241                                        }
3242
3243                                }
3244                                else if(!$external && $full_search) {
3245                                       
3246                                        foreach($full_search as $field => $value) {
3247                                                if(trim($value)!='')
3248                                                        array_push($rules,array(
3249                                                                                        'field' => $this->aux_full_search($field,false),
3250                                                                                        'type' => 'iLIKE',
3251                                                                                        'value' => '%'.$value.'%'
3252                                                                                        ));
3253                                        }
3254                               
3255                                }
3256
3257                                foreach ($names as $name)
3258                                {
3259                                        if ($name != '')
3260                                        {
3261                                                array_push($rules, array(
3262                                                        'field' => $data['fields']['search'],
3263                                                        'type'  => 'iLIKE',
3264                                                        'value' => '%'.$name.'%'
3265                                                ));
3266                                        }
3267                                }
3268                        }
3269
3270                        if ($external || $this->page_info['actual_catalog']['class'] == 'bo_people_catalog' ||
3271/**rev 104**/
3272                                //$this->page_info['actual_catalog']['class'] == 'bo_group_manager')
3273                                $this->page_info['actual_catalog']['class'] == 'bo_group_manager' ||
3274                                $this->page_info['actual_catalog']['class'] == 'bo_shared_people_manager' ||
3275                                $this->page_info['actual_catalog']['class'] == 'bo_shared_group_manager')
3276
3277
3278/***/
3279                        {
3280                                // Get only this attributes: dn, cn for external catalogs,
3281                                // used to restrict the attributes used in filters
3282                                $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'), $data['search_for'] != null);
3283                        }
3284                        else
3285                        {
3286                                // Get only this attributes: dn, cn, phpgwAccountType, objectClass, phpgwAccountStatus, phpghAccountVisible
3287                                // for non-external catalogs, used to restrict the attributes used in filters
3288                                $ids = $this->bo->find(array(
3289                                        $data['fields']['id'],
3290                                        $data['fields']['search'],
3291                                        'contact.object_class',
3292                                        //'contact.account_status',
3293                                        'contact.account_visible',
3294                                        'contact.connection.mail',
3295                                        'contact.connection.phone'
3296                                        ), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'), $data['search_for_area'], $data['search_for'] != null );
3297                        }
3298
3299                        if (!is_array($ids) || !count($ids))
3300                        {
3301                                $this->last_search_ids = null;
3302                                $this->save_session();
3303                                return null;
3304                        }
3305
3306                        $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
3307
3308                        $ids_f = array();
3309
3310                        foreach ($ids as $e_info)
3311                        {
3312/**rev 104**/
3313                                //$ids_f[] = $e_info[$id_field];
3314                                if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
3315                                {
3316                                        $ids_f[] = $e_info[$id_field];
3317                                } else{
3318                                        $ids_f[] = array(0=>$e_info[$id_field],1=>$e_info['perms'],2=>$e_info['owner']);
3319                                }
3320/****/
3321                        }
3322
3323                        return $ids_f;
3324                }
3325
3326                // CELEPAR
3327                /*
3328        function search($str_data)
3329        {
3330            $data = unserialize($str_data);
3331
3332            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
3333            {
3334                echo serialize(array(
3335                    'msg'    => lang('Invalid parameters'),
3336                    'status' => 'abort'
3337                ));
3338
3339                return;
3340            }
3341
3342            $rules  = array();
3343
3344            if ($data['search_for'] === '*')
3345            {
3346                $rules = array(
3347                    0 => array(
3348                        'field' => $data['fields']['search'],
3349                        'type'  => 'LIKE',
3350                        'value' => '%'
3351                    )
3352                );
3353            }
3354            else
3355            {
3356                $names = explode(' ', $data['search_for']);
3357
3358                if (!is_array($names))
3359                {
3360                    echo serialize(array(
3361                        'msg'    => lang('Invalid Search Parameter'),
3362                        'status' => 'abort'
3363                    ));
3364
3365                    return;
3366                }
3367
3368                foreach ($names as $name)
3369                {
3370                    if ($name != '')
3371                    {
3372                        array_push($rules, array(
3373                            'field' => $data['fields']['search'],
3374                            'type'  => 'iLIKE',
3375                            'value' => '%'.$name.'%'
3376                        ));
3377                    }
3378                }
3379            }
3380
3381
3382
3383            //$catalog = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
3384
3385            //if ($catalog['class'] === 'bo_people_catalog')
3386            //{
3387            //    array_push($rules, array(
3388            //        'field' => 'contact.id_owner',
3389            //        'type'  => '=',
3390            //        'value' => $GLOBALS['phpgw_info']['user']['account_id']
3391            //    ));
3392            //}
3393
3394
3395            $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
3396
3397            if (!is_array($ids) || !count($ids))
3398            {
3399                echo serialize(array(
3400                    'msg'    => lang('No Entries Found!'),
3401                    'status' => 'empty'
3402                ));
3403
3404                return;
3405            }
3406            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
3407
3408            $ids_f = array();
3409            foreach ($ids as $e_info)
3410            {
3411                $ids_f[] = $e_info[$id_field];
3412            }
3413
3414            echo serialize(array(
3415                'data'   => $ids_f,
3416                'msg'    => lang('Found %1 Entries', count($ids)),
3417                'status' => 'ok'
3418            ));
3419
3420                        return;
3421        }*/
3422                /*!
3423
3424                        @function get_multiple_entries
3425                        @abstract Returns an array containing the specifiend data in the default
3426                                CC UI format
3427                        @author Raphael Derosso Pereira
3428
3429                        @param array str_data A serialized array containing the ID's of the entries
3430                                to be taken, the fields to be taken and the rules to be used on the
3431                                retrieval:
3432                                $data = array(
3433                                        'ids'    => array(...),
3434                                        'fields' => array(...),
3435                                        'rules'  => array(...)
3436                                );
3437
3438                */
3439                function get_multiple_entries($str_data)
3440                {
3441                        $data = unserialize($str_data);
3442
3443                        if (!is_array($data) or !count($data) or !count($data['fields']) or !count($data['ids']))
3444                        {
3445                                return array(
3446                                        'msg'    => lang('Invalid Parameters'),
3447                                        'status' => 'abort'
3448                                );
3449                        }
3450
3451                        $entries = $this->bo->catalog->get_multiple_entries($data['ids'], $data['fields']);
3452
3453                        if (!is_array($entries) or !count($entries))
3454                        {
3455                                return array(
3456                                        'msg'    => lang('No Entries Found!'),
3457                                        'status' => 'empty'
3458                                );
3459                        }
3460
3461                        return array(
3462                                'msg'    => lang('Found %1 Entries!', count($entries)),
3463                                'status' => 'ok',
3464                                'data'   => $entries
3465                        );
3466                }
3467
3468                /*
3469
3470                        @function get_all_entries
3471                        @abstract Returns the specified fields for all catalog's entries
3472                                in the default CC UI format
3473                        @author Raphael Derosso Pereira
3474
3475                        @params array str_data A serialized array containing the fields to
3476                                be grabbed, the maximum number of entries to be returned and a
3477                                boolean specifying if the calls refers to a new grab or to an
3478                                unfinished one.
3479
3480                */
3481                function get_all_entries($str_data)
3482                {
3483                        $data = unserialize($str_data);
3484
3485                        if (!is_array($data) or
3486                            !count($data) or
3487                                !count($data['fields']) or
3488                                !$data['maxlength'] or
3489                                (!$data['new'] and !$data['offset']))
3490                        {
3491                                return array(
3492                                        'msg'    => lang('Invalid Parameters'),
3493                                        'status' => 'abort'
3494                                );
3495                        }
3496
3497                        if ($data['new'])
3498                        {
3499                                $this->all_entries = $this->bo->catalog->get_all_entries_ids();
3500
3501                                $this->save_session();
3502
3503                                if (!is_array($this->all_entries) or !count($this->all_entries))
3504                                {
3505                                        return array(
3506                                                'msg'    => lang('No Entries Found!'),
3507                                                'status' => 'empty'
3508                                        );
3509                                }
3510
3511                                $data['offset'] = 0;
3512                        }
3513
3514                        if ($data['maxlength'] != -1)
3515                        {
3516                                $result = $this->bo->catalog->get_multiple_entries(array_slice($this->all_entries, $data['offset'], $data['maxlength']), $data['fields']);
3517                        }
3518                        else
3519                        {
3520                                $result = $this->bo->catalog->get_multiple_entries($this->all_entries, $data['fields']);
3521                        }
3522
3523                        $jsCode = array();
3524                        $count = 0;
3525                        foreach ($result as $each)
3526                        {
3527                                if (!is_array($each))
3528                                {
3529                                        continue;
3530                                }
3531
3532                                if($this-> typeContact == 'groups') {
3533
3534                                        foreach ($each as $field => $value)     {
3535
3536                                                if ($field === 'title') {
3537                                                        $optionName = '\\"'.$value.'\\"';
3538
3539                                                }
3540                                                else if ($field === 'short_name')       {
3541
3542                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$optionName.' ('.$value.')", "'.$count.'");';
3543                                                        $count++;
3544                                                }
3545                                        }
3546                                }
3547
3548                                else  {
3549                                        foreach ($each as $field => $value)     {
3550                                                if ($field === 'names_ordered') {
3551                                                         if(is_array($value))
3552                                $value = $value[0];
3553                                                        $name = '\\"'.$value.'\\"';
3554                                                }
3555                                                else if ($field === 'connections')      {
3556
3557                                                        foreach ($value as $connection)         {
3558                                                                if ($connection['id_type'] == $this->preferences['personCardEmail'])    {
3559                                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$name.' <'.$connection['connection_value'].'>", "'.$count.'");';
3560                                                                        $count++;
3561                                                                }
3562                                                        }
3563                                                }
3564                                        }
3565                                }
3566                        }
3567
3568                        $jsCodeFinal = implode("\n", $jsCode);
3569
3570                        $nEntries = count($result);
3571
3572                        if (!$nEntries)
3573                        {
3574                                return array(
3575                                        'msg'    => lang('Error while getting user information...'),
3576                                        'status' => 'abort'
3577                                );
3578                        }
3579
3580                        return array(
3581                                'msg'      => lang('Found %1 Entries!', $nEntries),
3582                                'status'   => 'ok',
3583                                'typeContact'   => $this -> typeContact,
3584                                'final'    => $nEntries + $data['offset'] < count($this->all_entries) ? false : true,
3585                                'offset'   => $data['offset'] + $nEntries,
3586                                'data'     => $jsCodeFinal
3587                        );
3588                }
3589
3590                /*********************************************************************\
3591                 *                      Auxiliar Methods                             *
3592                \*********************************************************************/
3593
3594                /*!
3595
3596                        @function save_session
3597                        @abstract Saves the data on the session
3598                        @author Raphael Derosso Pereira
3599
3600                */
3601                function save_session()
3602                {
3603                        $GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter',$this->page_info);
3604                        $GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter',$this->all_entries);
3605                }
3606
3607                /*!
3608
3609                        @function convert_tree
3610                        @abstract Converts the tree array in the BO format to a JS tree array compatible
3611                                with the one available in eGW
3612                        @author Raphael Derosso Pereira
3613
3614                        @param (array)  $tree    The tree in the BO format
3615                        @param (string) $name    The tree name
3616                        @param (string) $iconDir The dir where the icons are
3617                        @param (string) $parent  The parent
3618                */
3619
3620                function convert_tree($tree, &$iconDir, $parent='0')
3621                {
3622//                      echo "Entrou<br>\tPai: $parent <br>";
3623                        $rtree = array();
3624
3625                        if ($parent === '0')
3626                        {
3627//                              echo 'Root!<br>';
3628                                $rtree['0'] = array(
3629                                        'type'       => 'catalog_group',
3630                                        'id'         => '0',
3631                                        'pid'        => 'none',
3632                                        'caption'    => lang('Catalogues'),
3633                                        'class'      => 'bo_catalog_group_catalog',
3634                                        'class_args' => array('_ROOT_', '$this', '$this->get_branch_by_level($this->catalog_level[0])')
3635                                );
3636                        }
3637
3638                        foreach($tree as $id => $value)
3639                        {
3640//                              echo 'ID: '.$id.'<br>';
3641                                $rtree[$parent.'.'.$id] = array(
3642                                        'type'    => $value['type'],
3643                                        'id'      => $parent.'.'.$id,
3644                                        'pid'     => $parent,
3645                                        'caption' => $value['name']
3646                                );
3647
3648                                switch($value['type'])
3649                                {
3650                                        case 'catalog_group':
3651                                        case 'mixed_catalog_group':
3652                                                $rtree = $rtree + $this->convert_tree($value['sub_branch'],$iconDir,$parent.'.'.$id);
3653                                                break;
3654                                }
3655                        }
3656
3657                        if (count($rtree))
3658                        {
3659                                return $rtree;
3660                        }
3661                }
3662
3663                function get_catalog_add_contact($id, $echo=true){
3664
3665                        $array_participants = array();
3666                        if(!$this->bo->catalog->src_info) {
3667                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3668                                $this->bo->catalog->src_info = $ldap->srcs[1];
3669                        }
3670
3671                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3672                        $dn=$this->bo->catalog->src_info['dn'];
3673                        $justThese = array("givenname","givenname","sn","telephonenumber","mail");
3674                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);
3675                        $info = ldap_get_entries($ds, $sr);
3676                        for($z = 0; $z < 5; $z++) {
3677                                $participant = $info[0][$justThese[$z]];
3678                                $participant[0] = utf8_decode($participant[0]);
3679                                array_push($array_participants, $participant);
3680                        }
3681
3682                        ldap_close($ds);
3683                        if ($echo)
3684                        {
3685                            echo serialize($array_participants);
3686                        }
3687                        else
3688                            {
3689                                return serialize($array_participants);
3690                            }
3691                }
3692
3693                function get_catalog_participants_group($id)
3694                {
3695                        if(!$this->bo->catalog->src_info) {
3696                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3697                                $this->bo->catalog->src_info = $ldap->srcs[1];
3698                        }
3699                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3700                        $justThese = array("description","memberuid");
3701                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);
3702                        $info = ldap_get_entries($ds, $sr);
3703                        $member_uids = $info[0]['memberuid'];
3704                        $contact['names_ordered'] = $info[0]['description'];
3705                        $filter = "";
3706                        for($z = 0; $z < count($member_uids); $z++) {
3707                                if($member_uids[$z])
3708                                        $filter.="(uid=".$member_uids[$z].")";
3709                        }
3710                        $array_participants = array();
3711                        if($filter) {
3712                                $filter = "(|".$filter.")";
3713                                $valarray = explode(',',$id);
3714                                array_shift($valarray);
3715                                $dn = implode(',',$valarray);
3716                                $justThese = array("cn","mail");
3717                                $sr = ldap_search($ds,$dn, $filter,$justThese);
3718                                $info = ldap_get_entries($ds, $sr);
3719                                for($z = 0; $z < $info['count']; $z++) {
3720                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3721                                    $array_emails[$info[$z]['mail'][0]] = null;
3722                                        array_push($array_participants, $participant);
3723                                }
3724                                ldap_close($ds);
3725                        }
3726                        sort($array_participants);
3727                        $innerHTML = '';
3728                        foreach($array_participants as $index => $participant){
3729                                $innerHTML .= $participant;
3730                        }
3731                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
3732                        echo serialize($return);
3733                }
3734
3735                function get_catalog_participants_list($id)
3736                {
3737
3738                        $fields = $this->bo->catalog->get_fields(false);
3739                        $fields['names_ordered'] = true;
3740                        $fields['mail_forwarding_address'] = true;
3741                        $contact = $this->bo->catalog->get_single_entry($id,$fields);
3742
3743                        $array_participants = array();
3744                        $array_emails = array();
3745
3746                        $filter = null;
3747                        for($z = 0; $z < $contact['mail_forwarding_address']['count']; $z++) {
3748                                        if(strstr($contact['mail_forwarding_address'][$z],'@')) {
3749                                                $filter.="(mail=".$contact['mail_forwarding_address'][$z].")";
3750                                                $array_emails[$contact['mail_forwarding_address'][$z]] = "<font color=black>".$contact['mail_forwarding_address'][$z]."</font>";
3751                                        }
3752                                        else
3753                                                $array_participants[$z] = "<font color=red>".$contact['mail_forwarding_address'][$z]."</font>";
3754                        }
3755
3756                        if($filter) {
3757                                $filter = "(|".$filter.")";
3758                                if(!$this->bo->catalog->src_info) {
3759                                        $ldap = CreateObject('contactcenter.bo_ldap_manager');
3760                                        $this->bo->catalog->src_info = $ldap->srcs[1];
3761                                }
3762                                $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3763                                $dn=$this->bo->catalog->src_info['dn'];
3764                                $justThese = array("cn","mail");
3765                                $sr = ldap_search($ds,$dn, $filter,$justThese);
3766                                $info = ldap_get_entries($ds, $sr);
3767                                for($z = 0; $z < $info['count']; $z++) {
3768                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3769                                        $array_emails[$info[$z]['mail'][0]] = null;
3770                                        array_push($array_participants, $participant);
3771                                }
3772
3773                                foreach($array_emails as $index => $email)
3774                                        if($email)
3775                                                array_push($array_participants, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$email."<br>");
3776
3777                                ldap_close($ds);
3778                        }
3779                        sort($array_participants);
3780                        $innerHTML = '';
3781                        foreach($array_participants as $index => $participant){
3782                                $innerHTML .= $participant;
3783                        }
3784                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
3785                        echo serialize($return);
3786                }
3787
3788                function export_contacts($typeExport){
3789
3790                        $boGroup = CreateObject('contactcenter.bo_group');
3791                        $contacts = $boGroup->get_all_contacts();
3792                        $streamBuffer = '';
3793
3794                        if(!count($contacts))
3795                                echo null;
3796
3797                        switch($typeExport) {
3798
3799                                case 'outlook_en':
3800                                        $streamBuffer = "Name;E-mail Address;Notes;Mobile Phone;Pager;Company;".
3801                                                        "Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";                                                       
3802                                        foreach($contacts as $index => $object){
3803                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\";"
3804                                                        . "\"".$object[ 'main-mail' ] . "\";"
3805                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\";"
3806                                                        . "\"".$object[ 'mobile' ] . "\";"
3807                                                        . "\"".$object[ 'business-pager' ] . "\";"
3808                                                        . "\"".$object[ 'corporate_name' ] . "\";"
3809                                                        . "\"".$object[ 'job_title' ] . "\";"
3810                                                        . "\"".$object[ 'home-phone' ] . "\";"
3811                                                        . "\"".$object[ 'home-fax' ] . "\";"
3812                                                        . "\"".$object[ 'business-phone' ] . "\";"
3813                                                        . "\"".$object[ 'business-fax' ] . "\"\r\n";
3814                                        }
3815                                        break;
3816
3817                                case 'outlook_pt-BR':
3818                                        $streamBuffer = "Nome;Sobrenome;Segundo nome;Nome;Apelido;End. de email;Endereço residencial;"
3819                                                                        ."Cidade do endereço residencial;CEP do endereço residencial;Estado;País/região do endereço residencial;"
3820                                                                        ."Telefone residencial;Fax residencial;Telefone celular;Página pessoal da Web;Rua do endereço comercial;"
3821                                                                        ."Cidade do endereço comercial;CEP do endereço comercial;Estado do endereço comercial;"
3822                                                                        ."País/região do endereço comercial;Página comercial da Web;Telefone comercial;Fax comercial;Pager;Empresa;"
3823                                                                        ."Cargo;Departamento;End. comercial;Observações\r\n";
3824
3825                                        foreach($contacts as $index => $object){
3826                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\";"
3827                                                        .";;;"
3828                                                        . "\"".$object[ 'alias' ] . "\";"
3829                                                        . "\"".$object[ 'main-mail' ] . "\";"
3830                                                        . "\"".$object[ 'home-address' ] . "\";"
3831                                                        . "\"".$object[ 'home-city_name' ] . "\";"
3832                                                        . "\"".$object[ 'home-postal_code' ] . "\";"
3833                                                        . "\"".$object[ 'home-state_name' ] . "\";"
3834                                                        . "\"".$object[ 'home-id_country' ] . "\";"
3835                                                        . "\"".$object[ 'home-phone' ] . "\";"
3836                                                        . "\"".$object[ 'home-fax' ] . "\";"
3837                                                        . "\"".$object[ 'mobile' ] . "\";"
3838                                                        . "\"".$object[ 'web_page' ] . "\";"
3839                                                        . "\"".$object[ 'business-address' ] . "\";"
3840                                                        . "\"".$object[ 'business-city_name' ] . "\";"
3841                                                        . "\"".$object[ 'business-postal_code' ] . "\";"
3842                                                        . "\"".$object[ 'business-state_name' ] . "\";"
3843                                                        . "\"".$object[ 'business-id_country' ] . "\";"
3844                                                        . "\"".$object[ 'web_page' ] . "\";"
3845                                                        . "\"".$object[ 'business-phone' ] . "\";"
3846                                                        . "\"".$object[ 'business-fax' ] . "\";"
3847                                                        . "\"".$object[ 'business-pager' ] . "\";"
3848                                                        . "\"".$object[ 'corporate_name' ] . "\";"
3849                                                        . "\"".$object[ 'job_title' ] . "\";"
3850                                                        . "\"".$object[ 'department' ] . "\";"
3851                                                        .";"
3852                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\"\r\n";
3853                                        }
3854
3855                                break;
3856
3857                                case 'outlook2000_pt-BR':
3858                                        $streamBuffer = "\"Tratamento\",\"Nome\",\"Segundo Nome\",\"Sobrenome\",\"Sufixo\",".
3859                                        "\"Empresa\",\"Departamento\",\"Cargo\",\"Rua do endereço comercial\",\"Rua do endereço comercial 2\",".
3860                                        "\"Rua do endereço comercial 3\",\"Cidade do endereço comercial\",\"Estado do endereço comercial\",".
3861                                        "\"CEP do endereço comercial\",\"País do endereço comercial\",\"Endereço residencial\",\"Rua residencial 2\",".
3862                                        "\"Rua residencial 3\",\"Cidade do endereço residencial\",\"Estado\",\"CEP do endereço residencial\",\"País do endereço residencial\",".
3863                                        "\"Outro endereço\",\"Outro endereço 2\",\"Outro endereço 3\",\"Cidade\",\"Estado\",\"CEP\",\"País\",".
3864                                        "\"Telefone do assistente\",\"Fax comercial\",\"Telefone comercial\",\"Telefone comercial 2\",\"Retorno de chamada\",".
3865                                        "\"Telefone do carro\",\"Telefone principal da empresa\",\"Fax residencial\",\"Telefone residencial\",".
3866                                        "\"Telefone residencial 2\",\"ISDN\",\"Telefone celular\",\"Outro fax\",\"Outro telefone\",\"Pager\",\"Telefone principal\",".
3867                                        "\"Radiofone\",\"Telefone TTY/TDD\",\"Telex\",\"Aniversário\",\"Anotações\",\"Caixa postal\",\"Categorias\",".
3868                                        "\"Código da empresa\",\"Código do governo\",\"Cônjuge\",\"Conta\",\"Endereço de correio eletrônico\",".
3869                                        "\"Nome de exibição do correio eletr.\",\"Endereço de correio eletrônico 2\",".
3870                                        "\"Nome de exibição do correio eletr.2\",\"Endereço de correio eletrônico 3\",".
3871                                        "\"Nome de exibição do correio eletr.3\",\"Datas especiais\",\"Disponibilidade da Internet\",".
3872                                        "\"Filhos\",\"Hobby\",\"Idioma\",\"Indicação\",\"Informações para cobrança\",\"Iniciais\",\"Local\",".
3873                                        "\"Nome do assistente\",\"Nome do gerenciador\",\"Página da Web\",\"Palavras-chave\",\"Particular\",\"Personalizado 1\",\"Personalizado 2\",".
3874                                        "\"Personalizado 3\",\"Personalizado 4\",\"Prioridade\",\"Profissão\",\"Quilometragem\",\"Sala\",\"Sensibilidade\",\"Servidor de diretório\",".
3875                                        "\"Sexo\"\r\n";
3876
3877
3878
3879                                        foreach($contacts as $index => $object){
3880                                $streamBuffer .= "\"".$object[ 'alias' ] . "\","                                   
3881                                                                . "\"".$object[ 'names_ordered' ] . "\","
3882                                                                .",,,"
3883                                                                . "\"".$object[ 'corporate_name' ] . "\","
3884                                                                . "\"".$object[ 'department' ] . "\","
3885                                                                . "\"".$object[ 'job_title' ] . "\","
3886                                                                . "\"".$object[ 'business-address' ] . "\","
3887                                                                . "\"".$object[ 'business-address-2' ] . "\","
3888                                                                .","
3889                                                                . "\"".$object[ 'business-city_name' ] . "\","
3890                                                                . "\"".$object[ 'business-state' ] . "\","
3891                                                                . "\"".$object[ 'business-postal_code' ] . "\","
3892                                                                . "\"".$object[ 'business-id_country' ] . "\","
3893                                                                . "\"".$object[ 'home-address' ] . "\","
3894                                                                . "\"".$object[ 'home-address-2' ] . "\","
3895                                                                .","
3896                                                                . "\"".$object[ 'home-city_name' ] . "\","
3897                                                                . "\"".$object[ 'home-state_name' ] . "\","
3898                                                                . "\"".$object[ 'home-postal_code' ] . "\","
3899                                                                . "\"".$object[ 'home-id_country' ] . "\","
3900                                                                .",,,,,,,,"
3901                                                                . "\"".$object[ 'business-fax' ] . "\","
3902                                                                . "\"".$object[ 'business-phone' ] . "\","
3903                                                                . "\"".$object[ 'business-mobile' ] . "\","
3904                                                                .",,,"
3905                                                                . "\"".$object[ 'home-fax' ] . "\","
3906                                                                . "\"".$object[ 'home-phone' ] . "\","
3907                                                                .",,"
3908                                                                . "\"".$object[ 'mobile' ] . "\","
3909                                                                .",,"
3910                                                                . "\"".$object[ 'home-pager' ] . "\","
3911                                                                . "\"".$object[ 'business-phone' ] . "\","
3912                                                                .",,,"
3913                                                                . "\"".$object[ 'birthdate' ] . "\","
3914                                                                . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
3915                                                                .",,,,,,"
3916                                                                . "\"".$object[ 'main-mail' ] . "\","
3917                                                                .","
3918                                                                . "\"".$object[ 'alternative-mail' ] . "\","
3919                                                                .",,,,,,,,,,,,,,"
3920                                                                . "\"".$object[ 'web_page' ] . "\","
3921                                                                .",,,,,,,,,,,,"
3922                                                                . "\"".$object[ 'sex' ] . "\"\r\n";                                                             
3923                            }
3924                                break;
3925
3926                                case 'outlook2000_en':
3927                                        $streamBuffer = "Title,First Name,Middle Name,Last Name,Suffix,Company,Department,Job Title,".
3928                                        "Business Street,Business Street 2,Business Street 3,Business City,Business State,Business Postal Code,".
3929                                        "Business Country,Home Street,Home Street 2,Home Street 3,Home City,Home State,Home Postal Code,Home Country,".
3930                                        "Other Street,Other Street 2,Other Street 3,Other City,Other State,Other Postal Code,Other Country,".
3931                                        "Assistant's Phone,Business Fax,Business Phone,Business Phone 2,Callback,Car Phone,Company Main Phone,Home Fax,".
3932                                        "Home Phone,Home Phone 2,ISDN,Mobile Phone,Other Fax,Other Phone,Pager,Primary Phone,Radio Phone,TTY/TDD Phone,Telex,".
3933                                        "Account,Anniversary,Assistant's Name,Billing Information,Birthday,Categories,Children,Directory Server,E-mail Address,".
3934                                        "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,".
3935                                        "Gender,Government ID Number,Hobby,Initials,Internet Free Busy,Keywords,Language,Location,Manager's Name,Mileage,Notes,".
3936                                        "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";
3937
3938                                        foreach($contacts as $index => $object){
3939                                                if( array_key_exists("phone", $object) )
3940                                                        $phone = $object['phone'];
3941                                                else
3942                            $phone = $object['business-phone'];
3943                                       
3944                                                $streamBuffer.= "\"".$object[ 'alias' ] . "\","
3945                                                        . "\"".$object[ 'names_ordered'] . "\","
3946                                                        .",,,"
3947                                                        . "\"".$object[ 'corporate_name' ] . "\","
3948                                                        . "\"".$object[ 'department' ] . "\","
3949                                                        . "\"".$object[ 'job_title' ] . "\","
3950                                                        . "\"".$object[ 'business-address' ] . "\","
3951                                                        . "\"".$object[ 'business-address-2' ] . "\","
3952                                                        .","
3953                                                        . "\"".$object[ 'business-city_name' ] . "\","
3954                                                        . "\"".$object[ 'business-state' ] . "\","
3955                                                        . "\"".$object[ 'business-postal_code' ] . "\","
3956                                                        . "\"".$object[ 'business-id_country' ] . "\","
3957                                                        . "\"".$object[ 'home-address' ] . "\","
3958                                                        . "\"".$object[ 'home-address-2' ] . "\","
3959                                                        .","
3960                                                        . "\"".$object[ 'home-city_name' ] . "\","
3961                                                        . "\"".$object[ 'home-state_name' ] . "\","
3962                                                        . "\"".$object[ 'home-postal_code' ] . "\","
3963                                                        . "\"".$object[ 'home-id_country' ] . "\","
3964                                                        .",,,,,,,,"
3965                                                        . "\"".$object[ 'business-fax' ] . "\","
3966                                                        . "\"".$phone . "\","
3967                                                        . "\"".$object[ 'business-mobile' ] . "\","
3968                                                        .",,,"
3969                                                        . "\"".$object[ 'home-fax' ] . "\","
3970                                                        . "\"".$object[ 'home-phone' ] . "\","
3971                                                        .",,"
3972                                                        . "\"".$object[ 'mobile' ] . "\","
3973                                                        .",,"
3974                                                        . "\"".$object[ 'business-pager' ] . "\","
3975                                                        . "\"".$object[ 'home-pager' ] . "\","
3976                                                        .",,,,,,,,"
3977                                                        . "\"".$object[ 'birthdate' ] . "\","
3978                                                        .",,,"
3979                                                        . "\"".$object[ 'main-mail' ] . "\","
3980                                                        .",,"
3981                                                        . "\"".$object[ 'alternative-mail' ] . "\","
3982                                                        .",,,,,,,,,,,,,,,"
3983                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
3984                                                        .",,,,,,,,,,,,,"
3985                                                        . "\"".$object[ 'web_page' ] . "\"\r\n";
3986
3987                                        }
3988                                break;
3989
3990                                case 'thunderbird':
3991                                        $streamBuffer = "First Name,Last Name,Display Name,Nickname,Primary Email,Secondary Email,"
3992                                                ."Screen Name,Work Phone,Home Phone,Fax Number,Pager Number,Mobile Number,Home Address,"
3993                                                ."Home Address 2,Home City,Home State,Home ZipCode,Home Country,Work Address,Work Address 2,"
3994                                                ."Work City,Work State,Work ZipCode,Work Country,Job Title,Department,Organization,Web Page 1,"
3995                                                ."Web Page 2,Birth Year,Birth Month,Birth Day,Custom 1,Custom 2,Custom 3,Custom 4,Notes,\n";
3996
3997                                        foreach($contacts as $index => $object){
3998                                                $array_birth = explode("-",$object[ 'birthdate' ]);
3999                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\","
4000                                                        .",,"
4001                                                        . "\"".$object[ 'alias' ] . "\","
4002                                                        . "\"".$object[ 'main-mail' ] . "\","
4003                                                        . "\"".$object[ 'alternative-mail' ] . "\","
4004                                                        .","
4005                                                        . "\"".$phone . "\","
4006                                                        . "\"".$object[ 'home-phone' ] . "\","
4007                                                        . "\"".$object[ 'business-fax' ] . "\","
4008                                                        . "\"".$object[ 'business-pager' ] . "\","
4009                                                        . "\"".$object[ 'mobile' ] . "\","
4010                                                        . "\"".$object[ 'home-address' ] . "\","
4011                                                        . "\"".$object[ 'home-address-2' ] . "\","
4012                                                        . "\"".$object[ 'home-city_name' ] . "\","
4013                                                        . "\"".$object[ 'home-state_name' ] . "\","
4014                                                        . "\"".$object[ 'home-postal_code' ] . "\","
4015                                                        . "\"".$object[ 'home-id_country' ] . "\","
4016                                                        . "\"".$object[ 'business-address' ] . "\","
4017                                                        . "\"".$object[ 'business-address-2' ] . "\","
4018                                                        . "\"".$object[ 'business-city_name' ] . "\","
4019                                                        . "\"".$object[ 'business-state_name' ] . "\","
4020                                                        . "\"".$object[ 'business-postal_code' ] . "\","
4021                                                        . "\"".$object[ 'business-id_country' ] . "\","
4022                                                        . "\"".$object[ 'job_title' ] . "\","
4023                                                        . "\"".$object[ 'department' ] . "\","
4024                                                        . "\"".$object[ 'corporate_name' ] . "\","
4025                                                        . "\"".$object[ 'web_page' ] . "\","
4026                                                        . "\"".$object[ 'web_page' ] . "\","
4027                                                        . "\"".$array_birth[0] . "\","
4028                                                        . "\"".$array_birth[1] . "\","
4029                                                        . "\"".$array_birth[2] . "\","
4030                                                        .",,,,"
4031                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\",\r\n";
4032
4033                                        }
4034                                break;
4035
4036                                case 'expresso':
4037                            $streamBuffer = 'Nome,Apelido,E-mail Principal,E-mail Alternativo,Celular,'
4038                                . 'Telefone Comercial,Endereço Comercial,Complemento End. Comercial,CEP Comercial,Cidade End. Comercial,Estado End. Comercial,País End. Comercial,'
4039                                . 'Telefone Residencial,Endereço Residencial,Complemento End. Residencial,CEP Residencial,Cidade End. Residencial,Estado End. Residencial,País End. Residencial,'
4040                                . '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'
4041                                                        . "\r\n";
4042
4043                            foreach($contacts as $index => $object){
4044                                $streamBuffer .= "\"".$object[ 'names_ordered'] . "\","
4045                                    . "\"".$object[ 'alias' ] . "\","
4046                                    . "\"".$object[ 'main-mail' ] . "\","
4047                                    . "\"".$object[ 'alternative-mail' ] . "\","
4048                                    . "\"".$object[ 'mobile' ] . "\","
4049                                    . "\"".$object[ 'business-phone' ] . "\","
4050                                    . "\"".$object[ 'business-address' ] . "\","
4051                                    . "\"".$object[ 'business-complement' ] . "\","
4052                                    . "\"".$object[ 'business-postal_code' ] . "\","
4053                                    . "\"".$object[ 'business-city_name' ] . "\","
4054                                    . "\"".$object[ 'business-state_name' ] . "\","
4055                                    . "\"".$object[ 'business-id_country' ] . "\","
4056                                    . "\"".$object[ 'home-phone' ] . "\","
4057                                    . "\"".$object[ 'home-address' ] . "\","
4058                                    . "\"".$object[ 'home-complement' ] . "\","
4059                                    . "\"".$object[ 'home-postal_code' ] . "\","
4060                                    . "\"".$object[ 'home-city_name' ] . "\","
4061                                    . "\"".$object[ 'home-state_name' ] . "\","
4062                                    . "\"".$object[ 'home-id_country' ] . "\","
4063                                                                . "\"".$object[ 'birthdate' ] . "\","
4064                                                                . "\"".$object[ 'sex' ] . "\","
4065                                                                . "\"".$object[ 'pgp_key' ] . "\","
4066                                                                . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
4067                                                                . "\"".$object[ 'web_page' ] . "\","
4068                                                                . "\"".$object[ 'corporate_name' ] . "\","
4069                                                                . "\"".$object[ 'job_title' ] . "\","
4070                                                                . "\"".$object[ 'department' ] . "\","
4071                                                                . "\"".$object[ 'business-fax' ] . "\","
4072                                                                . "\"".$object[ 'business-pager' ] . "\","
4073                                                                . "\"".$object[ 'business-mobile' ] . "\","
4074                                                                . "\"".$object[ 'home-fax' ] . "\","
4075                                                                . "\"".$object[ 'home-pager' ] . "\","
4076                                                                . "\"".$object[ 'business-address-2' ] . "\","
4077                                                                . "\"".$object[ 'home-address-2' ] . "\"\r\n";
4078                            }
4079                        break;
4080
4081                        }
4082
4083                        $file = "contacts_".md5(microtime()).".swp";
4084                        $tempDir = ini_get("session.save_path");
4085                        $f = fopen($tempDir.'/'.$file,"w");
4086                        if(!$f)
4087                                echo null;
4088
4089                        fputs($f,$streamBuffer);
4090                        fclose($f);
4091
4092                        echo $tempDir.'/'.$file;
4093                }
4094
4095                // Get the csv field and put into array, from php.net
4096                function parse_line($input_text, $delimiter = ',', $text_qualifier = '"') {
4097                        $text = trim($input_text);
4098                          if(is_string($delimiter) && is_string($text_qualifier)) {
4099                         $re_d = '\x' . dechex(ord($delimiter));            //format for regexp
4100                        $re_tq = '\x' . dechex(ord($text_qualifier));    //format for regexp
4101
4102                        $fields = array();
4103                        $field_num = 0;
4104                        while(strlen($text) > 0) {
4105                        if($text{0} == $text_qualifier) {
4106                                preg_match('/^' . $re_tq . '((?:[^' . $re_tq . ']|(?<=\x5c)' . $re_tq . ')*)' . $re_tq . $re_d . '?(.*)$/', $text, $matches);
4107
4108                                $value = str_replace('\\' . $text_qualifier, $text_qualifier, $matches[1]);
4109                                $text = trim($matches[2]);
4110
4111                                $fields[$field_num++] = $value;
4112                        } else {
4113                                preg_match('/^([^' . $re_d . ']*)' . $re_d . '?(.*)$/', $text, $matches);
4114
4115                                $value = $matches[1];
4116                                $text = trim($matches[2]);
4117
4118                                $fields[$field_num++] = $value;
4119                }
4120                }
4121                        return $fields;
4122                    } else
4123                        return false;
4124                }
4125
4126                //funcao alterada para importar outros campos alem de nome, telefone e email, de arquivo csv (Outlook 2000)
4127                //em 08/04/2009 - Rommel Cysne (rommel.cysne@serpro.gov.br);
4128                //Foi adicionada uma funcao (escapesheelcmd()) nas variaveis para que caracteres especiais sejam ignorados
4129                //durante a importacao dos contatos; o processo estava travando por causa de caracteres em campos como nome,
4130                //sobrenome, notas e e-mail;
4131                //em 19/06/2009 - Rommel Cysne (rommel.cysne@serpro.gov.br);
4132                function import_contacts($typeImport){
4133                        $this->so_group = CreateObject('contactcenter.so_group');
4134                        if($file = $_SESSION['contactcenter']['importCSV']) {
4135                                unset($_SESSION['contactcenter']['importCSV']);
4136                                $len = filesize($file);
4137                                $count = 0;
4138                                $return = array('error' => false, '_new' => 0, '_existing' => 0, '_failure' => 0);
4139                                $handle = @fopen($file, "r") or die(serialize($return['error'] = true));
4140
4141                                $input_header = fgets($handle);
4142                                if ($typeImport == 'outlook')
4143                                        $delim = ';';
4144                                else if ($typeImport == 'auto')
4145                                $delim = strstr($input_header,',') ? ',' : ';';
4146                                else
4147                                        $delim = ',';
4148                                $csv_header = $this->parse_line($input_header,$delim);
4149                                $firstContact = fgets($handle);
4150                                preg_match("/\"(.+)\"[,;]/sU",$firstContact,$matches); // yahoo csv
4151                                rewind($handle);
4152
4153                                $header = @fgetcsv($handle, $len, $delim) or die(serialize($return['error'] = true));
4154                                if(count($header)  < 2 || count($header) > 100) {
4155                                        $return['error'] = true;
4156                                        $return['sizeheader'] = count($header);
4157                                        echo serialize($return);
4158                                        return;
4159                                }
4160
4161                                if ($matches[0][strlen($matches[0])-1] == ';')
4162                                        $delim = ';';
4163
4164                                $boGroup = CreateObject('contactcenter.bo_group');
4165                                $boPeople = CreateObject('contactcenter.bo_people_catalog');
4166                                        switch($typeImport){
4167                                                case 'outlook2000':
4168                                                        $name_pos=1;
4169                                                        $name2_pos=2;
4170                                                        $name3_pos=3;
4171                                                        $corporate_street_pos=8;
4172                                                        $cep_pos=13;
4173                                                        $corporate_street_2_pos=22;
4174                                                        $fax_pos=30;
4175                                                        $phone_pos=31;
4176                                                        $home_phone_pos=37;
4177                                                        $personal_cell_pos=40;
4178                                                        $pager_pos=43;
4179                                                        $birth_pos=48;
4180                                                        $notes_pos=49;
4181                                                        $email_pos=56;
4182                                                        $aditionalEmail_pos=59;
4183
4184                                                        break;
4185                                                case 'outlook':
4186                                                        $name_pos=3;
4187                                                        $email_pos=4;
4188                                                        $phone_pos=7;
4189                                                        $home_phone_pos=10;
4190                                                        $personal_cell_pos=12;
4191                                                        $corporate_street_pos=13;
4192                                                        $cep_pos=15;
4193                                                        $phone_pos=18;
4194                                                        $fax_pos=19;
4195                                                        $pager_pos=20;
4196                                                        $notes_pos=25;
4197                                                        break;
4198                                                case 'thunderbird':
4199                                                        $name_pos=2;
4200                                                        $email_pos=4;
4201                                                        $phone_pos=7;
4202                                                        break;
4203                                                case 'expresso':
4204                                                        $name_pos=0;
4205                                                        $alias_pos=1;
4206                                                        $email_pos=2;
4207                                                        $aditionalEmail_pos=3;
4208                                                        $personal_cell_pos=4;
4209                                                        $corporate_phone_pos=5;
4210                                                        $corporate_street_pos=6;
4211                                                        $corporate_comp_pos=7;
4212                                                        $corporate_cep_pos=8;
4213                                                        $corporate_city_pos=9;
4214                                                        $corporate_state_pos=10;
4215                                                        $corporate_country_pos=11;
4216                                                        $home_phone_pos=12;
4217                                                        $street_pos=13;
4218                                                        $comp_pos=14;
4219                                                        $cep_pos=15;
4220                                                        $city_pos=16;
4221                                                        $state_pos=17;
4222                                                        $country_pos=18;
4223                                                        $birth_pos=19;
4224                                                        $sex_pos = 20;
4225                                                        $pgp_key_pos = 21;
4226                                                        $notes_pos=22;
4227                                                        $web_page_pos=23;
4228                                                        $corporate_name_pos=24;
4229                                                        $job_title_pos=25;
4230                                                        $department_pos=26;
4231                                                        $corporate_fax_pos=27;
4232                                                        $corporate_pager_pos=28;
4233                                                        $corporate_cell_pos=29;
4234                                                        $fax_pos=30;
4235                                                        $pager_pos=31;
4236                                                        $corporate_street_2_pos = 32;
4237                                                        $street_2_pos = 33;                                             
4238                                                        break;
4239                                        default:
4240                                                        foreach($csv_header as $index => $fieldName)
4241                                                        {
4242                                                                switch($fieldName){
4243                                                                case 'Name':
4244                                                                case 'Nome':
4245                                                                case 'First Name':
4246                                                                        $name_pos = $index;
4247                                                                        break;
4248                                                                case 'Second name':
4249                                                                case 'Segundo nome':
4250                                                                        $name2_pos = $index;
4251                                                                        break;
4252                                                                case 'Sobrenome':
4253                                                                case 'Surname':
4254                                                                        $name3_pos = $index;
4255                                                                        break;
4256                                                                case 'Business Street':
4257                                                                case 'Rua do endereço comercial':
4258                                                                        $corporate_street_pos = $index;
4259                                                                        break;
4260                                                                case 'Rua do endereço comercial 2':
4261                                                                case 'Outro endereço':
4262                                                                        $corporate_street_2_pos = $index;
4263                                                                        break;
4264                                                                case 'Business Postal Code':
4265                                                                case 'CEP do endereço comercial':
4266                                                                        $cep_pos = $index;
4267                                                                        break;
4268                                                                case 'Business Fax':
4269                                                                case 'Fax comercial':
4270                                                                case 'Fax':
4271                                                                        $fax_pos = $index;
4272                                                                        break;
4273                                                                case 'Home Phone':
4274                                                                case 'Telefone residencial':
4275                                                                        $home_phone_pos = $index;
4276                                                                        break;
4277                                                                case 'Mobile phone':
4278                                                                case 'Telefone celular':
4279                                                                        $personal_cell_pos = $index;
4280                                                                        break;
4281                                                                case 'Pager':
4282                                                                        $pager_pos = $index;
4283                                                                        break;
4284                                                                case 'Phone':
4285                                                                case 'Business Phone':
4286                                                                case 'Telefone':
4287                                                                case 'Telefone principal':
4288                                                                case 'Telefone comercial':
4289                                                                case 'Telefone Comercial':
4290                                                                        $phone_pos = $index;
4291                                                                        break;
4292                                                                case 'Aniversário':
4293                                                                case 'Birthdate':
4294                                                                        $birth_pos = $index;
4295                                                                case 'Anotações':
4296                                                                case 'Notes':
4297                                                                        $notes_pos = $index;
4298                                                                case 'E-mail':
4299                                                                case 'Email':
4300                                                                case 'E-mail Address':
4301                                                                case 'Endereço de correio eletrônico':
4302                                                                case 'End. de email':
4303                                                                        $email_pos = $index;
4304                                                                        break;
4305                                                                case 'Endereço de correio eletrônico 2':
4306                                                                        $aditionalEmail_pos = $index;
4307                                                                        break;
4308                                                                }
4309                                                        }
4310                                                        break;
4311                                }
4312
4313                                while (($data = fgetcsv($handle, $len, $delim))) {
4314                                        foreach ($header as $key=>$heading)
4315                                $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
4316
4317                                                $sdata = array();
4318                                                $full_name  = trim($row[$header[$name_pos]]);
4319                                                $email          = trim($row[$header[$email_pos]]);
4320                                                $phone          = trim($row[$header[$phone_pos]]);
4321                                                $name2          = trim($row[$header[$name2_pos]]);
4322                                                $name3          = trim($row[$header[$name3_pos]]);
4323
4324                                                $birth          = trim($row[$header[$birth_pos]]);
4325                                                $notes          = trim($row[$header[$notes_pos]]);
4326                                                $altEmail       = trim($row[$header[$altEmail_pos]]);
4327                                                $sdata['alias']                         = trim($row[$header[$alias_pos]]);
4328                                                $sdata['corporate_name']      = trim($row[$header[$corporate_name_pos]]);
4329                                                $sdata['job_title']             = trim($row[$header[$job_title_pos]]);
4330                                                $sdata['department']            = trim($row[$header[$department_pos]]);
4331                                                $sdata['web_page']                      = trim($row[$header[$web_page_pos]]);
4332                                               
4333                                                $sdata['sex']                   = trim($row[$header[$sex_pos]]);
4334                                                $sdata['pgp_key']      = trim($row[$header[$pgp_key_pos]]);
4335
4336
4337                                        $full_name = $full_name;
4338                                        $array_name = explode(' ', str_replace('"','',(str_replace('\'','',$full_name))));
4339                                        $sdata['given_names'] = addslashes($array_name[0]);
4340                                        $array_name[0] = null;
4341                                        $sdata['family_names'] = trim(implode(' ',$array_name));
4342                                        if($sdata['family_names'] == '')
4343                                        {
4344                                                $sdata['family_names'] = addslashes($name2) . " " . addslashes($name3);
4345                                        }
4346
4347                                                $sdata['connections']['default_email']['connection_name'] = lang('Main');
4348                                                $sdata['connections']['default_email']['connection_value'] = addslashes($email);
4349                                                $sdata['connections']['aditional_email']['connection_name'] = "Alternativo";
4350                                                $sdata['connections']['aditional_email']['connection_value'] = trim($row[$header[$aditionalEmail_pos]]);
4351
4352                                                $sdata['connections']['default_phone']['connection_name'] = lang('Main');
4353                                       
4354                                                $sdata['connections']['default_phone']['connection_value'] = $phone;
4355
4356                                                if( trim($row[$header[$home_phone_pos]]) != "" )
4357                                                {
4358                                                    $sdata['connections']['aditional_phone']['home_phone']['connection_name'] = 'Casa';
4359                                                    $sdata['connections']['aditional_phone']['home_phone']['connection_value'] = trim($row[$header[$home_phone_pos]]);
4360                                                }
4361
4362                                                if( trim($row[$header[$personal_cell_pos]]) != "" )
4363                                                {
4364                                                    $sdata['connections']['aditional_phone']['cellphone']['connection_name'] = 'Celular';
4365                                                    $sdata['connections']['aditional_phone']['cellphone']['connection_value'] = trim($row[$header[$personal_cell_pos]]);
4366                                                }
4367
4368                                                if( trim($row[$header[$corporate_phone_pos]]) != "")
4369                                                {
4370                                                    $sdata['connections']['aditional_phone']['corporate_phone']['connection_name'] = 'Trabalho';
4371                                                    $sdata['connections']['aditional_phone']['corporate_phone']['connection_value'] = trim($row[$header[$corporate_phone_pos]]);
4372                                                }
4373
4374                                                if( trim($row[$header[$fax_pos]]) != "" )
4375                                                {
4376                                                    $sdata['connections']['aditional_phone']['fax']['connection_name'] = 'Fax';
4377                                                    $sdata['connections']['aditional_phone']['fax']['connection_value'] = trim($row[$header[$fax_pos]]);
4378                                                }
4379
4380                                                if ($GLOBALS['phpgw_info']['server']['personal_contact_type'] == 'True')
4381                                                {
4382                                                    if( trim($row[$header[$pager_pos]]) != "" )
4383                                                    {
4384                                                        $sdata['connections']['aditional_phone']['pager']['connection_name'] = 'Pager';
4385                                                        $sdata['connections']['aditional_phone']['pager']['connection_value'] = trim($row[$header[$pager_pos]]);
4386                                                    }
4387
4388                                                    if( trim($row[$header[$corporate_fax_pos]]) != "" )
4389                                                    {
4390                                                        $sdata['connections']['aditional_phone']['corporate_fax']['connection_name'] = 'Fax Corporativo';
4391                                                        $sdata['connections']['aditional_phone']['corporate_fax']['connection_value'] = trim($row[$header[$corporate_fax_pos]]);
4392                                                    }
4393
4394                                                    if( trim($row[$header[$corporate_cell_pos]]) != "" )
4395                                                    {
4396                                                        $sdata['connections']['aditional_phone']['corporate_cell']['connection_name'] = 'Celular Corporativo';
4397                                                        $sdata['connections']['aditional_phone']['corporate_cell']['connection_value'] = trim($row[$header[$corporate_cell_pos]]);
4398                                                    }
4399
4400                                                    if( trim($row[$header[$corporate_pager_pos]]) != "" )
4401                                                    {
4402                                                        $sdata['connections']['aditional_phone']['corporate_pager']['connection_name'] = 'Pager Corporativo';
4403                                                        $sdata['connections']['aditional_phone']['corporate_pager']['connection_value'] = trim($row[$header[$corporate_pager_pos]]);
4404                                                    }
4405                                                }
4406                                       
4407                                                $sdata['addresses']['address_corporative']['address1'] = trim($row[$header[$corporate_street_pos]]);
4408                                                $sdata['addresses']['address_corporative']['address2'] = trim($row[$header[$corporate_street_2_pos]]);
4409                                                $sdata['addresses']['address_corporative']['complement'] = trim($row[$header[$corporate_comp_pos]]);
4410                                                $sdata['addresses']['address_corporative']['postal_code'] = trim($row[$header[$corporate_cep_pos]]);                                           
4411                                                $sdata['addresses']['address_corporative']['id_country'] = "BR";
4412                                                $sdata['addresses']['address_corporative']['id_state'] = trim($row[$header[$corporate_state_pos]]);     
4413                                                $sdata['addresses']['address_corporative']['id_city'] = trim($row[$header[$corporate_city_pos]]);
4414                                               
4415                                                                                                       
4416                                                $sdata['addresses']['address_personal']['address1'] = trim($row[$header[$street_pos]]);
4417                                                $sdata['addresses']['address_personal']['address2'] = trim($row[$header[$street_2_pos]]);
4418                                                $sdata['addresses']['address_personal']['complement'] = trim($row[$header[$comp_pos]]);
4419                                                $sdata['addresses']['address_personal']['postal_code'] = trim($row[$header[$cep_pos]]);
4420                                                $sdata['addresses']['address_personal']['id_country'] = "BR";                                                   
4421                                                $sdata['addresses']['address_personal']['id_state'] = trim($row[$header[$state_pos]]); 
4422                                                $sdata['addresses']['address_personal']['id_city'] =  trim($row[$header[$city_pos]]);
4423
4424                                        if(trim($birth)) {
4425                                                $array_birth = explode("/",trim($birth));
4426                                                $sdata['birthdate'] = date('Y-m-d', mktime(0,0,0,$array_birth[1],$array_birth[0],$array_birth[2]));
4427                                        }
4428
4429                                        $sdata['notes'] = addslashes($notes);
4430                                        //$sdata['is_quick_add'] = true;
4431                                        $sdata['connections']['default_phone']['connection_value'] = $phone;
4432
4433                                        //      verifica se email já existe!
4434                                        $email = addslashes($email);
4435                                        $contact = $boGroup->verify_contact($email);
4436
4437                                        if(!$sdata['given_names'] && $email){
4438                                                        $a_email = explode("@",$email);
4439                                                        $sdata['given_names'] = addslashes($a_email[0]);
4440                                        }
4441
4442                                        $line_iteration = $return['_failure'] + $return['_existing'] + $return['_new'];
4443
4444                                        if($contact){
4445                                                $return['_existing']++;
4446                                        }
4447                                        else if((!eregi("^[/_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) && $email) {
4448                                                $return['_failure']++;
4449                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid E-Mail address: " . $email ."<br>";
4450                                        }
4451                                        else if (!$sdata['given_names'] || !$boPeople ->quick_add($sdata)){
4452                                                $return['_failure']++;
4453                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid Name: " . $sdata['given_names'] ."<br>";
4454                                        }
4455                                        else{   
4456                                                        if($id_group != 0){                                                             
4457                                                                $this->so_group->add_user_by_name($id_group,$full_name);
4458                                                        }                                               
4459                                                        $return['_new']++;
4460                                                }
4461                        }
4462                                fclose($handle);
4463                                unlink($file);
4464                        }
4465                        else
4466                                $return['error'] = true;
4467
4468                        echo serialize($return);
4469                }
4470       
4471                /*!
4472                 * @function get_contact_details
4473                 * @abstract Retorna os detalhes extras de um contato
4474                 * @author Luiz Carlos Viana Melo - Prognus
4475                 * @param (string) O ID do usuário do LDAP
4476                 */
4477                function get_contact_details($id)
4478                {
4479                        $data = array();
4480                       
4481                        if(!$this->bo->catalog->src_info) {
4482                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
4483                                $this->bo->catalog->src_info = $ldap->srcs[1];
4484                        }
4485                       
4486                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);                             
4487                        $dn=$this->bo->catalog->src_info['dn'];
4488                       
4489                        //buscar os atributos do ldap
4490                        $configobj = CreateObject('phpgwapi.config', 'contactcenter');
4491                        $prefs = $configobj->read_repository();
4492                        $attr_names = array();
4493                        $attr_types = array();
4494                        $justThese = array();
4495                        foreach ($prefs as $pref_key => $pref_value)
4496                        {
4497                                if (stripos($pref_key, "cc_attribute_name_") !== false)
4498                                {
4499                                        $num = substr($pref_key, strlen("cc_attribute_name_"));
4500                                        $attr_names[] = $prefs["cc_attribute_name_$num"];
4501                                        $attr_types[] = $prefs["cc_attribute_type_$num"];
4502                                        $justThese[] = strtolower($prefs["cc_attribute_ldapname_$num"]);
4503                                }
4504                        }
4505                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);                                                   
4506                        $info = ldap_get_entries($ds, $sr);
4507                        if ($info)
4508                        {
4509                                for ($i = 0; $i < count($justThese); $i++)
4510                                {
4511                                        $attr = array();
4512                                        $attr['name'] = $attr_names[$i];
4513                                        if ($attr_types[$i] == 'multivalues')
4514                                        {
4515                                                $attr['type'] = 'multivalues';
4516                                                $attr['value'] = array();
4517                                                for ($j = 0; $j < $info[0][$justThese[$i]]['count']; $j++)
4518                                                        $attr['value'][] = utf8_decode($info[0][$justThese[$i]][$j]);
4519                                        }
4520                                        else
4521                                        {
4522                                                $attr['type'] = 'text';
4523                                                $attr['value'] = utf8_decode($info[0][$justThese[$i]][0]);
4524                                        }
4525                                        $data[] = $attr;
4526                                }
4527                        }
4528                        else
4529                                $data = 'error';
4530                        ldap_close($ds);
4531                       
4532                        echo serialize($data);
4533                }
4534        }
4535
4536?>
Note: See TracBrowser for help on using the repository browser.