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

Revision 7673, 162.9 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

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