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

Revision 276, 83.6 KB checked in by niltonneto, 16 years ago (diff)

Correções na importação e exportação dos contatos.

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