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

Revision 1411, 99.8 KB checked in by rodsouza, 15 years ago (diff)

Ticket #611 - Caracteres especiais codificados.

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