source: branches/2.2/contactcenter/inc/class.ui_data.inc.php @ 4076

Revision 4076, 133.5 KB checked in by niltonneto, 13 years ago (diff)

Ticket #1780 - Corrigido problema da data de nascimento ao importar arquivo CSV.

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