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

Revision 285, 94.5 KB checked in by brunocosta, 16 years ago (diff)

Correção dos problemas gerados no commit anterior, a funcionalidade citada no ticket #199 foram temporariamente desativadas.

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