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

Revision 1419, 100.3 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #421 - Ajuste no tratamento do referral para catalogo externo

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