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

Revision 1656, 116.2 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #760 - Adicicao de 'if' para verificar se o tipo de contato corporativo esta habilitado

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