source: trunk/contactcenter/inc/class.ui_data.inc.php @ 4717

Revision 4717, 151.0 KB checked in by airton, 13 years ago (diff)

Ticket #2113 - Falha na criacao de um contato compartilhado

  • 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 'groups':
2756                            $groups = $data['groups'];
2757                            unset($data['groups']);
2758                            break;
2759                                        case 'names_ordered':
2760                                        case 'pgp_key':
2761                                        case 'notes':
2762                                        case 'photo':
2763                                                $data[$field] = urldecode( $value );
2764                                                break;
2765
2766                                        case 'id_status':
2767                                        case 'id_prefix':
2768                                        case 'id_suffix':
2769                                                if ($data[$field] == 0)
2770                                                {
2771                                                        unset($data[$field]);
2772                                                }
2773                                                break;
2774
2775                                        case 'birthdate_0':
2776                                        case 'birthdate_1':
2777                                        case 'birthdate_2':
2778
2779                                                switch($date[$datecount]['digit'])
2780                                                {
2781                                                        case 'Y':
2782                                                                $date['value'][2] = (int) $data[$field];
2783                                                                break;
2784
2785                                                        case 'M':
2786                                                                $date['value'][0] = (int) $data[$field];
2787                                                                break;
2788
2789                                                        case 'D':
2790                                                                $date['value'][1] = (int) $data[$field];
2791                                                                break;
2792                                                }
2793                                                unset($data[$field]);
2794                                                $datecount++;
2795
2796                                                if ($datecount != 3)
2797                                                {
2798                                                        break;
2799                                                }
2800
2801                                                if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
2802                                                {
2803                                                        echo serialize(array(
2804                                                                'msg' => lang('Invalid Date'),
2805                                                                'status' => 'invalid_data'
2806                                                        ));
2807                                                        return;
2808                                                }
2809
2810                                                $data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
2811                                                break;
2812
2813                                        case 'sex':
2814                                                if ($data[$field] !== 'M' and $data[$field] !== 'F')
2815                                                {
2816                                                        echo serialize(array(
2817                                                                'msg' => lang('Invalid Sex'),
2818                                                                'status' => 'invalid_data'
2819                                                        ));
2820                                                        return;
2821                                                }
2822                                                break;
2823
2824
2825                                        case 'addresses':
2826                                                /* Insert new cities/states */
2827                                                if (isset($value['new_states']))
2828                                                {
2829                                                        foreach($value['new_states'] as $type => $state_info)
2830                                                        {
2831                                                                $index = 'address'.$type;
2832
2833                                                                $id_state = $this->bo->catalog->add_state($state_info);
2834                                                                $data['addresses'][$index]['id_state'] = $id_state;
2835
2836                                                                if ($value['new_cities'][$type])
2837                                                                {
2838                                                                        $value['new_cities'][$type]['id_state'] = $id_state;
2839                                                                }
2840                                                        }
2841
2842                                                        unset($data['addresses']['new_states']);
2843                                                }
2844
2845                                                if (isset($value['new_cities']))
2846                                                {
2847                                                        foreach($value['new_cities'] as $type => $city_info)
2848                                                        {
2849                                                                $index = 'address'.$type;
2850
2851                                                                $id_city = $this->bo->catalog->add_city($city_info);
2852                                                                $data['addresses'][$index]['id_city'] = $id_city;
2853                                                        }
2854
2855                                                        unset($data['addresses']['new_cities']);
2856                                                }
2857
2858                                        break;
2859
2860                                        case 'connections':
2861                                                /* Does nothing... */
2862                                                break;
2863
2864                                        default:
2865                                                echo serialize(array(
2866                                                        'msg' => lang('Invalid field: ').$field,
2867                                                        'status' => 'invalid_data'
2868                                                ));
2869                                                return;
2870                                }
2871                        }
2872
2873                        $code = '$id = $this->bo->catalog->';
2874
2875                        if (!is_null($id) and $id !== '')
2876                        {
2877                                $code .= $code.'update_single_info($id, $data);';
2878                                $result = array(
2879                                        'msg' => lang('Updated Successfully!'),
2880                                        'status' => 'ok'
2881                                );
2882                        }
2883                        else
2884                        {
2885                                $code .= 'add_single_entry($data,'.$owner.');';
2886                                $result = array(
2887                                        'msg' => lang('Entry Added Successfully!'),
2888                                        'status' => 'ok'
2889                                );
2890                        }
2891
2892                        eval($code);
2893
2894                        if (!($id))
2895                        {
2896                                $result = array(
2897                                        'msg' => lang('Some problem occured when trying to insert/update contact information.<br>'.
2898                                                   'Report the problem to the Administrator.'),
2899                                        'status' => 'fail'
2900                                );
2901                        }
2902
2903                        echo serialize($result);
2904}
2905                /*!
2906
2907                        @function post_photo
2908                        @abstract Wrapper to post a photo without reload a page.
2909                        @author Raphael Derosso Pereira
2910
2911                */
2912                function post_photo($id)
2913                {
2914                        //print_r($_FILES);
2915                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'y'));
2916
2917                        if (!is_array($_FILES) and is_array(!$_FILES['cc_pd_photo']))
2918                        {
2919                                $this->page_info['photos'][$id]['status'] = 'no_upload';
2920                                $this->page_info['photos'][$id]['msg'] = lang('No Photos uploaded to Server.');
2921
2922                                $this->save_session();
2923                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2924                                return;
2925                        }
2926
2927                        if (!function_exists('imagecreate'))
2928                        {
2929                                $this->page_info['photos'][$id]['status'] = 'no_GD_lib';
2930                                $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.');
2931
2932                                $this->save_session();
2933                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2934                                return;
2935                        }
2936
2937                        // TODO: Get Max Size from preferences!
2938                        if ($_FILES['cc_pd_photo']['size'] > 1000000)
2939                        {
2940                                $this->page_info['photos'][$id]['status'] = 'too_large';
2941                                $this->page_info['photos'][$id]['msg'] = lang('Image too large! ContactCenter limits the image size to 1 Mb');
2942
2943                                $this->save_session();
2944                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2945                                return;
2946                        }
2947
2948                        if ($_FILES['cc_pd_photo']['error'])
2949                        {
2950                                $this->page_info['photos'][$id]['status'] = 'error';
2951                                $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'];
2952
2953                                $this->save_session();
2954                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2955                                return;
2956                        }
2957
2958                        switch($_FILES['cc_pd_photo']['type'])
2959                        {
2960                                case 'image/jpeg':
2961                                case 'image/pjpeg':
2962                                        $src_img = imagecreatefromjpeg($_FILES['cc_pd_photo']['tmp_name']);
2963                                        if ($src_img == '')
2964                                        {
2965                                                $bogus = true;
2966                                        }
2967                                        break;
2968
2969                                case 'image/png':
2970                                case 'image/x-png':
2971                                        $src_img = imagecreatefrompng($_FILES['cc_pd_photo']['tmp_name']);
2972                                        if ($src_img == '')
2973                                        {
2974                                                $bogus = true;
2975                                        }
2976                                        break;
2977
2978                                case 'image/gif':
2979                                        $src_img = imagecreatefromgif($_FILES['cc_pd_photo']['tmp_name']);
2980                                        if ($src_img == '')
2981                                        {
2982                                                $bogus = true;
2983                                        }
2984                                        break;
2985
2986                                default:
2987
2988                                        $this->page_info['photos'][$id]['status'] = 'invalid_image';
2989                                        $this->page_info['photos'][$id]['msg'] = lang('The file must be an JPEG, PNG or GIF Image.');
2990
2991                                        $this->save_session();
2992                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2993                                        return;
2994                        }
2995
2996                        if ($bogus)
2997                        {
2998                                        $this->page_info['photos'][$id]['status'] = 'invalid_file';
2999                                        $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
3000
3001                                        $this->save_session();
3002                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
3003                                        return;
3004                        }
3005
3006                        $img_size = getimagesize($_FILES['cc_pd_photo']['tmp_name']);
3007                        $dst_img = imagecreatetruecolor(60, 80);
3008
3009                        if (!imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, 60, 80, $img_size[0], $img_size[1]))
3010                        {
3011                                $this->page_info['photos'][$id]['status'] = 'invalid_file';
3012                                $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
3013
3014                                $this->save_session();
3015                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
3016                                return;
3017                        }
3018
3019                        ob_start();
3020                        imagepng($dst_img);
3021                        $this->page_info['photos'][$id]['content'] = ob_get_contents();
3022                        ob_end_clean();
3023
3024                        $this->page_info['photos'][$id]['status'] = 'changed';
3025                        $this->page_info['photos'][$id]['msg'] = lang('Photo Successfully Updated!');
3026
3027                        $this->save_session();
3028
3029                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
3030
3031                        imagedestroy($src_img);
3032                        imagedestroy($dst_img);
3033                        echo 'ok';
3034                        return;
3035                }
3036
3037
3038                /*!
3039
3040                        @function get_photo
3041                        @abstract Returns the photo to the browser
3042                        @author Raphael Derosso Pereira
3043
3044                */
3045                function get_photo($id)
3046                {
3047                        $fields = $this->bo->catalog->get_fields(false);
3048                        $fields['photo'] = true;
3049
3050                        $contact = $this->bo->catalog->get_single_entry($id, $fields);
3051
3052                        if (!$contact['photo'])
3053                        {
3054                                header('Content-type: image/png');
3055                                echo file_get_contents(PHPGW_INCLUDE_ROOT.'/contactcenter/templates/default/images/photo_celepar.png');
3056                                return;
3057                        }
3058
3059                        header('Content-type: image/jpeg');
3060
3061                        $tmpDir = $GLOBALS['phpgw_info']['server']['temp_dir'];
3062                        $imagem_temp = fopen("$tmpDir/img_tmp","wb+");
3063                        fwrite($imagem_temp,$contact['photo']);
3064                        fclose($imagem_temp);                   
3065                        $exif = exif_read_data("$tmpDir/img_tmp","IDF0");
3066                        $ort = 1;
3067                        if ($exif['Orientation'] != '') {
3068                                $ort = $exif['Orientation'];
3069                        }
3070                        unlink("$tmpDir/img_tmp");                     
3071
3072                        $photo = imagecreatefromstring ($contact['photo']);
3073                        $width = imagesx($photo);
3074                        $height = imagesy($photo);
3075                        $twidth = 70;
3076                        $theight = 90;
3077                        $small_photo = imagecreatetruecolor ($twidth, $theight);
3078                        imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
3079                       
3080                        if ($ort != 1){
3081                                switch($ort)
3082                                {
3083                                        case 3:
3084                                                $rotate = imagerotate($small_photo, 180, 0);
3085                                                break;
3086                                        case 6:
3087                                                $rotate = imagerotate($small_photo, 270, 0);
3088                                                break;
3089                                        case 8:
3090                                                $rotate = imagerotate($small_photo, 90, 0);
3091                                                break;
3092                                }
3093                        } else $rotate = imagerotate($small_photo, 0, 0);
3094       
3095                        imagejpeg($rotate,"",100);
3096                        ImageDestroy($rotate);
3097                        ImageDestroy($small_photo);
3098
3099                        return;
3100                }
3101
3102                /*!
3103
3104                        @function get_states
3105                        @abstract Echos a serialized array containing all the states for the given country
3106                        @author Raphael Derosso Pereira
3107
3108                        @params $id_country The ID of the Country that contains the requested states
3109
3110                */
3111                function get_states($id_country)
3112                {
3113                        $states = $this->bo->catalog->get_all_states($id_country);
3114
3115                        if (!$states)
3116                        {
3117                                $result = array(
3118                                        'msg'    => lang('No States found for this Country.'),
3119                                        'status' => 'empty'
3120                                );
3121
3122                                echo serialize($result);
3123                                return;
3124                        }
3125
3126                        $result = array(
3127                                'msg'    => lang('States Successfully retrieved!'),
3128                                'status' => 'ok'
3129                        );
3130
3131                        foreach ($states as $state_info)
3132                        {
3133                                $result['data'][$state_info['id_state']] = $state_info['name'];
3134
3135                                if ($state_info['symbol'])
3136                                {
3137                                        $result['data'][$state_info['id_state']] .= ', '.$state_info['symbol'];
3138                                }
3139                        }
3140
3141                        echo serialize($result);
3142                }
3143
3144                /*!
3145
3146                        @function get_cities
3147                        @abstract Echos a serialized array containing all the cities of a given state
3148                        @author Raphael Derosso Pereira
3149
3150                        @param $id_country The ID of the Country that has the specified Cities (in case the
3151                                Country doesn't have any States)
3152                        @param $id_state The ID of the State that has the Cities requested
3153
3154                */
3155                function get_cities($id_country, $id_state=false)
3156                {
3157                        $cities = $this->bo->catalog->get_all_cities($id_country, $id_state);
3158
3159                        if (!$cities)
3160                        {
3161                                $result = array(
3162                                        'msg'    => lang('No Cities found for this State.'),
3163                                        'status' => 'empty'
3164                                );
3165
3166                                echo serialize($result);
3167                                return;
3168                        }
3169
3170                        $result = array(
3171                                'msg'    => lang('Cities Successfully retrieved!'),
3172                                'status' => 'ok'
3173                        );
3174
3175                        foreach ($cities as $city_info)
3176                        {
3177                                $result['data'][$city_info['id_city']] = $city_info['name'];
3178                        }
3179
3180                        echo serialize($result);
3181                }
3182
3183                //Traduz o campo na busca completa por entradas no catálogo do usuário.
3184                function aux_full_search ($field,$isldap) {
3185                        $retorno = '';
3186                        if($isldap) {
3187                                switch($field) {
3188                                        case 'mail':
3189                                                $retorno = 'contact.connection.mail';
3190                                                break;
3191                                        case 'phone':
3192                                                $retorno = 'contact.connection.phone';
3193                                                break;
3194                                }
3195                        }
3196                        else {
3197                                switch($field) {
3198                                        case 'corporate':
3199                                                $retorno = 'contact.corporate_name';
3200                                                break;
3201                                        case 'mail':
3202                                        case 'phone':
3203                                                $retorno = 'contact.contact_connection.connection.connection_value';
3204                                                break;
3205                                }
3206                        }
3207                        return $retorno;
3208                }
3209
3210                /*!
3211
3212                        @function search
3213                        @abstract Echos a serialized array containing the IDs
3214                                of the entries that matches the search argument
3215                        @author Raphael Derosso Pereira
3216                        @author Mário César Kolling (external catalogs)
3217
3218                        @param string $str_data A serialized array with two informations:
3219                                $data = array(
3220                                        'search_for' => (string),
3221                                        'recursive'  => (boolean),
3222                                );
3223
3224                */
3225                // SERPRO
3226                function search($str_data)
3227                {
3228                        $data = unserialize($str_data);
3229                        // It's an external catalog?
3230                        $external = $this->bo->is_external($this->page_info['actual_catalog']);
3231                        $full_search = isset($data['full_search'])?$data['full_search']:false;
3232                       
3233                        if (!is_array($data) || (!$data['search_for'] && !$full_search) || !is_array($data['fields']))
3234                        {
3235                            echo serialize(array(
3236                                    'msg'    => lang('Invalid parameters'),
3237                                    'status' => 'abort'
3238                            ));
3239
3240                            return array('error' => lang('Invalid parameters'));
3241                        }
3242
3243
3244                        /*
3245                         * TODO: look into the database to discover the database's encoding and convert the search_for field accordingly
3246                         */
3247                        // Support search parameters with accentuation
3248                        if ($this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
3249/**rev 104**/
3250                                //$this->page_info['actual_catalog']['class'] != 'bo_group_manager')
3251                                $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
3252                                $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
3253                                $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
3254/****/
3255                        {
3256
3257                                $data['search_for'] = ($data['search_for']);
3258                        }
3259
3260                        $rules  = array();
3261
3262                        if ($data['search_for'] === '*')
3263                        {
3264                                $rules = array(
3265                                        0 => array(
3266                                                'field' => $data['fields']['search'],
3267                                                'type'  => 'LIKE',
3268                                                'value' => '%'
3269                                        )
3270                                );
3271                        }
3272                        else
3273                        {
3274                            $names = explode(' ', $data['search_for']);
3275
3276                            if (!is_array($names))
3277                            {
3278                                    if(!$full_search) {
3279                                            echo serialize(array(
3280                                                    'msg'    => lang('Invalid Search Parameter'),
3281                                                    'status' => 'abort'
3282                                            ));
3283                                            exit;
3284                                    }
3285                                    else
3286                                            $names = array();
3287
3288                            }
3289
3290                                if (!$external && $this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
3291/**rev 104**/
3292                                        //$this->page_info['actual_catalog']['class'] != 'bo_group_manager')
3293                                        $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
3294                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
3295                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager' )
3296/*****/
3297                                {
3298                                        /*
3299                                         * Restrict the returned contacts search to objectClass = phpgwAccount,
3300                                         * must have attibute phpgwAccountStatus, phpgwAccountVisible != -1
3301                                         */
3302                                       
3303                                        $rules = array(
3304                                                0 => array(
3305                                                        'field' => 'contact.object_class',
3306                                                        'type'  => '=',
3307                                                        'value' => 'phpgwAccount'
3308                                                ),
3309                                                1 => array(
3310                                                        'field' => 'contact.account_status',
3311                                                        'type'  => 'iLIKE',
3312                                                        'value' => '%'
3313                                                ),
3314/**rev 104**/
3315                                                ///
3316                                                //1 => array(
3317                                                2 => array(
3318/*****/
3319                                                        'field' => 'contact.account_visible',
3320                                                        'type'  => '!=',
3321                                                        'value' => '-1'
3322/**rev 104**/
3323        /*                                      ),
3324                                                2 => array(
3325                                                        'field' => 'contact.object_class',
3326                                                        'type'  => '=',
3327                                                        'value' => 'inetOrgPerson'
3328/****/
3329                                                ),
3330                                        );
3331
3332                                        if($full_search) {
3333                                                foreach($full_search as $field => $value) {
3334                                                        if(trim($value)!='')
3335                                                                array_push($rules,array(
3336                                                                                                'field' => $this->aux_full_search($field,true),
3337                                                                                                'type' => 'LIKE',
3338                                                                                                'value' => '*'.$value.'*'
3339                                                                                                ));
3340                                                }
3341                                        }
3342
3343                                }
3344                                else if(!$external && $full_search) {
3345                                       
3346                                        foreach($full_search as $field => $value) {
3347                                                if(trim($value)!='')
3348                                                        array_push($rules,array(
3349                                                                                        'field' => $this->aux_full_search($field,false),
3350                                                                                        'type'  => 'LIKE and ~=',
3351                                                                                        'value' => $name
3352                                                                                        ));
3353                                                }
3354                               
3355                                }
3356
3357                                foreach ($names as $name)
3358                                {
3359                                        if ($name != '')
3360                                        {
3361                                                array_push($rules, array(
3362                                                        'field' => $data['fields']['search'],
3363                                                        'type'  => 'LIKE and ~=',
3364                                                        'value' => $name
3365                                                ));
3366                                        }
3367                                }
3368                        }
3369
3370                        if ($external || $this->page_info['actual_catalog']['class'] == 'bo_people_catalog' ||
3371/**rev 104**/
3372                                //$this->page_info['actual_catalog']['class'] == 'bo_group_manager')
3373                                $this->page_info['actual_catalog']['class'] == 'bo_group_manager' ||
3374                                $this->page_info['actual_catalog']['class'] == 'bo_shared_people_manager' ||
3375                                $this->page_info['actual_catalog']['class'] == 'bo_shared_group_manager')
3376
3377
3378/***/
3379                        {
3380                                // Get only this attributes: dn, cn for external catalogs,
3381                                // used to restrict the attributes used in filters
3382                                $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);
3383                        }
3384                        else
3385                        {
3386                                // Get only this attributes: dn, cn, phpgwAccountType, objectClass, phpgwAccountStatus, phpghAccountVisible
3387                                // for non-external catalogs, used to restrict the attributes used in filters
3388                                $ids = $this->bo->find(array(
3389                                        $data['fields']['id'],
3390                                        $data['fields']['search'],
3391                                        'contact.object_class',
3392                                        //'contact.account_status',
3393                                        'contact.account_visible',
3394                                        'contact.connection.mail',
3395                                        'contact.connection.phone'
3396                                        ), $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 );
3397                        }
3398
3399                        if (!is_array($ids) || !count($ids))
3400                        {
3401                                $this->last_search_ids = null;
3402                                $this->save_session();
3403                                return null;
3404                        }
3405
3406                        $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
3407
3408                        $ids_f = array();
3409
3410                        foreach ($ids as $e_info)
3411                        {
3412/**rev 104**/
3413                                //$ids_f[] = $e_info[$id_field];
3414                                if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
3415                                {
3416                                        $ids_f[] = $e_info[$id_field];
3417                                } else{
3418                                        $ids_f[] = array(0=>$e_info[$id_field],1=>$e_info['perms'],2=>$e_info['owner']);
3419                                }
3420/****/
3421                        }
3422
3423                        return $ids_f;
3424                }
3425
3426                // CELEPAR
3427                /*
3428        function search($str_data)
3429        {
3430            $data = unserialize($str_data);
3431
3432            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
3433            {
3434                echo serialize(array(
3435                    'msg'    => lang('Invalid parameters'),
3436                    'status' => 'abort'
3437                ));
3438
3439                return;
3440            }
3441
3442            $rules  = array();
3443
3444            if ($data['search_for'] === '*')
3445            {
3446                $rules = array(
3447                    0 => array(
3448                        'field' => $data['fields']['search'],
3449                        'type'  => 'LIKE',
3450                        'value' => '%'
3451                    )
3452                );
3453            }
3454            else
3455            {
3456                $names = explode(' ', $data['search_for']);
3457
3458                if (!is_array($names))
3459                {
3460                    echo serialize(array(
3461                        'msg'    => lang('Invalid Search Parameter'),
3462                        'status' => 'abort'
3463                    ));
3464
3465                    return;
3466                }
3467
3468                foreach ($names as $name)
3469                {
3470                    if ($name != '')
3471                    {
3472                        array_push($rules, array(
3473                            'field' => $data['fields']['search'],
3474                            'type'  => 'iLIKE',
3475                            'value' => '%'.$name.'%'
3476                        ));
3477                    }
3478                }
3479            }
3480
3481
3482
3483            //$catalog = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
3484
3485            //if ($catalog['class'] === 'bo_people_catalog')
3486            //{
3487            //    array_push($rules, array(
3488            //        'field' => 'contact.id_owner',
3489            //        'type'  => '=',
3490            //        'value' => $GLOBALS['phpgw_info']['user']['account_id']
3491            //    ));
3492            //}
3493
3494
3495            $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
3496
3497            if (!is_array($ids) || !count($ids))
3498            {
3499                echo serialize(array(
3500                    'msg'    => lang('No Entries Found!'),
3501                    'status' => 'empty'
3502                ));
3503
3504                return;
3505            }
3506            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
3507
3508            $ids_f = array();
3509            foreach ($ids as $e_info)
3510            {
3511                $ids_f[] = $e_info[$id_field];
3512            }
3513
3514            echo serialize(array(
3515                'data'   => $ids_f,
3516                'msg'    => lang('Found %1 Entries', count($ids)),
3517                'status' => 'ok'
3518            ));
3519
3520                        return;
3521        }*/
3522                /*!
3523
3524                        @function get_multiple_entries
3525                        @abstract Returns an array containing the specifiend data in the default
3526                                CC UI format
3527                        @author Raphael Derosso Pereira
3528
3529                        @param array str_data A serialized array containing the ID's of the entries
3530                                to be taken, the fields to be taken and the rules to be used on the
3531                                retrieval:
3532                                $data = array(
3533                                        'ids'    => array(...),
3534                                        'fields' => array(...),
3535                                        'rules'  => array(...)
3536                                );
3537
3538                */
3539                function get_multiple_entries($str_data)
3540                {
3541                        $data = unserialize($str_data);
3542
3543                        if (!is_array($data) or !count($data) or !count($data['fields']) or !count($data['ids']))
3544                        {
3545                                return array(
3546                                        'msg'    => lang('Invalid Parameters'),
3547                                        'status' => 'abort'
3548                                );
3549                        }
3550
3551                        $entries = $this->bo->catalog->get_multiple_entries($data['ids'], $data['fields']);
3552
3553                        if (!is_array($entries) or !count($entries))
3554                        {
3555                                return array(
3556                                        'msg'    => lang('No Entries Found!'),
3557                                        'status' => 'empty'
3558                                );
3559                        }
3560
3561                        return array(
3562                                'msg'    => lang('Found %1 Entries!', count($entries)),
3563                                'status' => 'ok',
3564                                'data'   => $entries
3565                        );
3566                }
3567
3568                /*
3569
3570                        @function get_all_entries
3571                        @abstract Returns the specified fields for all catalog's entries
3572                                in the default CC UI format
3573                        @author Raphael Derosso Pereira
3574
3575                        @params array str_data A serialized array containing the fields to
3576                                be grabbed, the maximum number of entries to be returned and a
3577                                boolean specifying if the calls refers to a new grab or to an
3578                                unfinished one.
3579
3580                */
3581                function get_all_entries($str_data)
3582                {
3583                        $data = unserialize($str_data);
3584
3585                        if (!is_array($data) or
3586                            !count($data) or
3587                                !count($data['fields']) or
3588                                !$data['maxlength'] or
3589                                (!$data['new'] and !$data['offset']))
3590                        {
3591                                return array(
3592                                        'msg'    => lang('Invalid Parameters'),
3593                                        'status' => 'abort'
3594                                );
3595                        }
3596
3597                        if ($data['new'])
3598                        {
3599                                $this->all_entries = $this->bo->catalog->get_all_entries_ids();
3600
3601                                $this->save_session();
3602
3603                                if (!is_array($this->all_entries) or !count($this->all_entries))
3604                                {
3605                                        return array(
3606                                                'msg'    => lang('No Entries Found!'),
3607                                                'status' => 'empty'
3608                                        );
3609                                }
3610
3611                                $data['offset'] = 0;
3612                        }
3613
3614                        if ($data['maxlength'] != -1)
3615                        {
3616                                $result = $this->bo->catalog->get_multiple_entries(array_slice($this->all_entries, $data['offset'], $data['maxlength']), $data['fields']);
3617                        }
3618                        else
3619                        {
3620                                $result = $this->bo->catalog->get_multiple_entries($this->all_entries, $data['fields']);
3621                        }
3622
3623                        $jsCode = array();
3624                        $count = 0;
3625                        foreach ($result as $each)
3626                        {
3627                                if (!is_array($each))
3628                                {
3629                                        continue;
3630                                }
3631
3632                                if($this-> typeContact == 'groups') {
3633
3634                                        foreach ($each as $field => $value)     {
3635
3636                                                if ($field === 'title') {
3637                                                        $optionName = '\\"'.$value.'\\"';
3638
3639                                                }
3640                                                else if ($field === 'short_name')       {
3641
3642                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$optionName.' ('.$value.')", "'.$count.'");';
3643                                                        $count++;
3644                                                }
3645                                        }
3646                                }
3647
3648                                else  {
3649                                        foreach ($each as $field => $value)     {
3650                                                if ($field === 'names_ordered') {
3651                                                         if(is_array($value))
3652                                $value = $value[0];
3653                                                        $name = '\\"'.$value.'\\"';
3654                                                }
3655                                                else if ($field === 'connections')      {
3656
3657                                                        foreach ($value as $connection)         {
3658                                                                if ($connection['id_type'] == $this->preferences['personCardEmail'])    {
3659                                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$name.' <'.$connection['connection_value'].'>", "'.$count.'");';
3660                                                                        $count++;
3661                                                                }
3662                                                        }
3663                                                }
3664                                        }
3665                                }
3666                        }
3667
3668                        $jsCodeFinal = implode("\n", $jsCode);
3669
3670                        $nEntries = count($result);
3671
3672                        if (!$nEntries)
3673                        {
3674                                return array(
3675                                        'msg'    => lang('Error while getting user information...'),
3676                                        'status' => 'abort'
3677                                );
3678                        }
3679
3680                        return array(
3681                                'msg'      => lang('Found %1 Entries!', $nEntries),
3682                                'status'   => 'ok',
3683                                'typeContact'   => $this -> typeContact,
3684                                'final'    => $nEntries + $data['offset'] < count($this->all_entries) ? false : true,
3685                                'offset'   => $data['offset'] + $nEntries,
3686                                'data'     => $jsCodeFinal
3687                        );
3688                }
3689
3690                /*********************************************************************\
3691                 *                      Auxiliar Methods                             *
3692                \*********************************************************************/
3693
3694                /*!
3695
3696                        @function save_session
3697                        @abstract Saves the data on the session
3698                        @author Raphael Derosso Pereira
3699
3700                */
3701                function save_session()
3702                {
3703                        $GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter',$this->page_info);
3704                        $GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter',$this->all_entries);
3705                }
3706
3707                /*!
3708
3709                        @function convert_tree
3710                        @abstract Converts the tree array in the BO format to a JS tree array compatible
3711                                with the one available in eGW
3712                        @author Raphael Derosso Pereira
3713
3714                        @param (array)  $tree    The tree in the BO format
3715                        @param (string) $name    The tree name
3716                        @param (string) $iconDir The dir where the icons are
3717                        @param (string) $parent  The parent
3718                */
3719
3720                function convert_tree($tree, &$iconDir, $parent='0')
3721                {
3722//                      echo "Entrou<br>\tPai: $parent <br>";
3723                        $rtree = array();
3724
3725                        if ($parent === '0')
3726                        {
3727//                              echo 'Root!<br>';
3728                                $rtree['0'] = array(
3729                                        'type'       => 'catalog_group',
3730                                        'id'         => '0',
3731                                        'pid'        => 'none',
3732                                        'caption'    => lang('Catalogues'),
3733                                        'class'      => 'bo_catalog_group_catalog',
3734                                        'class_args' => array('_ROOT_', '$this', '$this->get_branch_by_level($this->catalog_level[0])')
3735                                );
3736                        }
3737
3738                        foreach($tree as $id => $value)
3739                        {
3740//                              echo 'ID: '.$id.'<br>';
3741                                $rtree[$parent.'.'.$id] = array(
3742                                        'type'    => $value['type'],
3743                                        'id'      => $parent.'.'.$id,
3744                                        'pid'     => $parent,
3745                                        'caption' => $value['name']
3746                                );
3747
3748                                switch($value['type'])
3749                                {
3750                                        case 'catalog_group':
3751                                        case 'mixed_catalog_group':
3752                                                $rtree = $rtree + $this->convert_tree($value['sub_branch'],$iconDir,$parent.'.'.$id);
3753                                                break;
3754                                }
3755                        }
3756
3757                        if (count($rtree))
3758                        {
3759                                return $rtree;
3760                        }
3761                }
3762
3763                function get_catalog_add_contact($id, $echo=true){
3764
3765                        $array_participants = array();
3766                        if(!$this->bo->catalog->src_info) {
3767                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3768                                $this->bo->catalog->src_info = $ldap->srcs[1];
3769                        }
3770
3771                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3772                        $dn=$this->bo->catalog->src_info['dn'];
3773                        $justThese = array("givenname","givenname","sn","telephonenumber","mail");
3774                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);
3775                        $info = ldap_get_entries($ds, $sr);
3776                        for($z = 0; $z < 5; $z++) {
3777                                $participant = $info[0][$justThese[$z]];
3778                                $participant[0] = utf8_decode($participant[0]);
3779                                array_push($array_participants, $participant);
3780                        }
3781
3782                        ldap_close($ds);
3783                        if ($echo)
3784                        {
3785                            echo serialize($array_participants);
3786                        }
3787                        else
3788                            {
3789                                return serialize($array_participants);
3790                            }
3791                }
3792
3793                function get_catalog_participants_group($id)
3794                {
3795                        if(!$this->bo->catalog->src_info) {
3796                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
3797                                $this->bo->catalog->src_info = $ldap->srcs[1];
3798                        }
3799                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3800                        $justThese = array("description","memberuid");
3801                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);
3802                        $info = ldap_get_entries($ds, $sr);
3803                        $member_uids = $info[0]['memberuid'];
3804                        $contact['names_ordered'] = $info[0]['description'];
3805                        $filter = "";
3806                        for($z = 0; $z < count($member_uids); $z++) {
3807                                if($member_uids[$z])
3808                                        $filter.="(uid=".$member_uids[$z].")";
3809                        }
3810                        $array_participants = array();
3811                        if($filter) {
3812                                $filter = "(|".$filter.")";
3813                                $valarray = explode(',',$id);
3814                                array_shift($valarray);
3815                                $dn = implode(',',$valarray);
3816                                $justThese = array("cn","mail");
3817                                $sr = ldap_search($ds,$dn, $filter,$justThese);
3818                                $info = ldap_get_entries($ds, $sr);
3819                                for($z = 0; $z < $info['count']; $z++) {
3820                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3821                                    $array_emails[$info[$z]['mail'][0]] = null;
3822                                        array_push($array_participants, $participant);
3823                                }
3824                                ldap_close($ds);
3825                        }
3826                        sort($array_participants);
3827                        $innerHTML = '';
3828                        foreach($array_participants as $index => $participant){
3829                                $innerHTML .= $participant;
3830                        }
3831                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
3832                        echo serialize($return);
3833                }
3834
3835                function get_catalog_participants_list($id)
3836                {
3837
3838                        $fields = $this->bo->catalog->get_fields(false);
3839                        $fields['names_ordered'] = true;
3840                        $fields['mail_forwarding_address'] = true;
3841                        $contact = $this->bo->catalog->get_single_entry($id,$fields);
3842
3843                        $array_participants = array();
3844                        $array_emails = array();
3845
3846                        $filter = null;
3847                        for($z = 0; $z < $contact['mail_forwarding_address']['count']; $z++) {
3848                                        if(strstr($contact['mail_forwarding_address'][$z],'@')) {
3849                                                $filter.="(mail=".$contact['mail_forwarding_address'][$z].")";
3850                                                $array_emails[$contact['mail_forwarding_address'][$z]] = "<font color=black>".$contact['mail_forwarding_address'][$z]."</font>";
3851                                        }
3852                                        else
3853                                                $array_participants[$z] = "<font color=red>".$contact['mail_forwarding_address'][$z]."</font>";
3854                        }
3855
3856                        if($filter) {
3857                                $filter = "(|".$filter.")";
3858                                if(!$this->bo->catalog->src_info) {
3859                                        $ldap = CreateObject('contactcenter.bo_ldap_manager');
3860                                        $this->bo->catalog->src_info = $ldap->srcs[1];
3861                                }
3862                                $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
3863                                $dn=$this->bo->catalog->src_info['dn'];
3864                                $justThese = array("cn","mail");
3865                                $sr = ldap_search($ds,$dn, $filter,$justThese);
3866                                $info = ldap_get_entries($ds, $sr);
3867                                for($z = 0; $z < $info['count']; $z++) {
3868                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
3869                                        $array_emails[$info[$z]['mail'][0]] = null;
3870                                        array_push($array_participants, $participant);
3871                                }
3872
3873                                foreach($array_emails as $index => $email)
3874                                        if($email)
3875                                                array_push($array_participants, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$email."<br>");
3876
3877                                ldap_close($ds);
3878                        }
3879                        sort($array_participants);
3880                        $innerHTML = '';
3881                        foreach($array_participants as $index => $participant){
3882                                $innerHTML .= $participant;
3883                        }
3884                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);
3885                        echo serialize($return);
3886                }
3887
3888                function export_contacts($typeExport){
3889
3890                        $boGroup = CreateObject('contactcenter.bo_group');
3891                        $contacts = $boGroup->get_all_contacts();
3892                        $streamBuffer = '';
3893
3894                        if(!count($contacts))
3895                                echo null;
3896
3897                        switch($typeExport) {
3898
3899                                case 'outlook_en':
3900                                        $streamBuffer = "Name;E-mail Address;Notes;Mobile Phone;Pager;Company;".
3901                                                        "Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";                                                       
3902                                        foreach($contacts as $index => $object){
3903                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\";"
3904                                                        . "\"".$object[ 'main-mail' ] . "\";"
3905                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\";"
3906                                                        . "\"".$object[ 'mobile' ] . "\";"
3907                                                        . "\"".$object[ 'business-pager' ] . "\";"
3908                                                        . "\"".$object[ 'corporate_name' ] . "\";"
3909                                                        . "\"".$object[ 'job_title' ] . "\";"
3910                                                        . "\"".$object[ 'home-phone' ] . "\";"
3911                                                        . "\"".$object[ 'home-fax' ] . "\";"
3912                                                        . "\"".$object[ 'business-phone' ] . "\";"
3913                                                        . "\"".$object[ 'business-fax' ] . "\"\r\n";
3914                                        }
3915                                        break;
3916
3917                                case 'outlook_pt-BR':
3918                                        $streamBuffer = "Nome;Sobrenome;Segundo nome;Nome;Apelido;End. de email;Endereço residencial;"
3919                                                                        ."Cidade do endereço residencial;CEP do endereço residencial;Estado;País/região do endereço residencial;"
3920                                                                        ."Telefone residencial;Fax residencial;Telefone celular;Página pessoal da Web;Rua do endereço comercial;"
3921                                                                        ."Cidade do endereço comercial;CEP do endereço comercial;Estado do endereço comercial;"
3922                                                                        ."País/região do endereço comercial;Página comercial da Web;Telefone comercial;Fax comercial;Pager;Empresa;"
3923                                                                        ."Cargo;Departamento;End. comercial;Observações\r\n";
3924
3925                                        foreach($contacts as $index => $object){
3926                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\";"
3927                                                        .";;;"
3928                                                        . "\"".$object[ 'alias' ] . "\";"
3929                                                        . "\"".$object[ 'main-mail' ] . "\";"
3930                                                        . "\"".$object[ 'home-address' ] . "\";"
3931                                                        . "\"".$object[ 'home-city_name' ] . "\";"
3932                                                        . "\"".$object[ 'home-postal_code' ] . "\";"
3933                                                        . "\"".$object[ 'home-state_name' ] . "\";"
3934                                                        . "\"".$object[ 'home-id_country' ] . "\";"
3935                                                        . "\"".$object[ 'home-phone' ] . "\";"
3936                                                        . "\"".$object[ 'home-fax' ] . "\";"
3937                                                        . "\"".$object[ 'mobile' ] . "\";"
3938                                                        . "\"".$object[ 'web_page' ] . "\";"
3939                                                        . "\"".$object[ 'business-address' ] . "\";"
3940                                                        . "\"".$object[ 'business-city_name' ] . "\";"
3941                                                        . "\"".$object[ 'business-postal_code' ] . "\";"
3942                                                        . "\"".$object[ 'business-state_name' ] . "\";"
3943                                                        . "\"".$object[ 'business-id_country' ] . "\";"
3944                                                        . "\"".$object[ 'web_page' ] . "\";"
3945                                                        . "\"".$object[ 'business-phone' ] . "\";"
3946                                                        . "\"".$object[ 'business-fax' ] . "\";"
3947                                                        . "\"".$object[ 'business-pager' ] . "\";"
3948                                                        . "\"".$object[ 'corporate_name' ] . "\";"
3949                                                        . "\"".$object[ 'job_title' ] . "\";"
3950                                                        . "\"".$object[ 'department' ] . "\";"
3951                                                        .";"
3952                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\"\r\n";
3953                                        }
3954
3955                                break;
3956
3957                                case 'outlook2000_pt-BR':
3958                                        $streamBuffer = "\"Tratamento\",\"Nome\",\"Segundo Nome\",\"Sobrenome\",\"Sufixo\",".
3959                                        "\"Empresa\",\"Departamento\",\"Cargo\",\"Rua do endereço comercial\",\"Rua do endereço comercial 2\",".
3960                                        "\"Rua do endereço comercial 3\",\"Cidade do endereço comercial\",\"Estado do endereço comercial\",".
3961                                        "\"CEP do endereço comercial\",\"País do endereço comercial\",\"Endereço residencial\",\"Rua residencial 2\",".
3962                                        "\"Rua residencial 3\",\"Cidade do endereço residencial\",\"Estado\",\"CEP do endereço residencial\",\"País do endereço residencial\",".
3963                                        "\"Outro endereço\",\"Outro endereço 2\",\"Outro endereço 3\",\"Cidade\",\"Estado\",\"CEP\",\"País\",".
3964                                        "\"Telefone do assistente\",\"Fax comercial\",\"Telefone comercial\",\"Telefone comercial 2\",\"Retorno de chamada\",".
3965                                        "\"Telefone do carro\",\"Telefone principal da empresa\",\"Fax residencial\",\"Telefone residencial\",".
3966                                        "\"Telefone residencial 2\",\"ISDN\",\"Telefone celular\",\"Outro fax\",\"Outro telefone\",\"Pager\",\"Telefone principal\",".
3967                                        "\"Radiofone\",\"Telefone TTY/TDD\",\"Telex\",\"Aniversário\",\"Anotações\",\"Caixa postal\",\"Categorias\",".
3968                                        "\"Código da empresa\",\"Código do governo\",\"Cônjuge\",\"Conta\",\"Endereço de correio eletrônico\",".
3969                                        "\"Nome de exibição do correio eletr.\",\"Endereço de correio eletrônico 2\",".
3970                                        "\"Nome de exibição do correio eletr.2\",\"Endereço de correio eletrônico 3\",".
3971                                        "\"Nome de exibição do correio eletr.3\",\"Datas especiais\",\"Disponibilidade da Internet\",".
3972                                        "\"Filhos\",\"Hobby\",\"Idioma\",\"Indicação\",\"Informações para cobrança\",\"Iniciais\",\"Local\",".
3973                                        "\"Nome do assistente\",\"Nome do gerenciador\",\"Página da Web\",\"Palavras-chave\",\"Particular\",\"Personalizado 1\",\"Personalizado 2\",".
3974                                        "\"Personalizado 3\",\"Personalizado 4\",\"Prioridade\",\"Profissão\",\"Quilometragem\",\"Sala\",\"Sensibilidade\",\"Servidor de diretório\",".
3975                                        "\"Sexo\"\r\n";
3976
3977
3978
3979                                        foreach($contacts as $index => $object){
3980                                $streamBuffer .= "\"".$object[ 'alias' ] . "\","                                   
3981                                                                . "\"".$object[ 'names_ordered' ] . "\","
3982                                                                .",,,"
3983                                                                . "\"".$object[ 'corporate_name' ] . "\","
3984                                                                . "\"".$object[ 'department' ] . "\","
3985                                                                . "\"".$object[ 'job_title' ] . "\","
3986                                                                . "\"".$object[ 'business-address' ] . "\","
3987                                                                . "\"".$object[ 'business-address-2' ] . "\","
3988                                                                .","
3989                                                                . "\"".$object[ 'business-city_name' ] . "\","
3990                                                                . "\"".$object[ 'business-state' ] . "\","
3991                                                                . "\"".$object[ 'business-postal_code' ] . "\","
3992                                                                . "\"".$object[ 'business-id_country' ] . "\","
3993                                                                . "\"".$object[ 'home-address' ] . "\","
3994                                                                . "\"".$object[ 'home-address-2' ] . "\","
3995                                                                .","
3996                                                                . "\"".$object[ 'home-city_name' ] . "\","
3997                                                                . "\"".$object[ 'home-state_name' ] . "\","
3998                                                                . "\"".$object[ 'home-postal_code' ] . "\","
3999                                                                . "\"".$object[ 'home-id_country' ] . "\","
4000                                                                .",,,,,,,,"
4001                                                                . "\"".$object[ 'business-fax' ] . "\","
4002                                                                . "\"".$object[ 'business-phone' ] . "\","
4003                                                                . "\"".$object[ 'business-mobile' ] . "\","
4004                                                                .",,,"
4005                                                                . "\"".$object[ 'home-fax' ] . "\","
4006                                                                . "\"".$object[ 'home-phone' ] . "\","
4007                                                                .",,"
4008                                                                . "\"".$object[ 'mobile' ] . "\","
4009                                                                .",,"
4010                                                                . "\"".$object[ 'home-pager' ] . "\","
4011                                                                . "\"".$object[ 'business-phone' ] . "\","
4012                                                                .",,,"
4013                                                                . "\"".$object[ 'birthdate' ] . "\","
4014                                                                . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
4015                                                                .",,,,,,"
4016                                                                . "\"".$object[ 'main-mail' ] . "\","
4017                                                                .","
4018                                                                . "\"".$object[ 'alternative-mail' ] . "\","
4019                                                                .",,,,,,,,,,,,,,"
4020                                                                . "\"".$object[ 'web_page' ] . "\","
4021                                                                .",,,,,,,,,,,,"
4022                                                                . "\"".$object[ 'sex' ] . "\"\r\n";                                                             
4023                            }
4024                                break;
4025
4026                                case 'outlook2000_en':
4027                                        $streamBuffer = "Title,First Name,Middle Name,Last Name,Suffix,Company,Department,Job Title,".
4028                                        "Business Street,Business Street 2,Business Street 3,Business City,Business State,Business Postal Code,".
4029                                        "Business Country,Home Street,Home Street 2,Home Street 3,Home City,Home State,Home Postal Code,Home Country,".
4030                                        "Other Street,Other Street 2,Other Street 3,Other City,Other State,Other Postal Code,Other Country,".
4031                                        "Assistant's Phone,Business Fax,Business Phone,Business Phone 2,Callback,Car Phone,Company Main Phone,Home Fax,".
4032                                        "Home Phone,Home Phone 2,ISDN,Mobile Phone,Other Fax,Other Phone,Pager,Primary Phone,Radio Phone,TTY/TDD Phone,Telex,".
4033                                        "Account,Anniversary,Assistant's Name,Billing Information,Birthday,Categories,Children,Directory Server,E-mail Address,".
4034                                        "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,".
4035                                        "Gender,Government ID Number,Hobby,Initials,Internet Free Busy,Keywords,Language,Location,Manager's Name,Mileage,Notes,".
4036                                        "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";
4037
4038                                        foreach($contacts as $index => $object){
4039                                                if( array_key_exists("phone", $object) )
4040                                                        $phone = $object['phone'];
4041                                                else
4042                            $phone = $object['business-phone'];
4043                                       
4044                                                $streamBuffer.= "\"".$object[ 'alias' ] . "\","
4045                                                        . "\"".$object[ 'names_ordered'] . "\","
4046                                                        .",,,"
4047                                                        . "\"".$object[ 'corporate_name' ] . "\","
4048                                                        . "\"".$object[ 'department' ] . "\","
4049                                                        . "\"".$object[ 'job_title' ] . "\","
4050                                                        . "\"".$object[ 'business-address' ] . "\","
4051                                                        . "\"".$object[ 'business-address-2' ] . "\","
4052                                                        .","
4053                                                        . "\"".$object[ 'business-city_name' ] . "\","
4054                                                        . "\"".$object[ 'business-state' ] . "\","
4055                                                        . "\"".$object[ 'business-postal_code' ] . "\","
4056                                                        . "\"".$object[ 'business-id_country' ] . "\","
4057                                                        . "\"".$object[ 'home-address' ] . "\","
4058                                                        . "\"".$object[ 'home-address-2' ] . "\","
4059                                                        .","
4060                                                        . "\"".$object[ 'home-city_name' ] . "\","
4061                                                        . "\"".$object[ 'home-state_name' ] . "\","
4062                                                        . "\"".$object[ 'home-postal_code' ] . "\","
4063                                                        . "\"".$object[ 'home-id_country' ] . "\","
4064                                                        .",,,,,,,,"
4065                                                        . "\"".$object[ 'business-fax' ] . "\","
4066                                                        . "\"".$phone . "\","
4067                                                        . "\"".$object[ 'business-mobile' ] . "\","
4068                                                        .",,,"
4069                                                        . "\"".$object[ 'home-fax' ] . "\","
4070                                                        . "\"".$object[ 'home-phone' ] . "\","
4071                                                        .",,"
4072                                                        . "\"".$object[ 'mobile' ] . "\","
4073                                                        .",,"
4074                                                        . "\"".$object[ 'business-pager' ] . "\","
4075                                                        . "\"".$object[ 'home-pager' ] . "\","
4076                                                        .",,,,,,,,"
4077                                                        . "\"".$object[ 'birthdate' ] . "\","
4078                                                        .",,,"
4079                                                        . "\"".$object[ 'main-mail' ] . "\","
4080                                                        .",,"
4081                                                        . "\"".$object[ 'alternative-mail' ] . "\","
4082                                                        .",,,,,,,,,,,,,,,"
4083                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
4084                                                        .",,,,,,,,,,,,,"
4085                                                        . "\"".$object[ 'web_page' ] . "\"\r\n";
4086
4087                                        }
4088                                break;
4089
4090                                case 'thunderbird':
4091                                        $streamBuffer = "First Name,Last Name,Display Name,Nickname,Primary Email,Secondary Email,"
4092                                                ."Screen Name,Work Phone,Home Phone,Fax Number,Pager Number,Mobile Number,Home Address,"
4093                                                ."Home Address 2,Home City,Home State,Home ZipCode,Home Country,Work Address,Work Address 2,"
4094                                                ."Work City,Work State,Work ZipCode,Work Country,Job Title,Department,Organization,Web Page 1,"
4095                                                ."Web Page 2,Birth Year,Birth Month,Birth Day,Custom 1,Custom 2,Custom 3,Custom 4,Notes,\n";
4096
4097                                        foreach($contacts as $index => $object){
4098                                                $array_birth = explode("-",$object[ 'birthdate' ]);
4099                                                $streamBuffer.= "\"".$object[ 'names_ordered'] . "\","
4100                                                        .",,"
4101                                                        . "\"".$object[ 'alias' ] . "\","
4102                                                        . "\"".$object[ 'main-mail' ] . "\","
4103                                                        . "\"".$object[ 'alternative-mail' ] . "\","
4104                                                        .","
4105                                                        . "\"".$phone . "\","
4106                                                        . "\"".$object[ 'home-phone' ] . "\","
4107                                                        . "\"".$object[ 'business-fax' ] . "\","
4108                                                        . "\"".$object[ 'business-pager' ] . "\","
4109                                                        . "\"".$object[ 'mobile' ] . "\","
4110                                                        . "\"".$object[ 'home-address' ] . "\","
4111                                                        . "\"".$object[ 'home-address-2' ] . "\","
4112                                                        . "\"".$object[ 'home-city_name' ] . "\","
4113                                                        . "\"".$object[ 'home-state_name' ] . "\","
4114                                                        . "\"".$object[ 'home-postal_code' ] . "\","
4115                                                        . "\"".$object[ 'home-id_country' ] . "\","
4116                                                        . "\"".$object[ 'business-address' ] . "\","
4117                                                        . "\"".$object[ 'business-address-2' ] . "\","
4118                                                        . "\"".$object[ 'business-city_name' ] . "\","
4119                                                        . "\"".$object[ 'business-state_name' ] . "\","
4120                                                        . "\"".$object[ 'business-postal_code' ] . "\","
4121                                                        . "\"".$object[ 'business-id_country' ] . "\","
4122                                                        . "\"".$object[ 'job_title' ] . "\","
4123                                                        . "\"".$object[ 'department' ] . "\","
4124                                                        . "\"".$object[ 'corporate_name' ] . "\","
4125                                                        . "\"".$object[ 'web_page' ] . "\","
4126                                                        . "\"".$object[ 'web_page' ] . "\","
4127                                                        . "\"".$array_birth[0] . "\","
4128                                                        . "\"".$array_birth[1] . "\","
4129                                                        . "\"".$array_birth[2] . "\","
4130                                                        .",,,,"
4131                                                        . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\",\r\n";
4132
4133                                        }
4134                                break;
4135
4136                                case 'expresso':
4137                            $streamBuffer = 'Nome,Apelido,E-mail Principal,E-mail Alternativo,Celular,'
4138                                . 'Telefone Comercial,Endereço Comercial,Complemento End. Comercial,CEP Comercial,Cidade End. Comercial,Estado End. Comercial,País End. Comercial,'
4139                                . 'Telefone Residencial,Endereço Residencial,Complemento End. Residencial,CEP Residencial,Cidade End. Residencial,Estado End. Residencial,País End. Residencial,'
4140                                . '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'
4141                                                        . "\r\n";
4142
4143                            foreach($contacts as $index => $object){
4144                                $streamBuffer .= "\"".$object[ 'names_ordered'] . "\","
4145                                    . "\"".$object[ 'alias' ] . "\","
4146                                    . "\"".$object[ 'main-mail' ] . "\","
4147                                    . "\"".$object[ 'alternative-mail' ] . "\","
4148                                    . "\"".$object[ 'mobile' ] . "\","
4149                                    . "\"".$object[ 'business-phone' ] . "\","
4150                                    . "\"".$object[ 'business-address' ] . "\","
4151                                    . "\"".$object[ 'business-complement' ] . "\","
4152                                    . "\"".$object[ 'business-postal_code' ] . "\","
4153                                    . "\"".$object[ 'business-city_name' ] . "\","
4154                                    . "\"".$object[ 'business-state_name' ] . "\","
4155                                    . "\"".$object[ 'business-id_country' ] . "\","
4156                                    . "\"".$object[ 'home-phone' ] . "\","
4157                                    . "\"".$object[ 'home-address' ] . "\","
4158                                    . "\"".$object[ 'home-complement' ] . "\","
4159                                    . "\"".$object[ 'home-postal_code' ] . "\","
4160                                    . "\"".$object[ 'home-city_name' ] . "\","
4161                                    . "\"".$object[ 'home-state_name' ] . "\","
4162                                    . "\"".$object[ 'home-id_country' ] . "\","
4163                                                                . "\"".$object[ 'birthdate' ] . "\","
4164                                                                . "\"".$object[ 'sex' ] . "\","
4165                                                                . "\"".$object[ 'pgp_key' ] . "\","
4166                                                                . "\"".str_replace("\r\n\x0a","\t",$object[ 'notes' ]) . "\","
4167                                                                . "\"".$object[ 'web_page' ] . "\","
4168                                                                . "\"".$object[ 'corporate_name' ] . "\","
4169                                                                . "\"".$object[ 'job_title' ] . "\","
4170                                                                . "\"".$object[ 'department' ] . "\","
4171                                                                . "\"".$object[ 'business-fax' ] . "\","
4172                                                                . "\"".$object[ 'business-pager' ] . "\","
4173                                                                . "\"".$object[ 'business-mobile' ] . "\","
4174                                                                . "\"".$object[ 'home-fax' ] . "\","
4175                                                                . "\"".$object[ 'home-pager' ] . "\","
4176                                                                . "\"".$object[ 'business-address-2' ] . "\","
4177                                                                . "\"".$object[ 'home-address-2' ] . "\"\r\n";
4178                            }
4179                        break;
4180
4181                        }
4182
4183                        $file = "contacts_".md5(microtime()).".swp";
4184                        $tempDir = $GLOBALS['phpgw_info']['server']['temp_dir'];
4185                        $f = fopen($tempDir.'/'.$file,"w");
4186                        if(!$f)
4187                                echo null;
4188
4189                        fputs($f,$streamBuffer);
4190                        fclose($f);
4191
4192                        echo $tempDir.'/'.$file;
4193                }
4194
4195                // Get the csv field and put into array, from php.net
4196                function parse_line($input_text, $delimiter = ',', $text_qualifier = '"') {
4197                        $text = trim($input_text);
4198                          if(is_string($delimiter) && is_string($text_qualifier)) {
4199                         $re_d = '\x' . dechex(ord($delimiter));            //format for regexp
4200                        $re_tq = '\x' . dechex(ord($text_qualifier));    //format for regexp
4201
4202                        $fields = array();
4203                        $field_num = 0;
4204                        while(strlen($text) > 0) {
4205                        if($text{0} == $text_qualifier) {
4206                                preg_match('/^' . $re_tq . '((?:[^' . $re_tq . ']|(?<=\x5c)' . $re_tq . ')*)' . $re_tq . $re_d . '?(.*)$/', $text, $matches);
4207
4208                                $value = str_replace('\\' . $text_qualifier, $text_qualifier, $matches[1]);
4209                                $text = trim($matches[2]);
4210
4211                                $fields[$field_num++] = $value;
4212                        } else {
4213                                preg_match('/^([^' . $re_d . ']*)' . $re_d . '?(.*)$/', $text, $matches);
4214
4215                                $value = $matches[1];
4216                                $text = trim($matches[2]);
4217
4218                                $fields[$field_num++] = $value;
4219                }
4220                }
4221                        return $fields;
4222                    } else
4223                        return false;
4224                }
4225
4226                //funcao alterada para importar outros campos alem de nome, telefone e email, de arquivo csv (Outlook 2000)
4227                //em 08/04/2009 - Rommel Cysne (rommel.cysne@serpro.gov.br);
4228                //Foi adicionada uma funcao (escapesheelcmd()) nas variaveis para que caracteres especiais sejam ignorados
4229                //durante a importacao dos contatos; o processo estava travando por causa de caracteres em campos como nome,
4230                //sobrenome, notas e e-mail;
4231                //em 19/06/2009 - Rommel Cysne (rommel.cysne@serpro.gov.br);
4232                function import_contacts($typeImport, $id_group=false){
4233                        $this->so_group = CreateObject('contactcenter.so_group');
4234                        if($file = $_SESSION['contactcenter']['importCSV']) {
4235                                unset($_SESSION['contactcenter']['importCSV']);
4236                                $len = filesize($file);
4237                                $count = 0;
4238                                $return = array('error' => false, '_new' => 0, '_existing' => 0, '_failure' => 0);
4239                                $handle = @fopen($file, "r") or die(serialize($return['error'] = true));
4240
4241                                $input_header = fgets($handle);
4242                                if ($typeImport == 'outlook')
4243                                        $delim = ';';
4244                                else if ($typeImport == 'auto')
4245                                $delim = strstr($input_header,',') ? ',' : ';';
4246                                else
4247                                        $delim = ',';
4248                                $csv_header = $this->parse_line($input_header,$delim);
4249                                $firstContact = fgets($handle);
4250                                preg_match("/\"(.+)\"[,;]/sU",$firstContact,$matches); // yahoo csv
4251                                rewind($handle);
4252
4253                                $header = @fgetcsv($handle, $len, $delim) or die(serialize($return['error'] = true));
4254                                if(count($header)  < 2 || count($header) > 100) {
4255                                        $return['error'] = true;
4256                                        $return['sizeheader'] = count($header);
4257                                        echo serialize($return);
4258                                        return;
4259                                }
4260
4261                                if ($matches[0][strlen($matches[0])-1] == ';')
4262                                        $delim = ';';
4263
4264                                $boGroup = CreateObject('contactcenter.bo_group');
4265                                $boPeople = CreateObject('contactcenter.bo_people_catalog');
4266                                        switch($typeImport){
4267                                                case 'outlook2000':
4268                                                        $name_pos=1;
4269                                                        $name2_pos=2;
4270                                                        $name3_pos=3;
4271                                                        $corporate_street_pos=8;
4272                                                        $cep_pos=13;
4273                                                        $corporate_street_2_pos=22;
4274                                                        $fax_pos=30;
4275                                                        $phone_pos=31;
4276                                                        $home_phone_pos=37;
4277                                                        $personal_cell_pos=40;
4278                                                        $pager_pos=43;
4279                                                        $birth_pos=48;
4280                                                        $notes_pos=49;
4281                                                        $email_pos=56;
4282                                                        $aditionalEmail_pos=59;
4283
4284                                                        break;
4285                                                case 'outlook':
4286                                                        $name_pos=3;
4287                                                        $email_pos=4;
4288                                                        $phone_pos=7;
4289                                                        $home_phone_pos=10;
4290                                                        $personal_cell_pos=12;
4291                                                        $corporate_street_pos=13;
4292                                                        $cep_pos=15;
4293                                                        $phone_pos=18;
4294                                                        $fax_pos=19;
4295                                                        $pager_pos=20;
4296                                                        $notes_pos=25;
4297                                                        break;
4298                                                case 'thunderbird':
4299                                                        $name_pos=2;
4300                                                        $email_pos=4;
4301                                                        $phone_pos=7;
4302                                                        break;
4303                                                case 'expresso':
4304                                                        $name_pos=0;
4305                                                        $alias_pos=1;
4306                                                        $email_pos=2;
4307                                                        $aditionalEmail_pos=3;
4308                                                        $personal_cell_pos=4;
4309                                                        $corporate_phone_pos=5;
4310                                                        $corporate_street_pos=6;
4311                                                        $corporate_comp_pos=7;
4312                                                        $corporate_cep_pos=8;
4313                                                        $corporate_city_pos=9;
4314                                                        $corporate_state_pos=10;
4315                                                        $corporate_country_pos=11;
4316                                                        $home_phone_pos=12;
4317                                                        $street_pos=13;
4318                                                        $comp_pos=14;
4319                                                        $cep_pos=15;
4320                                                        $city_pos=16;
4321                                                        $state_pos=17;
4322                                                        $country_pos=18;
4323                                                        $birth_pos=19;
4324                                                        $sex_pos = 20;
4325                                                        $pgp_key_pos = 21;
4326                                                        $notes_pos=22;
4327                                                        $web_page_pos=23;
4328                                                        $corporate_name_pos=24;
4329                                                        $job_title_pos=25;
4330                                                        $department_pos=26;
4331                                                        $corporate_fax_pos=27;
4332                                                        $corporate_pager_pos=28;
4333                                                        $corporate_cell_pos=29;
4334                                                        $fax_pos=30;
4335                                                        $pager_pos=31;
4336                                                        $corporate_street_2_pos = 32;
4337                                                        $street_2_pos = 33;                                             
4338                                                        break;
4339                                        default:
4340                                                        foreach($csv_header as $index => $fieldName)
4341                                                        {
4342                                                                switch($fieldName){
4343                                                                case 'Name':
4344                                                                case 'Nome':
4345                                                                case 'First Name':
4346                                                                        $name_pos = $index;
4347                                                                        break;
4348                                                                case 'Second name':
4349                                                                case 'Segundo nome':
4350                                                                        $name2_pos = $index;
4351                                                                        break;
4352                                                                case 'Sobrenome':
4353                                                                case 'Surname':
4354                                                                        $name3_pos = $index;
4355                                                                        break;
4356                                                                case 'Business Street':
4357                                                                case 'Rua do endereço comercial':
4358                                                                        $corporate_street_pos = $index;
4359                                                                        break;
4360                                                                case 'Rua do endereço comercial 2':
4361                                                                case 'Outro endereço':
4362                                                                        $corporate_street_2_pos = $index;
4363                                                                        break;
4364                                                                case 'Business Postal Code':
4365                                                                case 'CEP do endereço comercial':
4366                                                                        $cep_pos = $index;
4367                                                                        break;
4368                                                                case 'Business Fax':
4369                                                                case 'Fax comercial':
4370                                                                case 'Fax':
4371                                                                        $fax_pos = $index;
4372                                                                        break;
4373                                                                case 'Home Phone':
4374                                                                case 'Telefone residencial':
4375                                                                        $home_phone_pos = $index;
4376                                                                        break;
4377                                                                case 'Mobile phone':
4378                                                                case 'Telefone celular':
4379                                                                        $personal_cell_pos = $index;
4380                                                                        break;
4381                                                                case 'Pager':
4382                                                                        $pager_pos = $index;
4383                                                                        break;
4384                                                                case 'Phone':
4385                                                                case 'Business Phone':
4386                                                                case 'Telefone':
4387                                                                case 'Telefone principal':
4388                                                                case 'Telefone comercial':
4389                                                                case 'Telefone Comercial':
4390                                                                        $phone_pos = $index;
4391                                                                        break;
4392                                                                case 'Aniversário':
4393                                                                case 'Birthdate':
4394                                                                        $birth_pos = $index;
4395                                                                case 'Anotações':
4396                                                                case 'Notes':
4397                                                                        $notes_pos = $index;
4398                                                                case 'E-mail':
4399                                                                case 'Email':
4400                                                                case 'E-mail Address':
4401                                                                case 'Endereço de correio eletrônico':
4402                                                                case 'End. de email':
4403                                                                        $email_pos = $index;
4404                                                                        break;
4405                                                                case 'Endereço de correio eletrônico 2':
4406                                                                        $aditionalEmail_pos = $index;
4407                                                                        break;
4408                                                                }
4409                                                        }
4410                                                        break;
4411                                }
4412
4413                                while (($data = fgetcsv($handle, $len, $delim))) {
4414                                        foreach ($header as $key=>$heading)
4415                                $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
4416
4417                                                $sdata = array();
4418                                                $full_name  = trim($row[$header[$name_pos]]);
4419                                                $email          = trim($row[$header[$email_pos]]);
4420                                                $phone          = trim($row[$header[$phone_pos]]);
4421                                                $name2          = trim($row[$header[$name2_pos]]);
4422                                                $name3          = trim($row[$header[$name3_pos]]);
4423
4424                                                $birth          = trim($row[$header[$birth_pos]]);
4425                                                $notes          = trim($row[$header[$notes_pos]]);
4426                                                $altEmail       = trim($row[$header[$altEmail_pos]]);
4427                                                $sdata['alias']                         = trim($row[$header[$alias_pos]]);
4428                                                $sdata['corporate_name']      = trim($row[$header[$corporate_name_pos]]);
4429                                                $sdata['job_title']             = trim($row[$header[$job_title_pos]]);
4430                                                $sdata['department']            = trim($row[$header[$department_pos]]);
4431                                                $sdata['web_page']                      = trim($row[$header[$web_page_pos]]);
4432                                               
4433                                                $sdata['sex']                   = trim($row[$header[$sex_pos]]);
4434                                                $sdata['pgp_key']      = trim($row[$header[$pgp_key_pos]]);
4435
4436
4437                                        $full_name = $full_name;
4438                                        $array_name = explode(' ', str_replace('"','',(str_replace('\'','',$full_name))));
4439                                        $sdata['given_names'] = addslashes($array_name[0]);
4440                                        $array_name[0] = null;
4441                                        $sdata['family_names'] = trim(implode(' ',$array_name));
4442                                        if($sdata['family_names'] == '')
4443                                        {
4444                                                $sdata['family_names'] = addslashes($name2) . " " . addslashes($name3);
4445                                        }
4446
4447                                                $sdata['connections']['default_email']['connection_name'] = lang('Main');
4448                                                $sdata['connections']['default_email']['connection_value'] = addslashes($email);
4449                                                $sdata['connections']['aditional_email']['connection_name'] = "Alternativo";
4450                                                $sdata['connections']['aditional_email']['connection_value'] = trim($row[$header[$aditionalEmail_pos]]);
4451
4452                                                $sdata['connections']['default_phone']['connection_name'] = lang('Main');
4453                                       
4454                                                $sdata['connections']['default_phone']['connection_value'] = $phone;
4455
4456                                                if( trim($row[$header[$home_phone_pos]]) != "" )
4457                                                {
4458                                                    $sdata['connections']['aditional_phone']['home_phone']['connection_name'] = 'Casa';
4459                                                    $sdata['connections']['aditional_phone']['home_phone']['connection_value'] = trim($row[$header[$home_phone_pos]]);
4460                                                }
4461
4462                                                if( trim($row[$header[$personal_cell_pos]]) != "" )
4463                                                {
4464                                                    $sdata['connections']['aditional_phone']['cellphone']['connection_name'] = 'Celular';
4465                                                    $sdata['connections']['aditional_phone']['cellphone']['connection_value'] = trim($row[$header[$personal_cell_pos]]);
4466                                                }
4467
4468                                                if( trim($row[$header[$corporate_phone_pos]]) != "")
4469                                                {
4470                                                    $sdata['connections']['aditional_phone']['corporate_phone']['connection_name'] = 'Trabalho';
4471                                                    $sdata['connections']['aditional_phone']['corporate_phone']['connection_value'] = trim($row[$header[$corporate_phone_pos]]);
4472                                                }
4473
4474                                                if( trim($row[$header[$fax_pos]]) != "" )
4475                                                {
4476                                                    $sdata['connections']['aditional_phone']['fax']['connection_name'] = 'Fax';
4477                                                    $sdata['connections']['aditional_phone']['fax']['connection_value'] = trim($row[$header[$fax_pos]]);
4478                                                }
4479
4480                                                if ($GLOBALS['phpgw_info']['server']['personal_contact_type'] == 'True')
4481                                                {
4482                                                    if( trim($row[$header[$pager_pos]]) != "" )
4483                                                    {
4484                                                        $sdata['connections']['aditional_phone']['pager']['connection_name'] = 'Pager';
4485                                                        $sdata['connections']['aditional_phone']['pager']['connection_value'] = trim($row[$header[$pager_pos]]);
4486                                                    }
4487
4488                                                    if( trim($row[$header[$corporate_fax_pos]]) != "" )
4489                                                    {
4490                                                        $sdata['connections']['aditional_phone']['corporate_fax']['connection_name'] = 'Fax Corporativo';
4491                                                        $sdata['connections']['aditional_phone']['corporate_fax']['connection_value'] = trim($row[$header[$corporate_fax_pos]]);
4492                                                    }
4493
4494                                                    if( trim($row[$header[$corporate_cell_pos]]) != "" )
4495                                                    {
4496                                                        $sdata['connections']['aditional_phone']['corporate_cell']['connection_name'] = 'Celular Corporativo';
4497                                                        $sdata['connections']['aditional_phone']['corporate_cell']['connection_value'] = trim($row[$header[$corporate_cell_pos]]);
4498                                                    }
4499
4500                                                    if( trim($row[$header[$corporate_pager_pos]]) != "" )
4501                                                    {
4502                                                        $sdata['connections']['aditional_phone']['corporate_pager']['connection_name'] = 'Pager Corporativo';
4503                                                        $sdata['connections']['aditional_phone']['corporate_pager']['connection_value'] = trim($row[$header[$corporate_pager_pos]]);
4504                                                    }
4505                                                }
4506                                       
4507                                                $sdata['addresses']['address_corporative']['address1'] = trim($row[$header[$corporate_street_pos]]);
4508                                                $sdata['addresses']['address_corporative']['address2'] = trim($row[$header[$corporate_street_2_pos]]);
4509                                                $sdata['addresses']['address_corporative']['complement'] = trim($row[$header[$corporate_comp_pos]]);
4510                                                $sdata['addresses']['address_corporative']['postal_code'] = trim($row[$header[$corporate_cep_pos]]);                                           
4511                                                $sdata['addresses']['address_corporative']['id_country'] = "BR";
4512                                                $sdata['addresses']['address_corporative']['id_state'] = trim($row[$header[$corporate_state_pos]]);     
4513                                                $sdata['addresses']['address_corporative']['id_city'] = trim($row[$header[$corporate_city_pos]]);
4514                                               
4515                                                                                                       
4516                                                $sdata['addresses']['address_personal']['address1'] = trim($row[$header[$street_pos]]);
4517                                                $sdata['addresses']['address_personal']['address2'] = trim($row[$header[$street_2_pos]]);
4518                                                $sdata['addresses']['address_personal']['complement'] = trim($row[$header[$comp_pos]]);
4519                                                $sdata['addresses']['address_personal']['postal_code'] = trim($row[$header[$cep_pos]]);
4520                                                $sdata['addresses']['address_personal']['id_country'] = "BR";                                                   
4521                                                $sdata['addresses']['address_personal']['id_state'] = trim($row[$header[$state_pos]]); 
4522                                                $sdata['addresses']['address_personal']['id_city'] =  trim($row[$header[$city_pos]]);
4523
4524                                        if(trim($birth)) {
4525                                                $array_birth = explode("/",trim($birth));
4526                                                $sdata['birthdate'] = date('Y-m-d', mktime(0,0,0,$array_birth[1],$array_birth[0],$array_birth[2]));
4527                                        }
4528
4529                                        $sdata['notes'] = addslashes($notes);
4530                                        //$sdata['is_quick_add'] = true;
4531                                        $sdata['connections']['default_phone']['connection_value'] = $phone;
4532
4533                                        //      verifica se email já existe!
4534                                        $email = addslashes($email);
4535                                        // Foi modificado o método que fazia a verificação se um contato já existe.
4536                                        // Antes era verificado somente com base no email do contato.
4537                                        $contact = $boGroup->verify_contact($email, $full_name, $phone);
4538
4539                                        if(!$sdata['given_names'] && $email){
4540                                                        $a_email = explode("@",$email);
4541                                                        $sdata['given_names'] = addslashes($a_email[0]);
4542                                        }
4543
4544                                        $line_iteration = $return['_failure'] + $return['_existing'] + $return['_new'];
4545
4546                                        if($contact){
4547                                                $return['_existing']++;
4548                                        }                                                               
4549                                    // Modificada a expressão regular para aceitar endereços de email fora do padrão nome@provedor.com.br.
4550                                    // Aceita casos de domínios internos como c0000@mail.caixa.                                 
4551                                        else if((!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[_a-z0-9-]+(\.[_a-z0-9-]+)+$", $email)) && $email) {
4552                                                $return['_failure']++;
4553                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid E-Mail address: " . $email ."<br>";
4554                                        }
4555                                        else if (!$sdata['given_names'] || !$boPeople ->quick_add($sdata)){
4556                                                $return['_failure']++;
4557                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid Name: " . $sdata['given_names'] ."<br>";
4558                                        }
4559                                        else{   
4560                                                        if($id_group != 0){                                                             
4561                                                                $this->so_group->add_user_by_name($id_group,$full_name);
4562                                                        }                                               
4563                                                        $return['_new']++;
4564                                                }
4565                        }
4566                                fclose($handle);
4567                                unlink($file);
4568                        }
4569                        else
4570                                $return['error'] = true;
4571
4572                        echo serialize($return);
4573                }
4574       
4575                /*!
4576                 * @function get_contact_details
4577                 * @abstract Retorna os detalhes extras de um contato
4578                 * @author Luiz Carlos Viana Melo - Prognus
4579                 * @param (string) O ID do usuário do LDAP
4580                 */
4581                function get_contact_details($id)
4582                {
4583                        $data = array();
4584                       
4585                        if(!$this->bo->catalog->src_info) {
4586                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
4587                                $this->bo->catalog->src_info = $ldap->srcs[1];
4588                        }
4589                       
4590                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);                             
4591                        $dn=$this->bo->catalog->src_info['dn'];
4592                       
4593                        //buscar os atributos do ldap
4594                        $configobj = CreateObject('phpgwapi.config', 'contactcenter');
4595                        $prefs = $configobj->read_repository();
4596                        $attr_names = array();
4597                        $attr_types = array();
4598                        $justThese = array();
4599                        foreach ($prefs as $pref_key => $pref_value)
4600                        {
4601                                if (stripos($pref_key, "cc_attribute_name_") !== false)
4602                                {
4603                                        $num = substr($pref_key, strlen("cc_attribute_name_"));
4604                                        $attr_names[] = $prefs["cc_attribute_name_$num"];
4605                                        $attr_types[] = $prefs["cc_attribute_type_$num"];
4606                                        $justThese[] = strtolower($prefs["cc_attribute_ldapname_$num"]);
4607                                }
4608                        }
4609                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);                                                   
4610                        $info = ldap_get_entries($ds, $sr);
4611                        if ($info)
4612                        {
4613                                for ($i = 0; $i < count($justThese); $i++)
4614                                {
4615                                        $attr = array();
4616                                        $attr['name'] = $attr_names[$i];
4617                                        if ($attr_types[$i] == 'multivalues')
4618                                        {
4619                                                $attr['type'] = 'multivalues';
4620                                                $attr['value'] = array();
4621                                                for ($j = 0; $j < $info[0][$justThese[$i]]['count']; $j++)
4622                                                        $attr['value'][] = utf8_decode($info[0][$justThese[$i]][$j]);
4623                                        }
4624                                        else
4625                                        {
4626                                                $attr['type'] = 'text';
4627                                                $attr['value'] = utf8_decode($info[0][$justThese[$i]][0]);
4628                                        }
4629                                        $data[] = $attr;
4630                                }
4631                        }
4632                        else
4633                                $data = 'error';
4634                        ldap_close($ds);
4635                       
4636                        echo serialize($data);
4637                }
4638        }
4639
4640?>
Note: See TracBrowser for help on using the repository browser.