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

Revision 4754, 145.2 KB checked in by roberto.santosjunior, 13 years ago (diff)

Ticket #1820 - Incluir Contato Compartilhado duplicado. r4599

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