source: branches/2.0/contactcenter/inc/class.ui_data.inc.php @ 3179

Revision 3179, 100.2 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1167 - Corrigido problema ao clicar em organização vazia.

  • 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                                        if(is_array($result)) {
998                                                foreach ($result as $id => $value)
999                                                {
1000                                                        if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
1001                                                                $this->page_info['actual_entries'][] = $value[$field_name];
1002                                                        else
1003                                                                $this->page_info['actual_entries'][] = array(0=>$value[$field_name],1=>$value['perms'],2=>$value['owner']);
1004                                                }
1005                                        }
1006                                }
1007                        }
1008                        else if ($letter === 'search')
1009                        {
1010                                //if (!$ids and $this->page_info['actual_letter'] !== 'search')
1011                                if (!$ids)
1012                                {
1013                                        //error_log('!$ids e $this->page_info[\'actual_letter\'] != search');
1014                                        $this->page_info['actual_entries'] = false;
1015                                       
1016                                        $this->page_info['actual_letter'] = $letter;
1017                                        $this->page_info['actual_page'] = 0;
1018                                       
1019                                        $this->save_session();
1020                                        $final[0] = 0;
1021                                        $final[1] = $this -> typeContact;
1022                                        echo serialize($final);                                 
1023                                        return;
1024                                }
1025                                else if ($ids['error'])
1026                                {
1027                                        $this->page_info['actual_entries'] = false;
1028                                        $this->page_info['actual_letter'] = $letter;
1029                                        $this->page_info['actual_page'] = 0;
1030
1031                                        $this->save_session();
1032                                        $final[0] = 0;
1033                                        $final[1] = $this -> typeContact;
1034                                        $final['error'] = $ids['error'];
1035                                        echo serialize($final);
1036                                        return;
1037                                }
1038                                else if ($ids)
1039                                {                               
1040                                        $this->page_info['actual_letter']  = $letter;
1041                                        $this->page_info['actual_entries'] = $ids;
1042                                        $this->page_info['n_pages'] = ceil(count($ids)/($this->page_info['n_cards'] ? $this->page_info['n_cards'] : 1));
1043                                }
1044                        }
1045                        else
1046                        {
1047                                unset($ids);
1048                        }
1049
1050                        if ($this->page_info['actual_entries'])
1051                        {
1052                                if ($page >= $this->page_info['n_pages'])
1053                                {
1054                                        $page = $this->page_info['n_pages'];
1055                                }
1056                               
1057                                $final = array(
1058                                        0 => (int)$this->page_info['n_pages'],
1059                                        1 => (int)$page,
1060                                        2 => array(
1061                                                0 => 'cc_company',
1062                                                1 => 'cc_name',
1063                                                2 => 'cc_title',
1064                                                3 => 'cc_phone',
1065                                                4 => 'cc_mail',
1066                                                5 => 'cc_alias',
1067                                                6 => 'cc_id',
1068                                                7 => 'cc_forwarding_address'                                           
1069                                        )
1070                                );
1071                               
1072                                //echo 'Page: '.$page.'<br>';
1073                                $id_i = (($page-1)*$this->page_info['n_cards']);
1074                                $id_f = $id_i + $this->page_info['n_cards'];
1075                                $n_entries = count($this->page_info['actual_entries']);
1076                               
1077                                //echo 'ID_I: '.$id_i.'<br>';
1078                                //echo 'ID_F: '.$id_f.'<br>';
1079                               
1080                                $ids = array();
1081                                $perms = array();
1082                                $owners = array();
1083                                $array_temp = array();                 
1084                               
1085                                foreach($this->page_info['actual_entries'] as $key=>$tmp){
1086                                                $array_temp[] = $tmp;                           
1087                                }       
1088                               
1089                                for($i = $id_i; $i < $id_f and $i < $n_entries; $i++)
1090                                {
1091                                        if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
1092                                                $ids[] = $array_temp[$i];
1093                                        else {
1094                                                $ids[] = $array_temp[$i][0];
1095                                                $perms[] = $array_temp[$i][1];
1096                                                $owners[] = $array_temp[$i][2];
1097                                        }
1098                                        //$perms[] = $array_temp[$i];
1099                                }
1100                               
1101                               
1102                                // Carrega o nome completo dos donos dos objetos (contatos e grupos);
1103                                $owner_names = array();
1104                                                       
1105                                if($owners) {
1106                                        $filter = "(|";
1107                                        foreach($owners as $i => $owner) {
1108                                                $filter .= "(uidNumber=".$owner.")";
1109                                        }
1110                                        $filter .= ")";
1111                                       
1112                                        if(!$this->bo->catalog->src_info) {
1113                                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
1114                                                $this->bo->catalog->src_info = $ldap->srcs[1];
1115                                        }
1116                                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], false);                             
1117                                        $dn=$this->bo->catalog->src_info['dn'];
1118                                        $justThese = array("cn","uidnumber","uid");
1119                                        $sr = ldap_search($ds,$dn, $filter,$justThese);                                                         
1120                                        $info = ldap_get_entries($ds, $sr);
1121                                        ldap_close($ds);                                                                                       
1122                                        for($z = 0; $z < $info['count']; $z++) {
1123                                                $owner_names[$info[$z]['uidnumber'][0]] = array("cn" => $info[$z]['cn'][0], "uid" => $info[$z]['uid'][0]);
1124                                        }                               
1125                                }
1126                                /// Original
1127                                //for($i = $id_i; $i < $id_f and $i < $n_entries; $i++)
1128                                //{
1129                                //      $ids[] = $this->page_info['actual_entries'][$i];
1130                                //}
1131                                ///
1132                               
1133                                $fields = $this->bo->catalog->get_fields(false);
1134                                if( $this->typeContact == 'groups' || $this->typeContact == 'shared_groups') {
1135                                        $final = array(
1136                                                0 => (int)$this->page_info['n_pages'],
1137                                                1 => (int)$page,
1138                                                2 => array(
1139                                                        0 => 'cc_title',
1140                                                        1 => 'cc_short_name',
1141                                                        2 => 'cc_id',
1142                                                        3 => 'cc_contacts'
1143                                                )                                               
1144                                        );                                     
1145                                        $groups =& $this->bo->catalog->get_multiple_entries($ids,$fields);
1146                                                                                                                       
1147                                        $i = 0;
1148                                        // contatos do grupo
1149                                        $boGroups = CreateObject('contactcenter.bo_group');                                     
1150                                        $contacts = array();
1151                                       
1152                                        foreach($groups as $group)              {       
1153                                                $final[3][$i][0] = $group['title'] ? $group['title'] : 'none';
1154                                                $final[3][$i][1] = $group['short_name'] ? $group['short_name'] : 'none';                                               
1155                                                $final[3][$i][2] = $group['id_group'] ? $group['id_group'] : 'none';
1156                                                $contacts = $boGroups -> get_contacts_by_group($group['id_group']);
1157                                                $final[3][$i][3] = $contacts;
1158                                                $final[3][$i][4] = $perms[$i];
1159                                                if($this->typeContact == 'shared_groups'){
1160                                                        $final[3][$i][5] = lang('Shared').": ".$owner_names[$owners[$i]]['cn'];
1161                                                        $final[3][$i][6] = $owner_names[$owners[$i]]['uid'];
1162                                                        $final[3][$i][7] = $owners[$i]; //uidNumber
1163                                                }                                               
1164                                                $i++;                                                   
1165                                        }
1166                                       
1167                                        $this->page_info['actual_letter'] = $letter;
1168                                        $this->page_info['actual_page'] = $page;                                       
1169                                       
1170                                       
1171                                        $lnk_compose = "location.href=('../expressoMail1_2/index.php?to=";
1172                                       
1173                                        $final[5] = '<span class="link"  onclick="'.$lnk_compose;                                       
1174                                        $final[10] = $this->typeContact;                                                                                                                                                                                                               
1175                                        $this->save_session();                                 
1176                                        echo serialize($final);
1177                                        return;                                 
1178                                }
1179                                $final[10] = $this -> typeContact;
1180                               
1181                                $fields['photo'] = true;
1182                                $fields['names_ordered'] = true;
1183                                $fields['alias'] = true;
1184                                $fields['account_type'] = true;
1185                                $fields['companies'] = 'default';
1186                                $fields['connections'] = 'default';
1187                                // ?aqui alterar a chamada desse método para receber o base dn?
1188                                if($external)
1189                                        $contacts = &$this->bo->catalog->get_multiple_entries($ids,$fields,false,true);
1190                                else
1191                                        $contacts = &$this->bo->catalog->get_multiple_entries($ids,$fields);
1192                               
1193                               
1194                                if (!is_array($contacts) or !count($contacts))
1195                                {
1196                                        $final[0] = 0;
1197                                        $final[1] = $this -> typeContact;
1198                                        echo serialize($final);
1199                                        return;
1200                                }
1201                               
1202                                $i = 0;
1203                                foreach($contacts as $index => $contact)
1204                                {
1205                                        /*
1206                                         * TODO: Os timeouts de conexão foram retirados, ver se será necessário retornar essa funcionalidade, e,
1207                                         * neste caso, terminar a implementação das mensagens de retorno.
1208                                         */
1209                                        if ($index !== 'error'){
1210                                                $final[3][$i][0] = $contact['companies']['company1']['company_name']?$contact['companies']['company1']['company_name']:'none';
1211                                                if($this->page_info['actual_catalog']['class']!='bo_global_ldap_catalog'){
1212                                                        $final[3][$i][1] = $contact['names_ordered'] ? urldecode($contact['names_ordered'])  : 'none';
1213                                                }
1214                                                else {
1215                                                        $contact['names_ordered'][0] = urldecode($contact['names_ordered'][0]);
1216                                                        $final[3][$i][1] = $contact['names_ordered'] ? $contact['names_ordered']  : 'none';
1217                                                }
1218                                                $final[3][$i][2] = $contact['companies']['company1']['title']? urldecode( $contact['companies']['company1']['title'] ) :'none';
1219
1220                                                /* Select the correct Email and Telephone to be shown */
1221                                                $preferences = ExecMethod('contactcenter.ui_preferences.get_preferences');
1222                                               
1223                                                if (!is_array($preferences))
1224                                                {
1225                                                        $preferences['personCardEmail'] = 1;
1226                                                        $preferences['personCardPhone'] = 2;
1227                                                }
1228                                                if ($contact['connections'])
1229                                                {
1230                                                        $default_email_found = false;
1231                                                        $default_phone_found = false;
1232                                                        foreach($contact['connections'] as $conn_info)
1233                                                        {
1234                                                                if ($conn_info['id_type'] == $preferences['personCardEmail'] and !$default_email_found)
1235                                                                {
1236                                                                        if ($conn_info['connection_is_default'])
1237                                                                        {
1238                                                                                $default_email_found = true;
1239                                                                        }
1240                                                                        $final[3][$i][4] = $conn_info['connection_value'] ? $conn_info['connection_value'] : 'none';
1241                                                                }
1242                                                                else if ($conn_info['id_type'] == $preferences['personCardPhone'] and !$default_phone_found)
1243                                                                {
1244                                                                        if ($conn_info['connection_is_default'])
1245                                                                        {
1246                                                                                $default_phone_found = true;
1247                                                                        }
1248                                                                        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){
1249                                                                                $conn_info['connection_value'] = "<a title=\"".lang("Call Extension")."\" href=\"#\" onclick=\"connectVoip('".$conn_info['connection_value']."', 'com')\">".$conn_info['connection_value']."</a>";
1250                                                                        }
1251                                                                        $final[3][$i][3] = $conn_info['connection_value'] ? $conn_info['connection_value'] : 'none';
1252                                                                }
1253                                                        }
1254                                                }
1255                                               
1256                                                if (!$final[3][$i][3])
1257                                                {
1258                                                        $final[3][$i][3] = 'none';
1259                                                }
1260
1261                                                if (!$final[3][$i][4])
1262                                                {
1263                                                        $final[3][$i][4] = 'none';
1264                                                }
1265
1266                                                $final[3][$i][5] = $contact['alias']? urldecode( $contact['alias'] ):'none';
1267                                                $final[3][$i][6] = $ids[$i];
1268
1269                                        //      If contact is a public list or a group, then load the forwarding addresses.
1270                                                if($contact['account_type'][0] == 'l' || $contact['account_type'][0] == 'g')
1271                                                        $final[3][$i][7] = ($contact['account_type'][0] == 'l' ? 'list' : 'group');
1272                                                       
1273                                                if($this->page_info['actual_catalog']['class']=='bo_shared_people_manager') {
1274                                                        $final[3][$i][8] = $perms[$i];
1275                                                        $final[3][$i][9] = lang('Shared').": ".$owner_names[$owners[$i]]['cn'];
1276                                                }
1277
1278                                                $final[4][$i] = $contact['photo'] ? 1  : 0;
1279                                        //      print_r($final[3][$i]);
1280                                        //      exit;
1281                                                $i++;
1282                                        }
1283                                        else
1284                                        {
1285                                                // coloca mensagem de erro no vetor que retorna para o browser
1286                                        }
1287                                       
1288                                }
1289                                $lnk_compose = "location.href=('../expressoMail1_2/index.php?to=";
1290                                $final[5] = '<span class="link" onclick="'.$lnk_compose;
1291
1292
1293                                $this->page_info['actual_letter'] = $letter;
1294                                $this->page_info['actual_page'] = $page;
1295                               
1296                                $this->save_session();                         
1297                                echo serialize($final);
1298                                return;
1299                        }
1300                       
1301                        $this->page_info['actual_letter'] = $letter;
1302                        $this->page_info['actual_page'] = $page;
1303                       
1304                        $this->save_session();
1305                       
1306                        $final[0] = 0;
1307                        $final[1] = $this -> typeContact;
1308                        echo serialize($final);
1309                }
1310               
1311                function get_visible_all_ldap()
1312                {
1313                        $bo = CreateObject('contactcenter.bo_ldap_manager');
1314                        $ldap_query = $bo->srcs;
1315                        return $ldap_query[1]['visible'];       
1316                }
1317
1318 
1319                /*!
1320               
1321                        @function get_group_data
1322                        @abstract Returns all the information of a given Group
1323                        @author Nilton Emilio Buhrer Neto
1324                       
1325                        @param (integer) $id The id to get information
1326               
1327                */             
1328                function get_group_data($id,$shared_from=null)
1329                {
1330                        $this->bo->catalog = CreateObject('contactcenter.bo_group_manager');
1331                        $fields = $this->bo->catalog->get_fields(true);
1332                        $data = $this->bo->catalog->get_single_entry($id,$fields);
1333                       
1334                        if($id) {                       
1335                                // get All Contacts by group.
1336                                $data['contact_in_list'] = $this->bo->catalog->get_contacts_by_group($id);                                                             
1337                        }
1338                       
1339                        $boGroup = CreateObject('contactcenter.bo_group');
1340                                               
1341                        $all_contacts = $boGroup->get_all_contacts('only_email',$shared_from);
1342                       
1343                        $contact_options = "";
1344                        if(count($all_contacts)) {                                     
1345                                foreach($all_contacts as $idx => $contact) {                           
1346                                        $contact_options .= "<OPTION value='".$contact['id_connection']."'>".$contact['names_ordered']." (".$contact['connection_value'].")</OPTION>";
1347                                }
1348                        }
1349                        $data['contact_list'] = $contact_options;                       
1350                        $data['result'] = 'ok';
1351                                                                                       
1352                        echo serialize($data);                 
1353                }               
1354               
1355                /*!
1356               
1357                        @function get_full_data
1358                        @abstract Returns all the information of a given Entry
1359                        @author Raphael Derosso Pereira
1360                       
1361                        @param (integer) $id The id to get information
1362               
1363                */
1364                function get_full_data($id,$catalog='bo_people_catalog')
1365                {
1366                        $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
1367                        $this->bo->catalog = CreateObject('contactcenter.'.$catalog);           
1368                        $fields = $this->bo->catalog->get_fields(true);
1369                        $fields['photo'] = false;
1370                        $entry = $this->bo->catalog->get_single_entry($id,$fields);
1371
1372                        if (is_bool($entry['given_names']))
1373                        {
1374                                $data['result'] = 'false';
1375                                echo serialize($data);
1376                                return;
1377                        }
1378
1379                        $date = explode('-', $entry['birthdate']);
1380                        $j = 0;
1381                        for ($i = 0; $i < 5; $i+=2)
1382                        {
1383                                switch($dateformat{$i})
1384                                {
1385                                        case 'Y':
1386                                                $birthdate[$j] = $date[0];
1387                                                break;
1388
1389                                        case 'm':
1390                                        case 'M':
1391                                                $birthdate[$j] = $date[1];
1392                                                break;
1393
1394                                        case 'd':
1395                                                $birthdate[$j] = $date[2];
1396                                }
1397                                $j++;
1398                        }
1399                        $datecount = 0;
1400                       
1401                        $data['result'] = 'ok';
1402                        $data['cc_full_add_contact_id'] = $id;
1403
1404                        /* Personal Data */
1405                        $data['personal']['cc_pd_photo'] = '../index.php?menuaction=contactcenter.ui_data.data_manager&method=get_photo&id='.$id;
1406                        $data['personal']['cc_pd_alias'] = $entry['alias'];
1407                        $data['personal']['cc_pd_given_names'] = $entry['given_names'];
1408                        $data['personal']['cc_pd_family_names'] = $entry['family_names'];
1409                        $data['personal']['cc_pd_full_name'] = $entry['names_ordered'];
1410                        $data['personal']['cc_pd_suffix'] = $entry['id_suffix'];
1411                        $data['personal']['cc_pd_birthdate_0'] = $birthdate[0];
1412                        $data['personal']['cc_pd_birthdate_1'] = $birthdate[1];
1413                        $data['personal']['cc_pd_birthdate_2'] = $birthdate[2];
1414                        //$data['personal']['cc_pd_sex'] = $entry['sex'] === 'M' ? 1 : ($entry['sex'] === 'F' ? 2 : 0);
1415                        $data['personal']['cc_pd_prefix'] = $entry['id_prefix'];
1416                        $data['personal']['cc_pd_gpg_finger_print'] = $entry['pgp_key'];
1417                        $data['personal']['cc_pd_notes'] = $entry['notes'];
1418
1419                        /* Addresses */
1420                        if (is_array($entry['addresses']))
1421                        {
1422                                $data['addresses'] = $entry['addresses'];
1423                        }
1424
1425                        /* Connections */
1426                        if (is_array($entry['connections']))
1427                        {
1428                                $data['connections'] = array();
1429                                foreach ($entry['connections'] as $connection)
1430                                {
1431                                        $type = $connection['id_type'];
1432                                        $i = count($data['connections'][$type]);
1433                                        $data['connections'][$type][$i]['id'] = $connection['id_connection'];
1434                                        $data['connections'][$type][$i]['name'] = $connection['connection_name'];
1435                                        $data['connections'][$type][$i]['value'] = $connection['connection_value'];
1436                                        $data['connections'][$type][$i]['is_default'] = $connection['connection_is_default'];
1437                                }
1438                        }
1439//                      print_r($data);
1440
1441                        /* Relations */
1442                       
1443                        echo serialize($data);
1444                }
1445
1446                /*!
1447
1448                        @function get_contact_full_add_const
1449                        @abstract Returns all the constant fields in Contact Full Add Window to the JS
1450                        @author Raphael Derosso Pereira
1451                */
1452                function get_contact_full_add_const()
1453                {
1454                        $data = array();
1455                        $boPeopleCatalog = CreateObject('contactcenter.bo_people_catalog');
1456                        $predata[] = $boPeopleCatalog -> get_all_prefixes();
1457                        $predata[] = $boPeopleCatalog -> get_all_suffixes();
1458                        $predata[] = $boPeopleCatalog -> get_all_addresses_types();
1459                        $predata[] = $boPeopleCatalog -> get_all_countries();
1460                        $predata[] = $boPeopleCatalog -> get_all_connections_types();
1461                        //$predata[] = $this->bo->catalog->get_all_relations_types();
1462
1463                        $i = 0;
1464                        foreach($predata as $data_)
1465                        {
1466                                if ($data_)
1467                                {
1468                                        $data[$i] = $data_;
1469                                }
1470
1471                                $i++;
1472                        }
1473
1474                        if (count($data))
1475                        {
1476                                echo serialize($data);
1477                                return;
1478                        }
1479                       
1480                        echo 0;
1481                }
1482               
1483                /*!
1484               
1485                        @function quick_add
1486                        @abstract Adds a new Contact using the Quick Add interface
1487                        @author Raphael Derosso Pereira
1488                       
1489                        @param string $sdata Serialized data
1490                */
1491                function quick_add($sdata)
1492                {
1493                       
1494                        $sdata = str_replace('\\"', '"', $sdata);
1495                        $new_array = unserialize($sdata);
1496                        $tdata = array();
1497                       
1498                        foreach($new_array as $tmp)
1499                                $tdata[] = $tmp;
1500                       
1501                        if (!$tdata)
1502                        {
1503                                echo serialize(array(
1504                                        'msg'    => lang('Problems on adding your Contact. Invalid Data came from client. No Contact added!'),
1505                                        'status' => 'abort'
1506                                ));
1507                               
1508                                return;
1509                        }
1510                       
1511                        // verifica se email já existe!
1512                        $boGroup = CreateObject('contactcenter.bo_group');
1513                        $contact = $boGroup->verify_contact($tdata[4]);
1514                                                                                               
1515                        if($contact)
1516                        {                                                       
1517                                $str_contact = "\r\n - ".implode("\r\n - ",$contact);
1518                               
1519                                echo serialize(array(
1520                                        'msg'    => lang('Problems on adding your Contact. The email "%1" already exists in: %2',$tdata[4], $str_contact),
1521                                        'status' => 'alreadyExists'
1522                                ));
1523                               
1524                                return;                 
1525                        }
1526
1527                        $data['alias'] = $tdata[0];
1528                        $data['given_names'] = $tdata[1];
1529                        $data['family_names'] = $tdata[2];
1530//                      $data['connections']['default_phone']['id_typeof_connection'] = 1;
1531                        $data['connections']['default_phone']['connection_name'] = lang('Main');
1532                        $data['connections']['default_phone']['connection_value'] = $tdata[3];
1533//                      $data['connections']['default_email']['id_typeof_connection'] = 2;
1534                        $data['connections']['default_email']['connection_name'] = lang('Main');
1535                        $data['connections']['default_email']['connection_value'] = $tdata[4];
1536                        $boPeople = CreateObject('contactcenter.bo_people_catalog');
1537
1538                        if ($boPeople ->quick_add($data))
1539                        {                               
1540                                $this->page_info['changed'] = true;
1541                               
1542                                echo serialize(array(
1543                                        'msg'    => lang('Entry added with success!'),
1544                                        'status' => 'ok'
1545                                ));
1546                        }
1547                        else
1548                        {
1549                                echo serialize(array(
1550                                        'msg'    => lang('Problems on adding your Contact. No Contact added!'),
1551                                        'status' => 'error'
1552                                ));
1553                        }
1554
1555                        $this->save_session(); 
1556                       
1557                }
1558
1559                /*!
1560               
1561                        @function add_group
1562                        @abstract Adds a new Group using the Add Group interface
1563                        @author Nilton Emilio Buhrer Neto
1564                       
1565                        @param string $sdata Serialized data
1566                */
1567                function add_group($sdata)
1568                {
1569                        $sdata = str_replace('\\"', '"', $sdata);
1570                        $tdata = unserialize($sdata);
1571                        $new_tdata = array();
1572                       
1573                        if (!$tdata)
1574                        {
1575                                echo serialize(array(
1576                                        'msg'    => lang('Problems on adding your Contact. Invalid Data came from client. No Contact added!'),
1577                                        'status' => 'abort'
1578                                ));
1579                               
1580                                return;
1581                        }
1582                       
1583                        foreach($tdata as $tmp)
1584                                $new_tdata[] = $tmp;
1585                       
1586                        $data['title'] = $new_tdata[0];                 
1587                        $data['contact_in_list'] = $new_tdata[1];
1588                        $data['id_group'] = $new_tdata[2];
1589                                               
1590                        $boGroup = CreateObject('contactcenter.bo_group_manager');
1591                        $id = $boGroup -> add_group($data);
1592                       
1593                        if ($id)
1594                        {
1595                                $this->page_info['changed'] = true;
1596                               
1597                                echo serialize(array(
1598                                        'msg'    => lang('Entry added with success!'),
1599                                        'status' => 'ok'
1600                                ));
1601                        }
1602                        else
1603                        {
1604                                echo serialize(array(
1605                                        'msg'    => lang('Problems on adding your Contact. No Contact added!'),
1606                                        'status' => 'error'
1607                                ));
1608                        }
1609
1610                        $this->save_session();
1611                }
1612
1613                /*!
1614               
1615                        @function remove_group
1616                        @abstract Removes a group if the user has the right to do it
1617                        @author Nilton Emilio Buhrer Neto                       
1618                        @param (integer) $id The id to be removed
1619                               
1620                */
1621                function remove_group($id)
1622                {                               
1623                                $soGroup = CreateObject('contactcenter.so_group');                             
1624                                $data = array ('id_group' => $id);
1625                                if($soGroup -> delete($data)) {
1626                                        echo serialize(array(
1627                                                'msg'    => lang('Removed Entry ID '.$id.'!'),
1628                                                'status' => 'ok'
1629                                        ));                                                     
1630                                }
1631                                else {
1632                                        echo serialize(array(
1633                                                'msg'    => lang('Problems on adding your Contact. No Contact added!'),
1634                                                'status' => 'error'
1635                                        ));
1636                                }
1637
1638                        $this->save_session();                         
1639                }
1640
1641
1642                function remove_all_entries (){
1643               
1644                        $error = false;
1645                        $this->all_entries = $this->bo->catalog->get_all_entries_ids();
1646
1647                        foreach($this->all_entries as $index => $id) {
1648                                $result = $this->bo->catalog->remove_single_entry($id);
1649                                if(!$result) {
1650                                        $error = true;
1651                                        break;         
1652                                }
1653                        }
1654
1655                        if(!$error) {
1656                                echo serialize(array(
1657                                        'msg'    => lang('Removed Entry ID '.$id.'!'),
1658                                        'status' => 'ok'
1659                                ));
1660                        }
1661                        else {
1662                                echo serialize(array(
1663                                        'msg'    => lang('Couldn\'t remove this entry. Inform the Site Admin!'),
1664                                        'status' => 'fail'
1665                                ));
1666                        }
1667
1668                        $this->save_session();
1669                }
1670
1671                /*!
1672               
1673                        @function remove_entry
1674                        @abstract Removes an entry if the user has the right to do it
1675                        @author Raphael Derosso Pereira
1676                       
1677                        @param (integer) $id The id to be removed
1678                               
1679                */
1680                function remove_entry ($id)
1681                {
1682                        if (!is_int($id))
1683                        {
1684                                echo lang('Couldn\'t remove entry! Problem passing data to the server. Please inform admin!');
1685                                return;
1686                        }
1687                       
1688                        $this->page_info['changed'] = true;
1689                        $result = $this->bo->catalog->remove_single_entry($id);
1690                       
1691                        if ($result)
1692                        {
1693                                if ($pos = array_search($id, $this->page_info['actual_entries']))
1694                                {
1695                                        unset($this->page_info['actual_entries'][$pos]);
1696                                }
1697                               
1698                                $temp = false;
1699                                reset($this->page_info['actual_entries']);
1700                                foreach($this->page_info['actual_entries'] as $t)
1701                                {
1702                                        $temp[] = $t;
1703                                }
1704                               
1705                                $this->page_info['actual_entries'] = $temp;
1706
1707                                echo serialize(array(
1708                                        'msg'    => lang('Removed Entry ID '.$id.'!'),
1709                                        'status' => 'ok'
1710                                ));
1711                        }
1712                        else
1713                        {
1714                                echo serialize(array(
1715                                        'msg'    => lang('Couldn\'t remove this entry. Inform the Site Admin!'),
1716                                        'status' => 'fail'
1717                                ));
1718                        }
1719                       
1720                        $this->save_session();
1721                }
1722
1723               
1724                /*!
1725               
1726                        @function post_full_add
1727                        @abstract Saves all the information altered/entered in the Full Add
1728                                window
1729                        @author Raphael Derosso Pereira
1730
1731                */
1732                function post_full_add()
1733                {
1734                        $data =  $_POST['data'];
1735                        // Exceptions!!! utf8 special chars.
1736                        $data = preg_replace("/\%u2(\d+)(\d+)(\d+)/","-",$data);
1737                        $data = unserialize(str_replace('\\"', '"', $data));
1738                        $this -> bo -> catalog = CreateObject('contactcenter.bo_people_catalog');
1739
1740                        if (!is_array($data))
1741                        {
1742                                echo serialize(array(
1743                                        'msg' => lang('<p>Some problem receiving data from browser. This is probably a bug in ContactCenter<br>'.
1744                                                  'Please go to eGroupWare Bug Reporting page and report this bug.<br>'.
1745                                                          'Sorry for the inconvenient!<br><br>'.
1746                                                          '<b><i>ContactCenter Developer Team</i></b></p>'),
1747                                        'status' => 'fatal'
1748                                ));
1749                                return;
1750                        }
1751//                      print_r($data);
1752//                      echo '<br><br>';
1753
1754                        $replacer = $data['commercialAnd'];
1755                        unset($data['commercialAnd']);
1756                        if (!is_string($replacer) or strpos($replacer, "'") or strpos($replacer, '"'))
1757                        {
1758                                echo serialize(array(
1759                                        'msg' => lang('Invalid \'&\' replacer! This may be an attempt to bypass Security! Action aborted!'),
1760                                        'status' => 'fatal'
1761                                ));
1762                               
1763                                return;
1764                        }
1765
1766                        if ($data['id_contact'])
1767                        {
1768                                $id = $data['id_contact'];
1769                                $id_photo = $id;
1770                                unset($data['id_contact']);
1771                        }
1772                        else
1773                        {
1774                                $id_photo = '_new_';
1775                        }
1776                       
1777                        /*
1778                         * Process Photo, if available
1779                         */
1780                        $sleep_count = 0;
1781                        $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
1782                        while($photo_ok[0]{0} !== 'o' and $photo_ok[1]{0} === 'y')
1783                        {
1784                                sleep(1);
1785                                $photo_ok = $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter');
1786                                $sleep_count++;
1787
1788                                if ($sleep_count > 35)
1789                                {
1790                                        // TODO
1791                                        return;
1792                                }
1793                        }
1794                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'n'));
1795                       
1796                        if (isset($this->page_info['photos'][$id_photo]))
1797                        {
1798                                if (array_search($this->page_info['photos'][$id_photo]['status'], array('changed', 'sync')) === false)
1799                                {
1800                                        echo serialize(array(
1801                                                'msg' => $this->page_info['photos'][$id_photo]['msg'],
1802                                                'status' => $this->page_info['photos'][$id_photo]['status']
1803                                        ));
1804
1805                                        return;
1806                                }
1807
1808                                $data['photo'] = $this->page_info['photos'][$id_photo]['content'];
1809                                unset($this->page_info['photos'][$id_photo]);
1810                                $this->save_session();
1811                        }
1812                       
1813                        /*
1814                         * Arrange Date so it gets inserted correctly
1815                         */
1816                         
1817                        $dateformat = $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'];
1818               
1819                        $j = 0;
1820                        for ($i = 0; $i < 5; $i+=2)
1821                        {
1822                                switch($dateformat{$i})
1823                                {
1824                                        case 'Y':
1825                                                $date[$j]['size'] = 4;
1826                                                $date[$j]['digit'] = 'Y';
1827                                                break;
1828
1829                                        case 'm':
1830                                        case 'M':
1831                                                $date[$j]['size'] = 2;
1832                                                $date[$j]['digit'] = 'M';
1833                                                break;
1834
1835                                        case 'd':
1836                                                $date[$j]['size'] = 2;
1837                                                $date[$j]['digit'] = 'D';
1838                                }
1839                                $j++;
1840                        }
1841                        $datecount = 0;
1842
1843                        /* Verify Data and performs insertion/update */
1844                        foreach($data as $field => $value)
1845                        {
1846                                if ($value == '' or is_null($value))
1847                                {
1848                                        unset($data[$field]);
1849                                        continue;
1850                                }
1851                                switch($field)
1852                                {
1853                                        case 'names_ordered':
1854                                                $data[$field] = urldecode($value);
1855                                        case 'alias':
1856                                        case 'given_names':
1857                                        case 'family_names':
1858                                        case 'pgp_key':
1859                                        case 'notes':                                   
1860                                                $data[$field] = urldecode($data[$field]);
1861                                                break;
1862                                        case 'id_status':
1863                                        case 'id_prefix':
1864                                        case 'id_suffix':
1865                                                if ($data[$field] == 0)
1866                                                {
1867                                                        unset($data[$field]);
1868                                                }
1869                                                break;
1870                                       
1871                                        case 'birthdate_0':
1872                                        case 'birthdate_1':
1873                                        case 'birthdate_2':
1874                                       
1875                                                switch($date[$datecount]['digit'])
1876                                                {
1877                                                        case 'Y':
1878                                                                $date['value'][2] = (int) $data[$field];
1879                                                                break;
1880
1881                                                        case 'M':
1882                                                                $date['value'][0] = (int) $data[$field];
1883                                                                break;
1884
1885                                                        case 'D':
1886                                                                $date['value'][1] = (int) $data[$field];
1887                                                                break;
1888                                                }
1889                                                unset($data[$field]);
1890                                                $datecount++;
1891
1892                                                if ($datecount != 3)
1893                                                {
1894                                                        break;
1895                                                }
1896                                               
1897                                                if (!checkdate($date['value'][0], $date['value'][1], $date['value'][2]))
1898                                                {
1899                                                        echo serialize(array(
1900                                                                'msg' => lang('Invalid Date'),
1901                                                                'status' => 'invalid_data'
1902                                                        ));
1903                                                        return;
1904                                                }
1905                                               
1906                                                $data['birthdate'] = $date['value'][2].'-'.$date['value'][0].'-'.$date['value'][1];
1907                                                break;
1908
1909                                        case 'sex':
1910                                                if ($data[$field] !== 'M' and $data[$field] !== 'F')
1911                                                {
1912                                                        echo serialize(array(
1913                                                                'msg' => lang('Invalid Sex'),
1914                                                                'status' => 'invalid_data'
1915                                                        ));
1916                                                        return;
1917                                                }
1918                                                break;
1919
1920
1921                                        case 'addresses':
1922                                                /* Insert new cities/states */
1923                                                if (isset($value['new_states']))
1924                                                {
1925                                                        foreach($value['new_states'] as $type => $state_info)
1926                                                        {
1927                                                                $index = 'address'.$type;
1928                                                               
1929                                                                $id_state = $this->bo->catalog->add_state($state_info);
1930                                                                $data['addresses'][$index]['id_state'] = $id_state;
1931
1932                                                                if ($value['new_cities'][$type])
1933                                                                {
1934                                                                        $data[$field]['new_cities'][$type]['id_state'] = $id_state;
1935                                                                }
1936                                                        }
1937
1938                                                        unset($data['addresses']['new_states']);
1939                                                }
1940
1941                                                if (isset($value['new_cities']))
1942                                                {
1943                                                        foreach($value['new_cities'] as $type => $city_info)
1944                                                        {
1945                                                                $index = 'address'.$type;
1946                                                               
1947                                                                $id_city = $this->bo->catalog->add_city($city_info);
1948                                                                $data['addresses'][$index]['id_city'] = $id_city;
1949                                                        }
1950
1951                                                        unset($data['addresses']['new_cities']);
1952                                                }
1953
1954                                        break;
1955
1956                                        case 'connections':
1957                                        case 'photo':
1958                                                /* Does nothing... */
1959                                                break;
1960
1961                                        default:
1962                                                echo serialize(array(
1963                                                        'msg' => lang('Invalid field: ').$field,
1964                                                        'status' => 'invalid_data'
1965                                                ));
1966                                                return;
1967                                }
1968                        }
1969
1970                        if (!is_null($id) and $id !== '')
1971                        {
1972                                $id = $this->bo->catalog->update_single_info($id, $data);
1973                                $result = array(
1974                                        'msg' => lang('Updated Successfully!'),
1975                                        'status' => 'ok'
1976                                );
1977                        }
1978                        else
1979                        {
1980                                $id = $this->bo->catalog->add_single_entry($data);
1981                                $result = array(
1982                                        'msg' => lang('Entry Added Successfully!'),
1983                                        'status' => 'ok'
1984                                );
1985                        }
1986
1987                        if (!($id))
1988                        {
1989                                $result = array(
1990                                        'msg' => lang('Some problem occured when trying to insert/update contact information.<br>'.
1991                                                   'Report the problem to the Administrator.'),
1992                                        'status' => 'fail'
1993                                );
1994                        }
1995
1996                        echo serialize($result);
1997                }
1998
1999                /*!
2000               
2001                        @function post_photo
2002                        @abstract Wrapper to post a photo without reload a page.
2003                        @author Raphael Derosso Pereira
2004
2005                */
2006                function post_photo($id)
2007                {
2008                        //print_r($_FILES);
2009                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('wait', 'y'));
2010                       
2011                        if (!is_array($_FILES) and is_array(!$_FILES['cc_pd_photo']))
2012                        {
2013                                $this->page_info['photos'][$id]['status'] = 'no_upload';
2014                                $this->page_info['photos'][$id]['msg'] = lang('No Photos uploaded to Server.');
2015                               
2016                                $this->save_session();
2017                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2018                                return;
2019                        }
2020
2021                        if (!function_exists('imagecreate'))
2022                        {
2023                                $this->page_info['photos'][$id]['status'] = 'no_GD_lib';
2024                                $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.');
2025                               
2026                                $this->save_session();
2027                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2028                                return;
2029                        }
2030
2031                        // TODO: Get Max Size from preferences!
2032                        if ($_FILES['cc_pd_photo']['size'] > 1000000)
2033                        {
2034                                $this->page_info['photos'][$id]['status'] = 'too_large';
2035                                $this->page_info['photos'][$id]['msg'] = lang('Image too large! ContactCenter limits the image size to 1 Mb');
2036
2037                                $this->save_session();
2038                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2039                                return;
2040                        }
2041
2042                        if ($_FILES['cc_pd_photo']['error'])
2043                        {
2044                                $this->page_info['photos'][$id]['status'] = 'error';
2045                                $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'];
2046
2047                                $this->save_session();
2048                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2049                                return;
2050                        }
2051                       
2052                        switch($_FILES['cc_pd_photo']['type'])
2053                        {
2054                                case 'image/jpeg':
2055                                case 'image/pjpeg':
2056                                        $src_img = imagecreatefromjpeg($_FILES['cc_pd_photo']['tmp_name']);
2057                                        if ($src_img == '')
2058                                        {
2059                                                $bogus = true;
2060                                        }
2061                                        break;
2062
2063                                case 'image/png':
2064                                case 'image/x-png':
2065                                        $src_img = imagecreatefrompng($_FILES['cc_pd_photo']['tmp_name']);
2066                                        if ($src_img == '')
2067                                        {
2068                                                $bogus = true;
2069                                        }
2070                                        break;
2071
2072                                case 'image/gif':
2073                                        $src_img = imagecreatefromgif($_FILES['cc_pd_photo']['tmp_name']);
2074                                        if ($src_img == '')
2075                                        {
2076                                                $bogus = true;
2077                                        }
2078                                        break;
2079
2080                                default:
2081                                       
2082                                        $this->page_info['photos'][$id]['status'] = 'invalid_image';
2083                                        $this->page_info['photos'][$id]['msg'] = lang('The file must be an JPEG, PNG or GIF Image.');
2084
2085                                        $this->save_session();
2086                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2087                                        return;
2088                        }
2089
2090                        if ($bogus)
2091                        {
2092                                        $this->page_info['photos'][$id]['status'] = 'invalid_file';
2093                                        $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
2094                                       
2095                                        $this->save_session();
2096                                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2097                                        return;
2098                        }
2099                       
2100                        $img_size = getimagesize($_FILES['cc_pd_photo']['tmp_name']);
2101                        $dst_img = imagecreatetruecolor(60, 80);
2102                       
2103                        if (!imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, 60, 80, $img_size[0], $img_size[1]))
2104                        {
2105                                $this->page_info['photos'][$id]['status'] = 'invalid_file';
2106                                $this->page_info['photos'][$id]['msg'] = lang('Couldn\'t open Image. It may be corrupted or internal library doesn\'t support this format.');
2107                               
2108                                $this->save_session();
2109                                $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2110                                return;
2111                        }
2112                       
2113                        ob_start();
2114                        imagepng($dst_img);
2115                        $this->page_info['photos'][$id]['content'] = ob_get_contents();
2116                        ob_end_clean();
2117
2118                        $this->page_info['photos'][$id]['status'] = 'changed';
2119                        $this->page_info['photos'][$id]['msg'] = lang('Photo Successfully Updated!');
2120
2121                        $this->save_session();
2122               
2123                        $GLOBALS['phpgw']->session->appsession('ui_data.photo','contactcenter', array('ok', 'y'));
2124
2125                        imagedestroy($src_img);
2126                        imagedestroy($dst_img);
2127                        echo 'ok';
2128                        return;
2129                }
2130
2131
2132                /*!
2133
2134                        @function get_photo
2135                        @abstract Returns the photo to the browser
2136                        @author Raphael Derosso Pereira
2137
2138                */
2139                function get_photo($id)
2140                {
2141                        $fields = $this->bo->catalog->get_fields(false);
2142                        $fields['photo'] = true;
2143                       
2144                        $contact = $this->bo->catalog->get_single_entry($id, $fields);
2145
2146                        if (!$contact['photo'])
2147                        {
2148                                header('Content-type: image/png');
2149                                echo file_get_contents(PHPGW_INCLUDE_ROOT.'/contactcenter/templates/default/images/photo_celepar.png');
2150                                return;
2151                        }
2152                       
2153                        header('Content-type: image/jpeg');
2154                        $photo = imagecreatefromstring ($contact['photo']);
2155                        $width = imagesx($photo);
2156                        $height = imagesy($photo);
2157                        $twidth = 70;
2158                        $theight = 90;
2159                        $small_photo = imagecreatetruecolor ($twidth, $theight);
2160                        imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
2161                        imagejpeg($small_photo,"",100);
2162                        return;
2163                }
2164               
2165                /*!
2166               
2167                        @function get_states
2168                        @abstract Echos a serialized array containing all the states for the given country
2169                        @author Raphael Derosso Pereira
2170
2171                        @params $id_country The ID of the Country that contains the requested states
2172
2173                */
2174                function get_states($id_country)
2175                {
2176                        $states = $this->bo->catalog->get_all_states($id_country);
2177
2178                        if (!$states)
2179                        {
2180                                $result = array(
2181                                        'msg'    => lang('No States found for this Country.'),
2182                                        'status' => 'empty'
2183                                );
2184
2185                                echo serialize($result);
2186                                return;
2187                        }
2188                       
2189                        $result = array(
2190                                'msg'    => lang('States Successfully retrieved!'),
2191                                'status' => 'ok'
2192                        );
2193                       
2194                        foreach ($states as $state_info)
2195                        {
2196                                $result['data'][$state_info['id_state']] = $state_info['name'];
2197
2198                                if ($state_info['symbol'])
2199                                {
2200                                        $result['data'][$state_info['id_state']] .= ', '.$state_info['symbol'];
2201                                }
2202                        }
2203
2204                        echo serialize($result);
2205                }
2206
2207                /*!
2208
2209                        @function get_cities
2210                        @abstract Echos a serialized array containing all the cities of a given state
2211                        @author Raphael Derosso Pereira
2212
2213                        @param $id_country The ID of the Country that has the specified Cities (in case the
2214                                Country doesn't have any States)
2215                        @param $id_state The ID of the State that has the Cities requested
2216
2217                */
2218                function get_cities($id_country, $id_state=false)
2219                {
2220                        $cities = $this->bo->catalog->get_all_cities($id_country, $id_state);
2221
2222                        if (!$cities)
2223                        {
2224                                $result = array(
2225                                        'msg'    => lang('No Cities found for this State.'),
2226                                        'status' => 'empty'
2227                                );
2228
2229                                echo serialize($result);
2230                                return;
2231                        }
2232                       
2233                        $result = array(
2234                                'msg'    => lang('Cities Successfully retrieved!'),
2235                                'status' => 'ok'
2236                        );
2237                       
2238                        foreach ($cities as $city_info)
2239                        {
2240                                $result['data'][$city_info['id_city']] = $city_info['name'];
2241                        }
2242                       
2243                        echo serialize($result);
2244                }
2245
2246
2247                /*!
2248               
2249                        @function search
2250                        @abstract Echos a serialized array containing the IDs
2251                                of the entries that matches the search argument
2252                        @author Raphael Derosso Pereira
2253                        @author Mário César Kolling (external catalogs)
2254
2255                        @param string $str_data A serialized array with two informations:
2256                                $data = array(
2257                                        'search_for' => (string),
2258                                        'recursive'  => (boolean),
2259                                );
2260
2261                */
2262                // SERPRO
2263                function search($str_data)
2264                {
2265                        $data = unserialize($str_data);
2266                        // It's an external catalog?
2267                        $external = $this->bo->is_external($this->page_info['actual_catalog']);
2268                       
2269            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
2270            {
2271                echo serialize(array(                                                                                                   
2272                   'msg'    => lang('Invalid parameters'),                                                                             
2273                    'status' => 'abort'
2274                ));
2275           
2276                return array('error' => lang('Invalid parameters'));                                                                                                                 
2277            }   
2278
2279           
2280                        /*
2281                         * TODO: look into the database to discover the database's encoding and convert the search_for field accordingly
2282                         */
2283                        // Support search parameters with accentuation
2284                        if ($this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
2285                                $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
2286                                $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&
2287                                $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
2288                        {
2289
2290                                $data['search_for'] = utf8_encode($data['search_for']);
2291                        }
2292           
2293            $rules  = array();                                                                                                         
2294           
2295           
2296            if ($data['search_for'] === '*')                                                                                           
2297            {
2298                $rules = array(                                                                                                         
2299                    0 => array(                                                                                                         
2300                        'field' => $data['fields']['search'],                                                                           
2301                        'type'  => 'LIKE',
2302                        'value' => '%'
2303                    )   
2304                ); 
2305            }   
2306            else                                                                                                                       
2307            {
2308                $names = explode(' ', $data['search_for']);                                                                             
2309               
2310                if (!is_array($names))                                                                                                 
2311                {
2312                    echo serialize(array(                                                                                               
2313                        'msg'    => lang('Invalid Search Parameter'),                                                                   
2314                        'status' => 'abort'
2315                    ));
2316 
2317                }
2318
2319                                if (!$external && $this->page_info['actual_catalog']['class'] != 'bo_people_catalog' &&
2320                                        $this->page_info['actual_catalog']['class'] != 'bo_group_manager' &&
2321                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' &&                                   
2322                                        $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager' )
2323                                {
2324                                        /*
2325                                         * Restrict the returned contacts search to objectClass = phpgwAccount,
2326                                         * must have attibute phpgwAccountStatus, phpgwAccountVisible != -1
2327                                         */
2328                                        $rules = array(
2329                                                0 => array(
2330                                                        'field' => 'contact.object_class',
2331                                                        'type'  => '=',
2332                                                        'value' => 'phpgwAccount'
2333                                                ),
2334                                                1 => array(
2335                                                        'field' => 'contact.account_status',
2336                                                        'type'  => 'iLIKE',
2337                                                        'value' => '%'
2338                                                ),
2339                                                2 => array(
2340                                                        'field' => 'contact.account_visible',
2341                                                        'type'  => '!=',
2342                                                        'value' => '-1'
2343                                                ),
2344                                        );
2345                                }
2346               
2347                foreach ($names as $name)
2348                {
2349                    if ($name != '')
2350                    {
2351                        array_push($rules, array(
2352                            'field' => $data['fields']['search'],
2353                            'type'  => 'iLIKE',
2354                            'value' => '%'.$name.'%'
2355                        ));
2356                    }
2357                }
2358            }
2359
2360                        if ($external || $this->page_info['actual_catalog']['class'] == 'bo_people_catalog' ||
2361                                $this->page_info['actual_catalog']['class'] == 'bo_group_manager' ||
2362                                $this->page_info['actual_catalog']['class'] == 'bo_shared_people_manager' ||
2363                                $this->page_info['actual_catalog']['class'] == 'bo_shared_group_manager'        )
2364                        {
2365                                // Get only this attributes: dn, cn for external catalogs,
2366                                // used to restrict the attributes used in filters
2367                                $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
2368                        }
2369                        else
2370                        {
2371                                // Get only this attributes: dn, cn, phpgwAccountType, objectClass, phpgwAccountStatus, phpghAccountVisible
2372                                // for non-external catalogs, used to restrict the attributes used in filters
2373                                $ids = $this->bo->find(array(
2374                                        $data['fields']['id'],
2375                                        $data['fields']['search'],
2376                                        'contact.object_class',
2377                                        //'contact.account_status',
2378                                        'contact.account_visible'
2379                                        ), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
2380                        }
2381
2382            if (!is_array($ids) || !count($ids))
2383            {
2384                                $this->last_search_ids = null;
2385                                $this->save_session();
2386                                return null;
2387            }
2388
2389            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
2390                       
2391            $ids_f = array();
2392
2393            foreach ($ids as $e_info)
2394            {
2395                                if($this->page_info['actual_catalog']['class'] != 'bo_shared_people_manager' && $this->page_info['actual_catalog']['class'] != 'bo_shared_group_manager')
2396                        $ids_f[] = $e_info[$id_field];
2397                else
2398                        $ids_f[] = array(0=>$e_info[$id_field],1=>$e_info['perms']);
2399            }
2400
2401                        return $ids_f;
2402                }
2403               
2404                // CELEPAR
2405                /*
2406        function search($str_data)
2407        {
2408            $data = unserialize($str_data);
2409
2410            if (!is_array($data) || !$data['search_for'] || !is_array($data['fields']))
2411            {
2412                echo serialize(array(
2413                    'msg'    => lang('Invalid parameters'),
2414                    'status' => 'abort'
2415                ));
2416
2417                return;
2418            }
2419
2420            $rules  = array();
2421
2422            if ($data['search_for'] === '*')
2423            {
2424                $rules = array(
2425                    0 => array(
2426                        'field' => $data['fields']['search'],
2427                        'type'  => 'LIKE',
2428                        'value' => '%'
2429                    )
2430                );
2431            }
2432            else
2433            {
2434                $names = explode(' ', $data['search_for']);
2435
2436                if (!is_array($names))
2437                {
2438                    echo serialize(array(
2439                        'msg'    => lang('Invalid Search Parameter'),
2440                        'status' => 'abort'
2441                    ));
2442                   
2443                    return;
2444                }
2445               
2446                foreach ($names as $name)
2447                {
2448                    if ($name != '')
2449                    {
2450                        array_push($rules, array(
2451                            'field' => $data['fields']['search'],
2452                            'type'  => 'iLIKE',
2453                            'value' => '%'.$name.'%'
2454                        ));
2455                    }
2456                }
2457            }
2458
2459           
2460           
2461            //$catalog = $this->bo->get_branch_by_level($this->bo->catalog_level[0]);
2462           
2463            //if ($catalog['class'] === 'bo_people_catalog')
2464            //{
2465            //    array_push($rules, array(
2466            //        'field' => 'contact.id_owner',
2467            //        'type'  => '=',
2468            //        'value' => $GLOBALS['phpgw_info']['user']['account_id']
2469            //    ));
2470            //}
2471           
2472           
2473            $ids = $this->bo->find(array($data['fields']['id'], $data['fields']['search']), $rules, array('order' => $data['fields']['search'], 'sort' => 'ASC'));
2474
2475            if (!is_array($ids) || !count($ids))
2476            {
2477                echo serialize(array(
2478                    'msg'    => lang('No Entries Found!'),
2479                    'status' => 'empty'
2480                ));
2481
2482                return;
2483            }
2484            $id_field = substr($data['fields']['id'], strrpos($data['fields']['id'], '.')+1);
2485
2486            $ids_f = array();
2487            foreach ($ids as $e_info)
2488            {
2489                $ids_f[] = $e_info[$id_field];
2490            }
2491
2492            echo serialize(array(
2493                'data'   => $ids_f,
2494                'msg'    => lang('Found %1 Entries', count($ids)),
2495                'status' => 'ok'
2496            ));
2497                       
2498                        return;
2499        }*/
2500                /*!
2501
2502                        @function get_multiple_entries
2503                        @abstract Returns an array containing the specifiend data in the default
2504                                CC UI format
2505                        @author Raphael Derosso Pereira
2506
2507                        @param array str_data A serialized array containing the ID's of the entries
2508                                to be taken, the fields to be taken and the rules to be used on the
2509                                retrieval:
2510                                $data = array(
2511                                        'ids'    => array(...),
2512                                        'fields' => array(...),
2513                                        'rules'  => array(...)
2514                                );
2515
2516                */
2517                function get_multiple_entries($str_data)
2518                {
2519                        $data = unserialize($str_data);
2520                       
2521                        if (!is_array($data) or !count($data) or !count($data['fields']) or !count($data['ids']))
2522                        {
2523                                return array(
2524                                        'msg'    => lang('Invalid Parameters'),
2525                                        'status' => 'abort'
2526                                );
2527                        }
2528
2529                        $entries = $this->bo->catalog->get_multiple_entries($data['ids'], $data['fields']);
2530                       
2531                        if (!is_array($entries) or !count($entries))
2532                        {
2533                                return array(
2534                                        'msg'    => lang('No Entries Found!'),
2535                                        'status' => 'empty'
2536                                );
2537                        }
2538
2539                        return array(
2540                                'msg'    => lang('Found %1 Entries!', count($entries)),
2541                                'status' => 'ok',
2542                                'data'   => $entries
2543                        );
2544                }
2545
2546                /*
2547
2548                        @function get_all_entries
2549                        @abstract Returns the specified fields for all catalog's entries
2550                                in the default CC UI format
2551                        @author Raphael Derosso Pereira
2552
2553                        @params array str_data A serialized array containing the fields to
2554                                be grabbed, the maximum number of entries to be returned and a
2555                                boolean specifying if the calls refers to a new grab or to an
2556                                unfinished one.
2557
2558                */
2559                function get_all_entries($str_data)
2560                {
2561                        $data = unserialize($str_data);
2562                       
2563                        if (!is_array($data) or
2564                            !count($data) or
2565                                !count($data['fields']) or
2566                                !$data['maxlength'] or
2567                                (!$data['new'] and !$data['offset']))
2568                        {
2569                                return array(
2570                                        'msg'    => lang('Invalid Parameters'),
2571                                        'status' => 'abort'
2572                                );
2573                        }
2574
2575                        if ($data['new'])
2576                        {
2577                                $this->all_entries = $this->bo->catalog->get_all_entries_ids();
2578
2579                                $this->save_session();
2580
2581                                if (!is_array($this->all_entries) or !count($this->all_entries))
2582                                {
2583                                        return array(
2584                                                'msg'    => lang('No Entries Found!'),
2585                                                'status' => 'empty'
2586                                        );
2587                                }
2588
2589                                $data['offset'] = 0;
2590                        }
2591                       
2592                        if ($data['maxlength'] != -1)
2593                        {
2594                                $result = $this->bo->catalog->get_multiple_entries(array_slice($this->all_entries, $data['offset'], $data['maxlength']), $data['fields']);
2595                        }
2596                        else
2597                        {
2598                                $result = $this->bo->catalog->get_multiple_entries($this->all_entries, $data['fields']);
2599                        }
2600
2601                        $prefs = ExecMethod('contactcenter.ui_preferences.get_preferences');
2602                       
2603                        $jsCode = array();
2604                        $count = 0;
2605                        foreach ($result as $each)
2606                        {
2607                                if (!is_array($each))
2608                                {
2609                                        continue;
2610                                }
2611
2612                                if($this-> typeContact == 'groups') {                           
2613                                       
2614                                        foreach ($each as $field => $value)     {
2615                                                                               
2616                                                if ($field === 'title') {
2617                                                        $optionName = '\\"'.$value.'\\"';
2618                                                         
2619                                                }
2620                                                else if ($field === 'short_name')       {
2621                                                       
2622                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$optionName.' ('.$value.')", "'.$count.'");';
2623                                                        $count++;                                                                                                                                                                       
2624                                                }                                       
2625                                        }
2626                                }
2627                               
2628                                else  {
2629                                        foreach ($each as $field => $value)     {
2630                                                if ($field === 'names_ordered') {
2631                                                         if(is_array($value))
2632                                $value = $value[0];
2633                                                        $name = '\\"'.$value.'\\"';
2634                                                }
2635                                                else if ($field === 'connections')      {
2636                                                       
2637                                                        foreach ($value as $connection)         {
2638                                                                if ($connection['id_type'] == $prefs['personCardEmail'])        {
2639                                                                        $jsCode[] = '_this.entries.options[_this.entries.options.length] = new Option("'.$name.' <'.$connection['connection_value'].'>", "'.$count.'");';
2640                                                                        $count++;
2641                                                                }
2642                                                        }
2643                                                }
2644                                        }
2645                                }
2646                        }
2647
2648                        $jsCodeFinal = implode("\n", $jsCode);
2649                       
2650                        $nEntries = count($result);
2651                       
2652                        if (!$nEntries)
2653                        {
2654                                return array(
2655                                        'msg'    => lang('Error while getting user information...'),
2656                                        'status' => 'abort'
2657                                );
2658                        }
2659
2660                        return array(
2661                                'msg'      => lang('Found %1 Entries!', $nEntries),
2662                                'status'   => 'ok',
2663                                'typeContact'   => $this -> typeContact,
2664                                'final'    => $nEntries + $data['offset'] < count($this->all_entries) ? false : true,
2665                                'offset'   => $data['offset'] + $nEntries,
2666                                'data'     => $jsCodeFinal
2667                        );
2668                }
2669               
2670                /*********************************************************************\
2671                 *                      Auxiliar Methods                             *
2672                \*********************************************************************/
2673
2674                /*!
2675               
2676                        @function save_session
2677                        @abstract Saves the data on the session
2678                        @author Raphael Derosso Pereira
2679               
2680                */
2681                function save_session()
2682                {
2683                        $GLOBALS['phpgw']->session->appsession('ui_data.page_info','contactcenter',$this->page_info);
2684                        $GLOBALS['phpgw']->session->appsession('ui_data.all_entries','contactcenter',$this->all_entries);
2685                }
2686
2687                /*!
2688               
2689                        @function convert_tree
2690                        @abstract Converts the tree array in the BO format to a JS tree array compatible
2691                                with the one available in eGW
2692                        @author Raphael Derosso Pereira
2693               
2694                        @param (array)  $tree    The tree in the BO format
2695                        @param (string) $name    The tree name
2696                        @param (string) $iconDir The dir where the icons are
2697                        @param (string) $parent  The parent
2698                */
2699
2700                function convert_tree($tree, &$iconDir, $parent='0')
2701                {
2702//                      echo "Entrou<br>\tPai: $parent <br>";
2703                        $rtree = array();
2704
2705                        if ($parent === '0')
2706                        {
2707//                              echo 'Root!<br>';
2708                                $rtree['0'] = array(
2709                                        'type'       => 'catalog_group',
2710                                        'id'         => '0',
2711                                        'pid'        => 'none',
2712                                        'caption'    => lang('Catalogues'),
2713                                        'class'      => 'bo_catalog_group_catalog',
2714                                        'class_args' => array('_ROOT_', '$this', '$this->get_branch_by_level($this->catalog_level[0])')
2715                                );
2716                        }
2717
2718                        foreach($tree as $id => $value)
2719                        {
2720//                              echo 'ID: '.$id.'<br>';
2721                                $rtree[$parent.'.'.$id] = array(
2722                                        'type'    => $value['type'],
2723                                        'id'      => $parent.'.'.$id,
2724                                        'pid'     => $parent,
2725                                        'caption' => $value['name']
2726                                );
2727                               
2728                                switch($value['type'])
2729                                {
2730                                        case 'catalog_group':
2731                                        case 'mixed_catalog_group':
2732                                                $rtree = $rtree + $this->convert_tree($value['sub_branch'],$iconDir,$parent.'.'.$id);
2733                                                break;
2734                                }
2735                        }
2736
2737                        if (count($rtree))
2738                        {
2739                                return $rtree;
2740                        }
2741                }
2742
2743                function get_catalog_add_contact($id){
2744
2745                        $array_participants = array();
2746                        if(!$this->bo->catalog->src_info) {
2747                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
2748                                $this->bo->catalog->src_info = $ldap->srcs[1];
2749                        }
2750                       
2751                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);                             
2752                        $dn=$this->bo->catalog->src_info['dn'];
2753                        $justThese = array("givenname","givenname","sn","telephonenumber","mail");
2754                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);                                                   
2755                        $info = ldap_get_entries($ds, $sr);                                                     
2756                        for($z = 0; $z < 5; $z++) {
2757                                $participant = $info[0][$justThese[$z]];                                                                                                       
2758                                array_push($array_participants, $participant);
2759                        }
2760
2761                        ldap_close($ds);
2762                        echo serialize($array_participants);
2763                }       
2764               
2765                function get_catalog_participants_group($id)
2766                {
2767                        if(!$this->bo->catalog->src_info) {
2768                                $ldap = CreateObject('contactcenter.bo_ldap_manager');
2769                                $this->bo->catalog->src_info = $ldap->srcs[1];
2770                        }                       
2771                        $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);                     
2772                        $justThese = array("description","memberuid");                 
2773                        $sr = ldap_read($ds,$id, "objectClass=*",$justThese);                                                   
2774                        $info = ldap_get_entries($ds, $sr);
2775                        $member_uids = $info[0]['memberuid'];
2776                        $contact['names_ordered'] = $info[0]['description'];
2777                        $filter = "";                   
2778                        for($z = 0; $z < count($member_uids); $z++) {
2779                                if($member_uids[$z])
2780                                        $filter.="(uid=".$member_uids[$z].")"; 
2781                        }
2782                        $array_participants = array();
2783                        if($filter) {
2784                                $filter = "(|".$filter.")";
2785                                $valarray = explode(',',$id);
2786                                array_shift($valarray);
2787                                $dn = implode(',',$valarray);
2788                                $justThese = array("cn","mail");
2789                                $sr = ldap_search($ds,$dn, $filter,$justThese);                                                         
2790                                $info = ldap_get_entries($ds, $sr);                                                     
2791                                for($z = 0; $z < $info['count']; $z++) {
2792                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
2793                                        $array_emails[$info[$z]['mail'][0]] = null;                                                             
2794                                        array_push($array_participants, $participant);                                 
2795                                }
2796                                ldap_close($ds);
2797                        }                       
2798                        sort($array_participants);
2799                        $innerHTML = '';                       
2800                        foreach($array_participants as $index => $participant){
2801                                $innerHTML .= $participant;
2802                        }
2803                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);                 
2804                        echo serialize($return);
2805                }
2806
2807                function get_catalog_participants_list($id)
2808                {
2809                       
2810                        $fields = $this->bo->catalog->get_fields(false);                       
2811                        $fields['names_ordered'] = true;
2812                        $fields['mail_forwarding_address'] = true;                     
2813                        $contact = $this->bo->catalog->get_single_entry($id,$fields);                   
2814                       
2815                        $array_participants = array();
2816                        $array_emails = array();
2817
2818                        $filter = null;
2819                        for($z = 0; $z < $contact['mail_forwarding_address']['count']; $z++) {                 
2820                                        if(strstr($contact['mail_forwarding_address'][$z],'@')) {
2821                                                $filter.="(mail=".$contact['mail_forwarding_address'][$z].")";
2822                                                $array_emails[$contact['mail_forwarding_address'][$z]] = "<font color=black>".$contact['mail_forwarding_address'][$z]."</font>";
2823                                        }                                                                                                                               
2824                                        else
2825                                                $array_participants[$z] = "<font color=red>".$contact['mail_forwarding_address'][$z]."</font>";
2826                        }                                       
2827                       
2828                        if($filter) {
2829                                $filter = "(|".$filter.")";                                                     
2830                                if(!$this->bo->catalog->src_info) {
2831                                        $ldap = CreateObject('contactcenter.bo_ldap_manager');
2832                                        $this->bo->catalog->src_info = $ldap->srcs[1];
2833                                }
2834                                $ds = $GLOBALS['phpgw']->common->ldapConnect($this->bo->catalog->src_info['host'], $this->bo->catalog->src_info['acc'], $this->bo->catalog->src_info['pw'], true);
2835                               
2836                                $dn=$this->bo->catalog->src_info['dn'];
2837                                $justThese = array("cn","mail");
2838                                $sr = ldap_search($ds,$dn, $filter,$justThese);                                                         
2839                                $info = ldap_get_entries($ds, $sr);                                                     
2840                                for($z = 0; $z < $info['count']; $z++) {
2841                                        $participant =  '<font color=\'DARKBLUE\'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&quot;'.$info[$z]['cn'][0].'&quot; &lt;'.$info[$z]['mail'][0].'&gt;</font><br>';
2842                                        $array_emails[$info[$z]['mail'][0]] = null;                                                             
2843                                        array_push($array_participants, $participant);                                 
2844                                }
2845                               
2846                                foreach($array_emails as $index => $email)
2847                                        if($email)
2848                                                array_push($array_participants, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$email."<br>");                         
2849                                                                                               
2850                                ldap_close($ds);
2851                        }
2852                        sort($array_participants);
2853                        $innerHTML = '';                       
2854                        foreach($array_participants as $index => $participant){
2855                                $innerHTML .= $participant;
2856                        }
2857                        $return = array('size' => count($array_participants), 'names_ordered'=> $contact['names_ordered'], 'inner_html' => $innerHTML);                 
2858                        echo serialize($return);
2859                }       
2860               
2861                function export_contacts($typeExport){
2862
2863                        $boGroup = CreateObject('contactcenter.bo_group');
2864                        $contacts = $boGroup->get_all_contacts();
2865                        $streamBuffer = '';
2866
2867                        if(!count($contacts))
2868                                echo null;
2869                       
2870                        switch($typeExport) {
2871
2872                                case 'outlook_en':
2873                                        $streamBuffer = "Name;E-mail Address;Notes;Mobile Phone;Pager;Company;".
2874                                                        "Job Title;Home Phone;Home Fax;Business Phone;Business Fax\r\n";                                                       
2875                                        foreach($contacts as $index => $object){
2876                                                $streamBuffer.= $object['names_ordered'].";".$object['connection_value'].";;;;;;".$object['phone'].";;;\r\n";
2877                                        }
2878                                break;
2879                               
2880                                case 'outlook_pt-BR':
2881                                        $streamBuffer = "Nome;End. de email;Endereço residencial;".
2882                                        "Cidade do endereço residencial;CEP do endereço residencial;".
2883                                        "Estado;País/região do endereço residencial;Telefone residencial;".
2884                                        "Rua do endereço comercial;Cidade do endereço comercial;".
2885                                        "CEP do endereço comercial;Estado do endereço comercial;".
2886                                        "País/região do endereço comercial;Telefone comercial;Empresa;Cargo\r\n";                                                       
2887                                        foreach($contacts as $index => $object){
2888                                                $streamBuffer.= $object['names_ordered'].";".$object['connection_value'].";;;;;;".$object['phone'].";;;;;;;;\r\n";
2889                                        }
2890                                break;
2891                               
2892                                case 'outlook2000_pt-BR':
2893                                        $streamBuffer = "\"Tratamento\",\"Nome\",\"Segundo Nome\",\"Sobrenome\",\"Sufixo\",".
2894                                        "\"Empresa\",\"Departamento\",\"Cargo\",\"Rua do endereço comercial\",\"Rua do endereço comercial 2\",".
2895                                        "\"Rua do endereço comercial 3\",\"Cidade do endereço comercial\",\"Estado do endereço comercial\",".
2896                                        "\"CEP do endereço comercial\",\"País do endereço comercial\",\"Endereço residencial\",\"Rua residencial 2\",".
2897                                        "\"Rua residencial 3\",\"Cidade do endereço residencial\",\"Estado\",\"CEP do endereço residencial\",\"País do endereço residencial\",".
2898                                        "\"Outro endereço\",\"Outro endereço 2\",\"Outro endereço 3\",\"Cidade\",\"Estado\",\"CEP\",\"País\",".
2899                                        "\"Telefone do assistente\",\"Fax comercial\",\"Telefone comercial\",\"Telefone comercial 2\",\"Retorno de chamada\",".
2900                                        "\"Telefone do carro\",\"Telefone principal da empresa\",\"Fax residencial\",\"Telefone residencial\",".
2901                                        "\"Telefone residencial 2\",\"ISDN\",\"Telefone celular\",\"Outro fax\",\"Outro telefone\",\"Pager\",\"Telefone principal\",".
2902                                        "\"Radiofone\",\"Telefone TTY/TDD\",\"Telex\",\"Aniversário\",\"Anotações\",\"Caixa postal\",\"Categorias\",".
2903                                        "\"Código da empresa\",\"Código do governo\",\"Cônjuge\",\"Conta\",\"Endereço de correio eletrônico\",".
2904                                        "\"Nome de exibição do correio eletr.\",\"Endereço de correio eletrônico 2\",".
2905                                        "\"Nome de exibição do correio eletr.2\",\"Endereço de correio eletrônico 3\",".
2906                                        "\"Nome de exibição do correio eletr.3\",\"Datas especiais\",\"Disponibilidade da Internet\",".
2907                                        "\"Filhos\",\"Hobby\",\"Idioma\",\"Indicação\",\"Informações para cobrança\",\"Iniciais\",\"Local\",".
2908                                        "\"Nome do assistente\",\"Nome do gerenciador\",\"Página da Web\",\"Palavras-chave\",\"Particular\",\"Personalizado 1\",\"Personalizado 2\",".
2909                                        "\"Personalizado 3\",\"Personalizado 4\",\"Prioridade\",\"Profissão\",\"Quilometragem\",\"Sala\",\"Sensibilidade\",\"Servidor de diretório\",".
2910                                        "\"Sexo\"\r\n";
2911                                        foreach($contacts as $index => $object){
2912                                                $streamBuffer.= ",\"".$object['names_ordered']."\",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,".$object['phone'].",,,,,,,,,,,,\"".$object['connection_value']."\",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
2913                                        }
2914                                break;
2915                               
2916                                case 'outlook2000_en':
2917                                        $streamBuffer = "Title,First Name,Middle Name,Last Name,Suffix,Company,Department,Job Title,".
2918                                        "Business Street,Business Street 2,Business Street 3,Business City,Business State,Business Postal Code,".
2919                                        "Business Country,Home Street,Home Street 2,Home Street 3,Home City,Home State,Home Postal Code,Home Country,".
2920                                        "Other Street,Other Street 2,Other Street 3,Other City,Other State,Other Postal Code,Other Country,".
2921                                        "Assistant's Phone,Business Fax,Business Phone,Business Phone 2,Callback,Car Phone,Company Main Phone,Home Fax,".
2922                                        "Home Phone,Home Phone 2,ISDN,Mobile Phone,Other Fax,Other Phone,Pager,Primary Phone,Radio Phone,TTY/TDD Phone,Telex,".
2923                                        "Account,Anniversary,Assistant's Name,Billing Information,Birthday,Categories,Children,Directory Server,E-mail Address,".
2924                                        "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,".
2925                                        "Gender,Government ID Number,Hobby,Initials,Internet Free Busy,Keywords,Language,Location,Manager's Name,Mileage,Notes,".
2926                                        "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";
2927                                        foreach($contacts as $index => $object){
2928                                                $streamBuffer.= ",".$object['names_ordered'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,".$object['phone'].",,,,,,,,,,,,".$object['connection_value'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
2929                                        }
2930                                break;
2931                                       
2932                                case 'thunderbird':
2933                                        $streamBuffer = "\n";                                                   
2934                                        foreach($contacts as $index => $object){
2935                                                $streamBuffer.= ",,".$object['names_ordered'].",,".$object['connection_value'].",,".$object['phone'].",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
2936                                        }
2937                                break;
2938                               
2939                                case 'expresso':
2940                                        $streamBuffer = "Nome,Email,Telefone\r\n";
2941                                        foreach($contacts as $index => $object){
2942                                                $streamBuffer.= $object['names_ordered'].",".$object['connection_value'].",".$object['phone']."\r\n";
2943                                        }
2944                                break;
2945                               
2946                        }
2947
2948                        $file = "contacts_".md5(microtime()).".swp";
2949                        $tempDir = ini_get("session.save_path");
2950                        $f = fopen($tempDir.'/'.$file,"w");
2951                        if(!$f)
2952                                echo null;
2953               
2954                        fputs($f,$streamBuffer);
2955                        fclose($f);
2956
2957                        echo $tempDir.'/'.$file;
2958                }
2959
2960                // Get the csv field and put into array, from php.net
2961                function parse_line($input_text, $delimiter = ',', $text_qualifier = '"') {
2962                        $text = trim($input_text);
2963                          if(is_string($delimiter) && is_string($text_qualifier)) {
2964                         $re_d = '\x' . dechex(ord($delimiter));            //format for regexp
2965                        $re_tq = '\x' . dechex(ord($text_qualifier));    //format for regexp
2966                       
2967                        $fields = array();
2968                        $field_num = 0;
2969                        while(strlen($text) > 0) {
2970                        if($text{0} == $text_qualifier) {
2971                                preg_match('/^' . $re_tq . '((?:[^' . $re_tq . ']|(?<=\x5c)' . $re_tq . ')*)' . $re_tq . $re_d . '?(.*)$/', $text, $matches);
2972                               
2973                                $value = str_replace('\\' . $text_qualifier, $text_qualifier, $matches[1]);
2974                                $text = trim($matches[2]);
2975               
2976                                $fields[$field_num++] = $value;
2977                        } else {
2978                                preg_match('/^([^' . $re_d . ']*)' . $re_d . '?(.*)$/', $text, $matches);
2979                               
2980                                $value = $matches[1];
2981                                $text = trim($matches[2]);
2982               
2983                                $fields[$field_num++] = $value;
2984                }
2985                }
2986                        return $fields;
2987                    } else
2988                        return false;
2989                }
2990
2991                function import_contacts($typeImport){
2992
2993                        if($file = $_SESSION['contactcenter']['importCSV']) {                           
2994                                unset($_SESSION['contactcenter']['importCSV']);                         
2995                                $len = filesize($file);
2996                                $count = 0;
2997                                $return = array('error' => false, '_new' => 0, '_existing' => 0, '_failure' => 0);
2998                                $handle = @fopen($file, "r") or die(serialize($return['error'] = true));
2999                               
3000                                $input_header = fgets($handle);
3001                                if ($typeImport == 'outlook')
3002                                        $delim = ';';
3003                                else if ($typeImport == 'auto')
3004                                $delim = strstr($input_header,',') ? ',' : ';';
3005                                else 
3006                                        $delim = ',';
3007                                $csv_header = $this->parse_line($input_header,$delim);
3008                                $firstContact = fgets($handle);
3009                                preg_match("/\"(.+)\"[,;]/sU",$firstContact,$matches); // yahoo csv
3010                                rewind($handle);                               
3011
3012                                $header = @fgetcsv($handle, $len, $delim) or die(serialize($return['error'] = true));
3013                                if(count($header)  < 2 || count($header) > 100) {
3014                                        $return['error'] = true;
3015                                        $return['sizeheader'] = count($header);
3016                                        echo serialize($return);
3017                                        return;
3018                                }
3019                               
3020                                if ($matches[0][strlen($matches[0])-1] == ';')
3021                                        $delim = ';';
3022                               
3023                        $boGroup = CreateObject('contactcenter.bo_group');
3024                        $boPeople = CreateObject('contactcenter.bo_people_catalog');
3025                                switch($typeImport){
3026                                        case 'outlook2000':
3027                                                $name_pos=1;
3028                                                $email_pos=56;
3029                                                $phone_pos=44;
3030                                                break;
3031                                        case 'outlook':
3032                                                $name_pos=0;
3033                                                $email_pos=1;
3034                                                $phone_pos=7;
3035                                                break;
3036                                        case 'thunderbird':
3037                                                $name_pos=2;
3038                                                $email_pos=4;
3039                                                $phone_pos=7;
3040                                                break;
3041                                        case 'expresso':
3042                                                $name_pos=0;
3043                                                $email_pos=1;
3044                                                $phone_pos=2;
3045                                                break;
3046                                        default:
3047                                                foreach($csv_header as $index => $fieldName)
3048                                                {
3049                                                        switch(strtoupper($fieldName)){
3050                                                        case 'NAME':
3051                                                        case 'NOME':
3052                                                        case 'FIRST NAME':
3053                                                                $name_pos = $index;
3054                                                                break;
3055                                                        case 'E-MAIL':
3056                                                        case 'EMAIL':
3057                                                        case 'E-MAIL ADDRESS':
3058                                                        case 'ENDEREÇO DE CORREIO ELETRÔNICO':
3059                                                        case 'END. DE EMAIL':
3060                                                                $email_pos = $index;
3061                                                                break;
3062                                                        case 'HOME PHONE':
3063                                                        case 'PHONE':
3064                                                        case 'TELEFONE':
3065                                                        case 'TELEFONE PRINCIPAL':
3066                                                        case 'TELEFONE COMERCIAL':
3067                                                                $phone_pos = $index;
3068                                                                break;
3069                                                        }
3070                                                }
3071                                                break;
3072                                }
3073                               
3074
3075                                while (($data = fgetcsv($handle, $len, $delim))) {
3076                                foreach ($header as $key=>$heading)
3077                                $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
3078                               
3079                                        $sdata = array();
3080                                        $full_name  = trim($row[$header[$name_pos]]);
3081                                        $email          = trim($row[$header[$email_pos]]);
3082                                        $phone          = trim($row[$header[$phone_pos]]);
3083                                        $array_name = explode(' ', str_replace('"','',(str_replace('\'','',$full_name))));
3084                                        $sdata['given_names'] = $array_name[0];
3085                                        $array_name[0] = null;
3086                                        $sdata['family_names'] = trim(implode(' ',$array_name));
3087                                        $sdata['connections']['default_email']['connection_name'] = lang('Main');
3088                                        $sdata['connections']['default_email']['connection_value'] = $email;
3089
3090                                        $sdata['connections']['default_phone']['connection_name'] = lang('Main');
3091                                        $sdata['connections']['default_phone']['connection_value'] = $phone;
3092                                        $sdata['is_quick_add'] = true;
3093                                       
3094                                        //      verifica se email já existe!
3095                                        $contact = $boGroup->verify_contact($email);
3096                                                                               
3097                                        if(!$sdata['given_names'] && $email){
3098                                                        $a_email = explode("@",$email);
3099                                                        $sdata['given_names'] = $a_email[0];
3100                                        }
3101
3102                                        $line_iteration = $return['_failure'] + $return['_existing'] + $return['_new'];
3103                                        if($contact){
3104                                                $return['_existing']++;
3105                                        }                                                                                                               
3106                                        else if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
3107                                                $return['_failure']++;
3108                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid E-Mail address: " . $email ."<br>";
3109                                        }
3110                                        else if (!$sdata['given_names'] || !$email || !$boPeople ->quick_add($sdata)){
3111                                                $return['_failure']++;                                                 
3112                                                $return['_failure_status'] .= "Line: " . ($line_iteration + 2) . ", Invalid Name: " . $sdata['given_names'] ."<br>";
3113                                        }
3114                                        else
3115                                                $return['_new']++;
3116                        }                               
3117                                fclose($handle);
3118                                unlink($file);
3119                        }
3120                        else
3121                                $return['error'] = true;
3122
3123                        echo serialize($return);
3124                }
3125/*
3126                function convert_tree($tree, $name, &$iconDir, $parent='0')
3127                {
3128                        $new = null;
3129                        $code = null;
3130                       
3131                        if ($parent === '0')
3132                        {
3133
3134                                $code .= $name.".add(new dNode({id:'0', caption: '".lang('Catalogues')."'}),'none');\n";
3135                        }
3136                       
3137                        foreach ($tree as $id => $value)
3138                        {
3139                                $title = $value['name'];
3140
3141                                switch ($value['type'])
3142                                {                                       
3143                                        case 'unknown':
3144                                                $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";
3145                                                break;
3146                                       
3147                                        case 'catalog_group':
3148                                                $code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}'}),'$parent');\n";
3149                                                $code .= $this->convert_tree($value['sub_branch'],$name,$iconDir,$parent.'.'.$id);
3150                                                break;
3151
3152                                        case 'mixed_catalog_group':
3153                                                $code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}', onClick: 'setCatalog(\\'{$parent}.{$id}\\')'}),'$parent');\n";
3154
3155                                                $code .= $this->convert_tree($value['sub_branch'],$name,$iconDir,$parent.'.'.$id);
3156                                                break;
3157                                       
3158                                        case 'catalog':
3159                                                $code .= $name.".add(new dNode({id: '{$parent}.{$id}', caption: '{$value['name']}', onClick: 'setCatalog(\\'{$parent}.{$id}\\')'}),'$parent');\n";
3160                                               
3161                                }
3162                        }
3163                       
3164                        return $code;
3165                }
3166*/
3167        }
3168
3169?>
Note: See TracBrowser for help on using the repository browser.