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

Revision 1496, 109.9 KB checked in by wmerlotto, 15 years ago (diff)

Ticket #628 - Implementada a funcionalidade de adição no catálogo compartilhado.

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