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

Revision 3660, 133.3 KB checked in by eduardoalex, 13 years ago (diff)

Ticket #1429 - Corrigindo erro gerado pela revisão 3322.

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