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

Revision 2475, 116.8 KB checked in by rodsouza, 14 years ago (diff)

Ticket #1009 - Correção de problemas no ExpressoContacts? ao exibir algumas imagens.

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