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

Revision 4483, 143.4 KB checked in by airton, 13 years ago (diff)

Ticket #1913 - Copia de um contato do Catalogo Global para o pessoal contem erros de codificacao

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