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

Revision 241, 80.5 KB checked in by niltonneto, 16 years ago (diff)

Otimizado código para retornar options da janela de adicionar

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