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

Revision 4548, 150.8 KB checked in by airton, 13 years ago (diff)

Ticket #1954 - Implementacao de busca avançada no contactcenter - Padronizacao da tela de busca avancada

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