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

Revision 4544, 151.6 KB checked in by airton, 13 years ago (diff)

Ticket #1954 - Implementação de busca avançada no contactcenter

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