source: contrib/ProjectManager/inc/class.boinfolog.inc.php @ 3594

Revision 3594, 136.1 KB checked in by afernandes, 13 years ago (diff)

Ticket #1416 - Disponibilizado o módulo ProjectManager? para a comunidade

  • Property svn:executable set to *
Line 
1<?php
2  /**************************************************************************\
3  * eGroupWare - infolog                                                    *
4  * http://www.eGroupWare.org                                                *
5  * Maintained and further developed by RalfBecker@outdoor-training.de       *
6  * Based on Webinfolog by Craig Knudsen <cknudsen@radix.net>               *
7  *          http://www.radix.net/~cknudsen                                  *
8  * Originaly modified by Mark Peters <skeeter@phpgroupware.org>             *
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 boinfolog
18        {
19
20var $db;
21                var $public_functions = Array(
22                        'read_entry'      => True,
23                        'delete_entry'    => True,
24                        'delete_infolog' => True,
25                        'change_owner'    => True,
26                        'update'          => True,
27                        'check_set_default_prefs' => True,
28                        'store_to_cache'  => True,
29                        'export_event'    => True,
30                        'send_alarm'      => True,
31                        'reinstate'       => True
32                );
33
34                var $soap_functions = Array(
35                        'read_entry' => Array(
36                                'in' => Array(
37                                        'int'
38                                ),
39                                'out' => Array(
40                                        'SOAPStruct'
41                                )
42                        ),
43                        'delete_entry' => Array(
44                                'in' => Array(
45                                        'int'
46                                ),
47                                'out' => Array(
48                                        'int'
49                                )
50                        ),
51                        'delete_infolog' => Array(
52                                'in' => Array(
53                                        'int'
54                                ),
55                                'out' => Array(
56                                        'int'
57                                )
58                        ),
59                        'change_owner' => Array(
60                                'in' => Array(
61                                        'array'
62                                ),
63                                'out' => Array(
64                                        'int'
65                                )
66                        ),
67                        'update' => Array(
68                                'in' => Array(
69                                        'array',
70                                        'array',
71                                        'array',
72                                        'array',
73                                        'array'
74                                ),
75                                'out' => Array(
76                                        'array'
77                                )
78                        ),
79                        'store_to_cache'        => Array(
80                                'in' => Array(
81                                        'struct'
82                                ),
83                                'out' => Array(
84                                        'SOAPStruct'
85                                )
86                        ),
87                        'store_to_cache'        => Array(
88                                'in' => Array(
89                                        'array'
90                                ),
91                                'out' => Array(
92                                        'string'
93                                )
94                        ),
95                        'categories' => array(
96                                'in'  => array('bool'),
97                                'out' => array('array')
98                        ),
99                );
100
101                var $debug = False;
102//              var $debug = True;
103
104                var $so;
105                var $so1;
106                var $ex_participants;
107                var $cached_events;
108                var $repeating_events;
109                var $day;
110                var $month;
111                var $year;
112                var $prefs;
113
114                var $owner;
115                var $holiday_color;
116                var $printer_friendly = False;
117
118                var $cached_holidays;
119
120                var $g_owner = 0;
121
122                var $filter;
123                var $cat_id;
124                var $users_timeformat;
125
126                var $modified;
127                var $deleted;
128                var $added;
129
130                var $is_group = False;
131
132                var $soap = False;
133
134                var $use_session = False;
135
136                var $today;
137                var $debug_string;
138
139                var $sortby;
140                var $num_months;
141                var $xmlrpc = False;    // not called via xmlrpc
142        var $async = false;
143
144                function boinfolog($session=0)
145                {
146
147                        if(!is_object($GLOBALS['phpgw']->datetime))
148                        {
149                                $GLOBALS['phpgw']->datetime = createobject('phpgwapi.date_time');
150                        }
151
152                        $this->cat = CreateObject('phpgwapi.categories');
153
154$this->resources = CreateObject('phpgwapi.resources');
155
156$this->priority = CreateObject('phpgwapi.priority');
157
158                        $this->grants = $GLOBALS['phpgw']->acl->get_grants('infolog');
159                        @reset($this->grants);
160                        if(DEBUG_APP)
161                        {
162                                if(floor(phpversion()) >= 4)
163                                {
164                                        $this->debug_string = '';
165                                        ob_start();
166                                }
167
168                                foreach($this->grants as $grantor => $rights)
169                                {
170                                        print_debug('Grantor',$grantor);
171                                        print_debug('Rights',$rights);
172                                }
173                        }
174
175                        print_debug('Read use_session',$session);
176
177                        if($session)
178                        {
179                                $this->read_sessiondata();
180                                $this->use_session = True;
181                        }
182                        print_debug('BO Filter',$this->filter);
183                        print_debug('Owner',$this->owner);
184
185                        if ($GLOBALS['argv']) {
186                          $this->async = true;
187                          $this->load_lang();
188                        }
189
190                        $this->prefs['infolog']    = $GLOBALS['phpgw_info']['user']['preferences']['infolog'];
191                        $this->check_set_default_prefs();
192
193                        $owner = get_var('owner',array('GET','POST'),$GLOBALS['owner']);
194
195                        ereg('menuaction=([a-zA-Z.]+)',$_SERVER['HTTP_REFERER'],$regs);
196                        $from = $regs[1];
197                        if ((substr($_SERVER['PHP_SELF'],-8) == 'home.php' && substr($this->prefs['infolog']['defaultinfolog'],0,7) == 'planner'
198                                || $_GET['menuaction'] == 'infolog.uiinfolog.planner' &&
199                                $from  != 'infolog.uiinfolog.planner' && !$this->save_owner)
200                                && (int)$this->prefs['infolog']['planner_start_with_group'] > 0)
201                        {
202                                // entering planner for the first time ==> saving owner in save_owner, setting owner to default
203                                //
204                                $this->save_owner = $this->owner;
205                                $owner = 'g_'.$this->prefs['infolog']['planner_start_with_group'];
206                        }
207                        elseif ($_GET['menuaction'] != 'infolog.uiinfolog.planner' &&
208                                $this->save_owner)
209                        {
210                                // leaving planner with an unchanged user/owner ==> setting owner back to save_owner
211                                //
212                                $owner = (int)(isset($_GET['owner']) ? $_GET['owner'] : $this->save_owner);
213                                unset($this->save_owner);
214                        }
215                        elseif (!empty($owner) && $owner != $this->owner && $from == 'infolog.uiinfolog.planner')
216                        {
217                                // user/owner changed within planner ==> forgetting save_owner
218                                //
219                                unset($this->save_owner);
220                        }
221
222                        if(isset($owner) && $owner!='' && substr($owner,0,2) == 'g_')
223                        {
224                                $this->set_owner_to_group(substr($owner,2));
225                        }
226                        elseif(isset($owner) && $owner!='')
227                        {
228                                $this->owner = (int)$owner;
229                        }
230                        elseif(!@isset($this->owner) || !@$this->owner)
231                        {
232                                $this->owner = (int)$GLOBALS['phpgw_info']['user']['account_id'];
233                        }
234                        elseif(isset($this->owner) && $GLOBALS['phpgw']->accounts->get_type($this->owner) == 'g')
235                        {
236                                $this->set_owner_to_group((int)$this->owner);
237                        }
238
239                        $this->prefs['common']    = $GLOBALS['phpgw_info']['user']['preferences']['common'];
240
241                        if ($this->prefs['common']['timeformat'] == '12')
242                        {
243                                $this->users_timeformat = 'h:ia';
244                        }
245                        else
246                        {
247                                $this->users_timeformat = 'H:i';
248                        }
249                        $this->holiday_color = (substr($GLOBALS['phpgw_info']['theme']['bg07'],0,1)=='#'?'':'#').$GLOBALS['phpgw_info']['theme']['bg07'];
250
251                        $friendly = (isset($_GET['friendly'])?$_GET['friendly']:'');
252                        $friendly = ($friendly=='' && isset($_POST['friendly'])?$_POST['friendly']:$friendly);
253
254                        $this->printer_friendly = ((int)$friendly == 1?True:False);
255
256                        if(isset($_POST['filter'])) { $this->filter = $_POST['filter']; }
257                        if(isset($_POST['sortby'])) { $this->sortby = $_POST['sortby']; }
258                        if(isset($_POST['cat_id'])) { $this->cat_id = $_POST['cat_id']; }
259
260                        if(!isset($this->filter))
261                        {
262                                $this->filter = ' '.$this->prefs['infolog']['defaultfilter'].' ';
263                        }
264
265                        if(!isset($this->sortby))
266                        {
267                                $this->sortby = $this->prefs['infolog']['defaultinfolog'] == 'planner_user' ? 'user' : 'category';
268                        }
269
270                        if($GLOBALS['phpgw']->accounts->get_type($this->owner)=='g')
271                        {
272                                $this->filter = ' all ';
273                        }
274
275                        $this->so = CreateObject('infolog.soinfolog',
276                                Array(
277                                        'owner'         => $this->owner,
278                                        'filter'        => $this->filter,
279                                        'category'      => $this->cat_id,
280                                        'g_owner'       => $this->g_owner
281                                )
282                        );
283                        $this->rpt_day = array( // need to be after creation of soinfolog
284                                MCAL_M_SUNDAY    => 'Sunday',
285                                MCAL_M_MONDAY    => 'Monday',
286                                MCAL_M_TUESDAY   => 'Tuesday',
287                                MCAL_M_WEDNESDAY => 'Wednesday',
288                                MCAL_M_THURSDAY  => 'Thursday',
289                                MCAL_M_FRIDAY    => 'Friday',
290                                MCAL_M_SATURDAY  => 'Saturday'
291                        );
292                        if($this->bo->prefs['infolog']['weekdaystarts'] != 'Sunday')
293                        {
294                                $mcals = array_keys($this->rpt_day);
295                                $days  = array_values($this->rpt_day);
296                                $this->rpt_day = array();
297                                list($n) = $found = array_keys($days,$this->prefs['infolog']['weekdaystarts']);
298                                for ($i = 0; $i < 7; ++$i,++$n)
299                                {
300                                        $this->rpt_day[$mcals[$n % 7]] = $days[$n % 7];
301                                }
302                        }
303                        $this->rpt_type = Array(
304                                MCAL_RECUR_NONE         => 'None',
305                                MCAL_RECUR_DAILY        => 'Daily',
306                                MCAL_RECUR_WEEKLY       => 'Weekly',
307                                MCAL_RECUR_MONTHLY_WDAY => 'Monthly (by day)',
308                                MCAL_RECUR_MONTHLY_MDAY => 'Monthly (by date)',
309                                MCAL_RECUR_YEARLY       => 'Yearly'
310                        );
311
312                        $localtime = $GLOBALS['phpgw']->datetime->users_localtime;
313
314                        $date = (isset($GLOBALS['date'])?$GLOBALS['date']:'');
315                        $date = (isset($_GET['date'])?$_GET['date']:$date);
316                        $date = ($date=='' && isset($_POST['date'])?$_POST['date']:$date);
317
318                        $year = (isset($_GET['year'])?$_GET['year']:'');
319                        $year = ($year=='' && isset($_POST['year'])?$_POST['year']:$year);
320
321                        $month = (isset($_GET['month'])?$_GET['month']:'');
322                        $month = ($month=='' && isset($_POST['month'])?$_POST['month']:$month);
323
324                        $day = (isset($_GET['day'])?$_GET['day']:'');
325                        $day = ($day=='' && isset($_POST['day'])?$_POST['day']:'');
326
327                        $num_months = (isset($_GET['num_months'])?$_GET['num_months']:'');
328                        $num_months = ($num_months=='' && isset($_POST['num_months'])?$_POST['num_months']:$num_months);
329
330                        if(isset($date) && $date!='')
331                        {
332                                $this->year  = (int)(substr($date,0,4));
333                                $this->month = (int)(substr($date,4,2));
334                                $this->day   = (int)(substr($date,6,2));
335                        }
336                        else
337                        {
338                                if(isset($year) && $year!='')
339                                {
340                                        $this->year = $year;
341                                }
342                                else
343                                {
344                                        $this->year = date('Y',$localtime);
345                                }
346                                if(isset($month) && $month!='')
347                                {
348                                        $this->month = $month;
349                                }
350                                else
351                                {
352                                        $this->month = date('m',$localtime);
353                                }
354                                if(isset($day) && $day!='')
355                                {
356                                        $this->day = $day;
357                                }
358                                else
359                                {
360                                        $this->day = date('d',$localtime);
361                                }
362                        }
363
364                        if(isset($num_months) && $num_months!='')
365                        {
366                                $this->num_months = $num_months;
367                        }
368                        elseif($this->num_months == 0)
369                        {
370                                $this->num_months = 1;
371                        }
372
373                        $this->today = date('Ymd',$GLOBALS['phpgw']->datetime->users_localtime);
374
375                        if(DEBUG_APP)
376                        {
377                                print_debug('BO Filter','('.$this->filter.')');
378                                print_debug('Owner',$this->owner);
379                                print_debug('Today',$this->today);
380                                if(floor(phpversion()) >= 4)
381                                {
382                                        $this->debug_string .= ob_get_contents();
383                                        ob_end_clean();
384                                }
385                        }
386
387$evento=$this->restore_from_appsession();
388                        $this->xmlrpc = is_object($GLOBALS['server']) && $GLOBALS['server']->last_method;
389                }
390
391          function load_lang() {
392            if(!$_SESSION['phpgw_info']['infolog']['langAlarm'])
393              {
394                $array_keys = array();
395                $fn = '../../infolog/setup/phpgw_alarm_'.$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'].'.lang';                       
396                echo $fn;
397                if (file_exists($fn)){
398                  $fp = fopen($fn,'r');
399                  while ($data = fgets($fp,16000))      {
400                    list($message_id,$app_name,$null,$content) = explode("\t",substr($data,0,-1));                     
401                    $_SESSION['phpgw_info']['infolog']['langAlarm'][$message_id] =  $content;
402                  }
403                  fclose($fp);
404                }
405              }
406          }
407                function list_methods($_type='xmlrpc')
408                {
409                        /*
410                          This handles introspection or discovery by the logged in client,
411                          in which case the input might be an array.  The server always calls
412                          this function to fill the server dispatch map using a string.
413                        */
414                        if (is_array($_type))
415                        {
416                                $_type = $_type['type'];
417                        }
418                        switch($_type)
419                        {
420                                case 'xmlrpc':
421                                        $xml_functions = array(
422                                                'list_methods' => array(
423                                                        'function'  => 'list_methods',
424                                                        'signature' => array(array(xmlrpcStruct,xmlrpcString)),
425                                                        'docstring' => lang('Read this list of methods.')
426                                                ),
427                                                'read' => array(
428                                                        'function'  => 'read_entry',
429                                                        'signature' => array(array(xmlrpcStruct,xmlrpcInt)),
430                                                        'docstring' => lang('Read a single entry by passing the id and fieldlist.')
431                                                ),
432                                                'read_entry' => array(  // deprecated, use read
433                                                        'function'  => 'read_entry',
434                                                        'signature' => array(array(xmlrpcStruct,xmlrpcInt)),
435                                                        'docstring' => lang('Read a single entry by passing the id and fieldlist.')
436                                                ),
437                                                'write' => array(
438                                                        'function'  => 'update',
439                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
440                                                        'docstring' => lang('Add or update a single entry by passing the fields.')
441                                                ),
442                                                'add_entry' => array(   // deprecated, use write
443                                                        'function'  => 'update',
444                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
445                                                        'docstring' => lang('Add a single entry by passing the fields.')
446                                                ),
447                                                'update_entry' => array(        // deprecated, use write
448                                                        'function'  => 'update',
449                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
450                                                        'docstring' => lang('Update a single entry by passing the fields.')
451                                                ),
452                                                'delete' => array(
453                                                        'function'  => 'delete_entry',
454                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
455                                                        'docstring' => lang('Delete a single entry by passing the id.')
456                                                ),
457                                                'delete_entry' => array(        // deprecated, use delete
458                                                        'function'  => 'delete_entry',
459                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
460                                                        'docstring' => lang('Delete a single entry by passing the id.')
461                                                ),
462                                                'delete_infolog' => array(
463                                                        'function'  => 'delete_infolog',
464                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
465                                                        'docstring' => lang('Delete an entire users infolog.')
466                                                ),
467                                                'change_owner' => array(
468                                                        'function'  => 'change_owner',
469                                                        'signature' => array(array(xmlrpcInt,xmlrpcStruct)),
470                                                        'docstring' => lang('Change all events for $params[\'old_owner\'] to $params[\'new_owner\'].')
471                                                ),
472                                                'search' => array(
473                                                        'function'  => 'store_to_cache',
474                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
475                                                        'docstring' => lang('Read a list of entries.')
476                                                ),
477                                                'store_to_cache' => array(      // deprecated, use search
478                                                        'function'  => 'store_to_cache',
479                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
480                                                        'docstring' => lang('Read a list of entries.')
481                                                ),
482                                                'export_event' => array(
483                                                        'function'  => 'export_event',
484                                                        'signature' => array(array(xmlrpcString,xmlrpcStruct)),
485                                                        'docstring' => lang('Export a list of entries in iCal format.')
486                                                ),
487                                                'categories' => array(
488                                                        'function'  => 'categories',
489                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
490                                                        'docstring' => lang('List all categories.')
491                                                ),
492                                        );
493                                        return $xml_functions;
494                                        break;
495                                case 'soap':
496                                        return $this->soap_functions;
497                                        break;
498                                default:
499                                        return array();
500                                        break;
501                        }
502                }
503
504                function set_owner_to_group($owner)
505                {
506                        print_debug('infolog::boinfolog::set_owner_to_group:owner',$owner);
507                        $this->owner = (int)$owner;
508                        $this->is_group = True;
509                        $this->g_owner = Array();
510                        $members = $GLOBALS['phpgw']->accounts->member($owner);
511                        if (is_array($members))
512                        {
513                                foreach($members as $user)
514                                {
515                                        // use only members which gave the user a read-grant
516                                        if ($this->check_perms(PHPGW_ACL_READ,0,$user['account_id']))
517                                        {
518                                                $this->g_owner[] = $user['account_id'];
519                                        }
520                                }
521                        }
522                        //echo "<p>".function_backtrace().": set_owner_to_group($owner) = ".print_r($this->g_owner,True)."</p>\n";
523                }
524
525                function member_of_group($owner=0)
526                {
527                        $owner = ($owner==0?$GLOBALS['phpgw_info']['user']['account_id']:$owner);
528                        $group_owners = $GLOBALS['phpgw']->accounts->membership();
529                        while($group_owners && list($index,$group_info) = each($group_owners))
530                        {
531                                if($this->owner == $group_info['account_id'])
532                                {
533                                        return True;
534                                }
535                        }
536                        return False;
537                }
538
539                function save_sessiondata($data='')
540                {
541                        if ($this->use_session)
542                        {
543                                if (!is_array($data))
544                                {
545                                        $data = array(
546                                                'filter'     => $this->filter,
547                                                'cat_id'     => $this->cat_id,
548                                                'owner'      => $this->owner,
549                                                'save_owner' => $this->save_owner,
550                                                'year'       => $this->year,
551                                                'month'      => $this->month,
552                                                'day'        => $this->day,
553                                                'date'       => $this->date,
554                                                'sortby'     => $this->sortby,
555                                                'num_months' => $this->num_months,
556                                                'return_to'  => $this->return_to
557                                        );
558                                }
559                                if($this->debug)
560                                {
561                                        if(floor(phpversion()) >= 4)
562                                        {
563                                                ob_start();
564                                        }
565                                        echo '<!-- '."\n".'Save:'."\n"._debug_array($data,False)."\n".' -->'."\n";
566                                        if(floor(phpversion()) >= 4)
567                                        {
568                                                $this->debug_string .= ob_get_contents();
569                                                ob_end_clean();
570                                        }
571                                }
572                                $GLOBALS['phpgw']->session->appsession('session_data','infolog',$data);
573                        }
574                }
575
576                function read_sessiondata()
577                {
578                        $data = $GLOBALS['phpgw']->session->appsession('session_data','infolog');
579                        print_debug('Read',_debug_array($data,False));
580
581                        $this->filter = $data['filter'];
582                        $this->cat_id = $data['cat_id'];
583                        $this->sortby = $data['sortby'];
584                        $this->owner  = (int)$data['owner'];
585                        $this->save_owner = (int)$data['save_owner'];
586                        $this->year   = (int)$data['year'];
587                        $this->month  = (int)$data['month'];
588                        $this->day    = (int)$data['day'];
589                        $this->num_months = (int)$data['num_months'];
590                        $this->return_to = $data['return_to'];
591                }
592
593                function read_entry()
594                {
595
596                        $event = $this->so->read_entry($id);
597                                echo $event;
598                       
599                       
600                        return False;
601                }
602
603                function delete_single($param)
604                {
605                        if($this->check_perms(PHPGW_ACL_DELETE,(int)$param['id']))
606                        {
607                                $temp_event = $this->get_cached_event();
608                                $event = $this->read_entry((int)$param['id']);
609//                              if($this->owner == $event['owner'])
610//                              {
611                                $exception_time = mktime($event['start']['hour'],$event['start']['min'],0,$param['month'],$param['day'],$param['year']) - $GLOBALS['phpgw']->datetime->tz_offset;
612                                $event['recur_exception'][] = (int)$exception_time;
613                                $this->so->cal->event = $event;
614//                              print_debug('exception time',$event['recur_exception'][count($event['recur_exception']) -1]);
615//                              print_debug('count event exceptions',count($event['recur_exception']));
616                                $this->so->add_entry($event);
617                                $cd = 16;
618
619                                $this->so->cal->event = $temp_event;
620                                unset($temp_event);
621                        }
622                        else
623                        {
624                                $cd = 60;
625                        }
626//                      }
627                        return $cd;
628                }
629
630                function delete_entry($id)
631                {
632                        if (is_array($id) && count($id) == 1)
633                        {
634                                list(,$id) = each($id);
635                        }
636                        if($this->check_perms(PHPGW_ACL_DELETE,$id))
637                        {
638                                $this->so->delete_entry($id);
639
640                                if ($this->xmlrpc)
641                                {
642                                        $this->so->expunge($id);
643                                }
644                                return $this->xmlrpc ? True : 16;
645                        }
646                        if ($this->xmlrpc)
647                        {
648                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
649                        }
650                        return 60;
651                }
652
653                function reinstate($params='')
654                {
655                        if($this->check_perms(PHPGW_ACL_EDIT,$params['cal_id']) && isset($params['reinstate_index']))
656                        {
657                                $event = $this->so->read_entry($params['cal_id']);
658                                @reset($params['reinstate_index']);
659                                print_debug('Count of reinstate_index',count($params['reinstate_index']));
660                                if(count($params['reinstate_index']) > 1)
661                                {
662                                        while(list($key,$value) = each($params['reinstate_index']))
663                                        {
664                                                print_debug('reinstate_index ['.$key.']',(int)$value);
665                                                print_debug('exception time',$event['recur_exception'][(int)$value]);
666                                                unset($event['recur_exception'][(int)$value]);
667                                                print_debug('count event exceptions',count($event['recur_exception']));
668                                        }
669                                }
670                                else
671                                {
672                                        print_debug('reinstate_index[0]',(int)$params['reinstate_index'][0]);
673                                        print_debug('exception time',$event['recur_exception'][(int)$params['reinstate_index'][0]]);
674                                        unset($event['recur_exception'][(int)$params['reinstate_index'][0]]);
675                                        print_debug('count event exceptions',count($event['recur_exception']));
676                                }
677                                $this->so->cal->event = $event;
678                                $this->so->add_entry($event);
679                                return 42;
680                        }
681                        else
682                        {
683                                return 43;
684                        }
685                }
686
687                function delete_infolog($owner)
688                {
689                        if($GLOBALS['phpgw_info']['user']['apps']['admin'])
690                        {
691                                $this->so->delete_infolog($owner);
692                        }
693                }
694
695                function change_owner($params='')
696                {
697                        if($GLOBALS['phpgw_info']['server']['infolog_type'] == 'sql')
698                        {
699                                if(is_array($params))
700                                {
701                                        $this->so->change_owner($params['old_owner'],$params['new_owner']);
702                                }
703                        }
704                }
705
706                function expunge()
707                {
708                        reset($this->so->cal->deleted_events);
709                        while(list($i,$event_id) = each($this->so->cal->deleted_events))
710                        {
711                                $event = $this->so->read_entry($event_id);
712                                if(!$this->ex_participants)
713                                        $this->ex_participants = html_entity_decode($event['ex_participants']);                 
714                                if($this->check_perms(PHPGW_ACL_DELETE,$event))
715                                {
716                                        $this->send_update(MSG_DELETED,$event['participants'],$event);
717                                }
718                                else
719                                {
720                                        unset($this->so->cal->deleted_events[$i]);
721                                }
722                        }
723                        $this->so->expunge();
724                }
725
726                function search_keywords($keywords)
727                {
728                        $type = $GLOBALS['phpgw']->accounts->get_type($this->owner);
729
730                        if($type == 'g')
731                        {
732                                $members = $GLOBALS['phpgw']->acl->get_ids_for_location($this->owner, 1, 'phpgw_group');
733                        }
734                        else
735                        {
736                                $members = array_keys($this->grants);
737
738                                if (!in_array($this->owner,$members))
739                                {
740                                        $members[] = $this->owner;
741                                }
742                        }
743                        foreach($members as $n => $uid)
744                        {
745                                if (!($this->grants[$uid] & PHPGW_ACL_READ))
746                                {
747                                        unset($members[$n]);
748                                }
749                        }
750
751
752                        return $this->so->list_events_keyword($keywords,$members);
753                }
754
755                function update($params='')
756                {
757
758                        if($params['from_mobile']) {
759                                $ui_return = "mobile.ui_mobileinfolog.edit";
760                                $ui_index = "mobile.ui_mobileinfolog.index";
761                                $ui_overlap = "mobile.ui_mobileinfolog.overlap";
762                        }
763                        else {
764                                $ui_return = "infolog.uiinfolog.edit";
765                                $ui_index = "infolog.uiinfolog.index";         
766                                $ui_overlap = "infolog.uiinfolog.overlap";
767                        }
768
769                        if(!is_object($GLOBALS['phpgw']->datetime))
770                        {
771                                $GLOBALS['phpgw']->datetime = createobject('phpgwapi.date_time');
772                        }
773                        $l_cal = (@isset($params['info_type']) && $params['info_type']?$params['info_type']:$_POST['info_type']);
774                        $l_participants = (@$params['participants']?$params['participants']:$_POST['participants']);
775                        $this->ex_participants = (@$params['ex_participants']?$params['ex_participants']:$_POST['ex_participants']);
776                        $l_categories = (@$params['categories']?$params['categories']:$_POST['categories']);
777                        $l_start = (@isset($params['start']) && $params['start']?$params['start']:$_POST['start']);
778                        $l_end = (@isset($params['end']) && $params['end']?$params['end']:$_POST['end']);
779                        $l_recur_enddate = (@isset($params['recur_enddate']) && $params['recur_enddate']?$params['recur_enddate']:$_POST['recur_enddate']);
780
781                       
782                        $send_to_ui = True;
783                        //if ((!is_array($l_start) || !is_array($l_end)) && !isset($_GET['readsess']))  // xmlrpc call
784                        if ($this->xmlrpc)      // xmlrpc call
785                        {
786
787                                $send_to_ui = False;
788
789                                $l_cal = $params;       // no extra array
790
791                                foreach(array('start','end','recur_enddate') as $name)
792                                {
793                                        $var = 'l_'.$name;
794                                        $$var = $GLOBALS['server']->iso86012date($params[$name]);
795                                        unset($l_cal[$name]);
796                                }
797
798                                if (!is_array($l_participants) || !count($l_participants))
799                                {
800                                        $l_participants = array($GLOBALS['phpgw_info']['user']['account_id'].'A');
801                                }
802                                else
803                                {
804                                        $l_participants = array();
805                                        foreach($params['participants'] as $user => $data)
806                                        {
807                                                $l_participants[] = $user.$data['status'];
808                                        }
809                                }
810
811                                unset($l_cal['participants']);
812
813                                if (!is_object($GLOBALS['phpgw']->categories))
814                                {
815                                        $GLOBALS['phpgw']->categories = CreateObject('phpgwapi.categories');
816                                }
817
818                                $l_categories = $GLOBALS['server']->xmlrpc2cats($params['category']);
819                                unset($l_cal['category']);
820
821                                // using access={public|private} in all modules via xmlrpc
822                                $l_cal['public'] = $params['access'] != 'private';
823                                unset($l_cal['access']);
824/*
825                                $fp = fopen('/tmp/xmlrpc.log','a+');
826                                ob_start();
827                                echo "\nboinfolog::update("; print_r($params); echo ")\n";
828                                //echo "\nl_start="; print_r($l_start);
829                                //echo "\nl_end="; print_r($l_end);
830                                fwrite($fp,ob_get_contents());
831                                ob_end_clean();
832                                fclose($fp);
833*/
834                        }
835
836                        print_debug('ID',$l_cal['id']);
837
838                        // don't wrap to the next day for no time
839                        if ($l_end['hour'] == 24 && $l_end['min'] == 0)
840                        {
841                                $l_end['hour'] = 23;
842                                $l_end['min'] = 59;
843                        }
844
845                        if(isset($_GET['readsess']))
846                        {
847
848                                $event = $this->restore_from_appsession();
849                                $event['title'] = stripslashes($event['title']);
850                                $event['description'] = stripslashes($event['description']);
851$event['description1'] = stripslashes($event['description1']);
852$event['participants1'] = stripslashes($event['participants1']);
853                                $event['ex_participants'] = stripslashes($event['ex_participants']);
854                                $datetime_check = $this->validate_update($event);
855                                if($datetime_check)
856                                {
857                                        ExecMethod($ui_return,
858                                                Array(
859                                                        'cd'            => $datetime_check,
860                                                        'readsess'      => 1
861                                                )
862                                        );
863                                        if(!$params['from_mobile'])
864                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
865                                        else
866                                                return;
867                                }
868                                $overlapping_events = False;
869                        }
870                        else
871                        {
872
873                                if((!$l_cal['id'] && !$this->check_perms(PHPGW_ACL_ADD)) ||
874                                   ($l_cal['id'] && !$this->check_perms(PHPGW_ACL_EDIT,$l_cal['id'])))
875                                {
876
877                                        if ($this->xmlrpc)
878                                        {
879                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
880                                        }
881                                        if (!$send_to_ui)
882                                        {
883                                                return array(($l_cal['id']?1:2) => 'permission denied');
884                                        }
885
886                                        ExecMethod($ui_index);
887
888
889                                        if(!$params['from_mobile'])
890                                                $GLOBALS['phpgw']->common->phpgw_exit();
891                                        else
892                                                return;
893                                }
894
895                                print_debug('Prior to fix_update_time()');
896
897                                $this->fix_update_time($l_start);
898
899                                $this->fix_update_time($l_end);
900
901                                if(!isset($l_cal['ex_participants']))
902                                {
903                                        $l_cal['ex_participants'] = $this->ex_participants;
904                                }
905
906                                if(!isset($l_categories))
907                                {
908                                        $l_categories = 0;
909                                }
910
911                                $is_public = ($l_cal['type'] != 'private' && $l_cal['type'] != 'privateHiddenFields');
912
913                                $this->so->event_init();
914
915                        $this->add_attribute('uid',$l_cal['uid']);
916
917                                $this->add_attribute('type',$l_cal['type']);
918
919                                if($l_cal['ex_participants']) {
920                                        $this->add_attribute('ex_participants',$l_cal['ex_participants']);
921                                }
922                                if(count($l_categories) >= 2)
923                                {
924                                        $this->so->set_category(implode(',',$l_categories));
925                                }
926                                else
927                                {
928                                        $this->so->set_category(strval($l_categories[0]));
929                                }
930                                $this->so->set_title($l_cal['title']);
931                                $this->so->set_description($l_cal['description']);
932$this->so->set_description1($l_cal['description1']);
933$this->so->set_participants1($l_cal['participants1']);
934                                $this->so->set_ex_participants($l_cal['ex_participants']);
935                                $this->so->set_start($l_start['year'],$l_start['month'],$l_start['mday'],$l_start['hour'],$l_start['min'],0);
936                                $this->so->set_end($l_end['year'],$l_end['month'],$l_end['mday'],$l_end['hour'],$l_end['min'],0);
937                                $this->so->set_class($is_public);
938                                $this->so->add_attribute('reference',(@isset($l_cal['reference']) && $l_cal['reference']?$l_cal['reference']:0));
939                                $this->so->add_attribute('location',(@isset($l_cal['location']) && $l_cal['location']?$l_cal['location']:''));
940                                if($l_cal['id'])
941                                {
942                                        $this->so->add_attribute('id',$l_cal['id']);
943                                }
944
945                                if($l_cal['rpt_use_end'] != 'y')
946                                {
947                                        $l_recur_enddate['year'] = 0;
948                                        $l_recur_enddate['month'] = 0;
949                                        $l_recur_enddate['mday'] = 0;
950                                }
951                                elseif (isset($l_recur_enddate['str']))
952                                {
953                                        $l_recur_enddate = $this->jscal->input2date($l_recur_enddate['str'],False,'mday');
954                                }
955
956                                switch((int)$l_cal['recur_type'])
957                                {
958
959
960                                        case MCAL_RECUR_NONE:
961                                                $this->so->set_recur_none();
962
963                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
964
965                                                break;
966                                        case MCAL_RECUR_DAILY:
967                                                $this->so->set_recur_daily((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
968
969                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
970
971                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
972                                                $init_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_init[1]),$tmp_init[0],$tmp_init[2]); // transforma a data inicial + hora + minuto em UNIX timestamp;
973
974                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
975                                                {
976
977                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
978                                                        $end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
979
980                                                }else { // se nao existe data final da repeticao (agendamento infinito):
981
982                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
983                                                }
984                                                break;
985                                        case MCAL_RECUR_WEEKLY:
986
987                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
988
989                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
990                                                $init_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_init[1]),$tmp_init[0],$tmp_init[2]); // transforma a data inicial + hora + minuto em UNIX timestamp;
991
992                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
993                                                {
994
995                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
996                                                        $end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
997
998                                                }else { // se nao existe data final da repeticao (agendamento infinito):
999
1000                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1001                                                }
1002
1003                                                foreach(array('rpt_sun','rpt_mon','rpt_tue','rpt_wed','rpt_thu','rpt_fri','rpt_sat') as $rpt_day)
1004                                                {
1005                                                        $l_cal['recur_data'] += (int)$l_cal[$rpt_day];
1006                                                }
1007                                                if (is_array($l_cal['rpt_day']))
1008                                                {
1009                                                        foreach ($l_cal['rpt_day'] as $mask)
1010                                                        {
1011                                                                $l_cal['recur_data'] |= (int)$mask;
1012                                                                $rpt_wdays = $l_cal['recur_data']; // recebe os dias da semana (somatorio) para repetir o alarme;
1013                                                        }
1014                                                }
1015                                                $this->so->set_recur_weekly((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval'],$l_cal['recur_data']);
1016                                                break;
1017                                        case MCAL_RECUR_MONTHLY_MDAY:
1018                                                $this->so->set_recur_monthly_mday((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
1019
1020                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1021
1022                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
1023                                                $init_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_init[1]),$tmp_init[0],$tmp_init[2]); // transforma a data inicial + hora + minuto em UNIX timestamp;
1024
1025                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
1026                                                {
1027
1028                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
1029                                                        $end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
1030
1031                                                }else { // se nao existe data final da repeticao (agendamento infinito):
1032
1033                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1034                                                }
1035                                                break;
1036                                        case MCAL_RECUR_MONTHLY_WDAY:
1037                                                $this->so->set_recur_monthly_wday((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
1038                                                break;
1039                                        case MCAL_RECUR_YEARLY:
1040                                                $this->so->set_recur_yearly((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
1041
1042                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1043
1044                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
1045                                                $init_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_init[1]),$tmp_init[0],$tmp_init[2]); // transforma a data inicial + hora + minuto em UNIX timestamp;
1046
1047                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
1048                                                {
1049
1050                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
1051                                                        $end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
1052
1053                                                }else { // se nao existe data final da repeticao (agendamento infinito):
1054
1055                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1056                                                }
1057                                                break;
1058                                }
1059
1060                                if($l_participants)
1061                                {
1062                                        $parts = $l_participants;
1063                                        $minparts = min($l_participants);
1064                                        $part = Array();
1065                                        for($i=0;$i<count($parts);$i++)
1066                                        {
1067                                                if (($accept_type = substr($parts[$i],-1,1)) == '0' || (int)$accept_type > 0)
1068                                                {
1069                                                        $accept_type = 'U';
1070                                                }
1071                                                $acct_type = $GLOBALS['phpgw']->accounts->get_type((int)$parts[$i]);
1072                                                if($acct_type == 'u')
1073                                                {
1074                                                        $part[(int)$parts[$i]] = $accept_type;
1075                                                }
1076                                                elseif($acct_type == 'g')
1077                                                {
1078                                                        $part[(int)$parts[$i]] = $accept_type;
1079                                                        $groups[] = $parts[$i];
1080                                                        /* This pulls ALL users of a group and makes them as participants to the event */
1081                                                        /* I would like to turn this back into a group thing. */
1082                                                        $acct = CreateObject('phpgwapi.accounts',(int)$parts[$i]);
1083                                                        $members = $acct->member((int)$parts[$i]);
1084                                                        unset($acct);
1085                                                        if($members == False)
1086                                                        {
1087                                                                continue;
1088                                                        }
1089                                                        while($member = each($members))
1090                                                        {
1091                                                                $part[$member[1]['account_id']] = $accept_type;
1092                                                        }
1093                                                }
1094                                        }
1095                                }
1096                                else
1097                                {
1098                                        $part = False;
1099                                }
1100
1101                                if($part)
1102                                {
1103                                        @reset($part);
1104                                        while(list($key,$accept_type) = each($part))
1105                                        {
1106                                                $this->so->add_attribute('participants',$accept_type,(int)$key);
1107                                        }
1108                                }
1109
1110                                if($groups)
1111                                {
1112                                        @reset($groups);
1113                                        $this->so->add_attribute('groups',(int)$group_id);
1114                                }
1115
1116                                $event = $this->get_cached_event();
1117                                if(!is_int($minparts))
1118                                {
1119                                        $minparts = $this->owner;
1120                                }
1121                                if(!@isset($event['participants'][$l_cal['owner']]))
1122                                {
1123                                        $this->so->add_attribute('owner',$minparts);
1124                                }
1125                                else
1126                                {
1127                                        $this->so->add_attribute('owner',$l_cal['owner']);
1128                                }
1129                                $this->so->add_attribute('priority',$l_cal['priority']);
1130
1131                                foreach($l_cal as $name => $value)
1132                                {
1133                                        if ($name[0] == '#')    // Custom field
1134                                        {
1135                                                $this->so->add_attribute($name,stripslashes($value));
1136                                        }
1137                                }
1138                                if (isset($_POST['preserved']) && is_array($preserved = unserialize(stripslashes($_POST['preserved']))))
1139                                {
1140                                        foreach($preserved as $name => $value)
1141                                        {
1142                                                switch($name)
1143                                                {
1144                                                        case 'owner':
1145                                                                $this->so->add_attribute('participants',$value,$l_cal['owner']);
1146                                                                break;
1147                                                        default:
1148                                                                $this->so->add_attribute($name,str_replace(array('&amp;','&quot;','&lt;','&gt;'),array('&','"','<','>'),$value));
1149                                                }
1150                                        }
1151                                }
1152                                $event = $this->get_cached_event();
1153
1154                                if ($l_cal['alarmdays'] > 0 || $l_cal['alarmhours'] > 0 ||
1155                                                $l_cal['alarmminutes'] > 0)
1156                                {
1157                                        $offset = ($l_cal['alarmdays'] * 24 * 3600) +
1158                                                ($l_cal['alarmhours'] * 3600) + ($l_cal['alarmminutes'] * 60);
1159
1160                                        $time = $this->maketime($event['start']) - $offset;
1161
1162                                        $event['alarm'][] = Array(
1163                                                'time'    => $time,
1164                                                'offset'  => $offset,
1165                                                'owner'   => $this->owner,
1166                                                'enabled' => 1,
1167                                                'repeat'  => $repetido, // para repetir alarme;
1168                                                'init_rept' => $init_rept, // inicio repeticao;
1169                                                'end_rept' => $end_rept, // fim repeticao;
1170                                                'rpt_wdays' => $rpt_wdays // dias repeticao da semana;
1171                                        );
1172                                }
1173
1174                                $this->store_to_appsession($event);
1175                                $datetime_check = $this->validate_update($event);
1176                                print_debug('bo->validated_update() returnval',$datetime_check);
1177
1178                                /*if($datetime_check)
1179                                {
1180
1181
1182                                        if (!$send_to_ui)
1183                                        {
1184                                                return array($datetime_check => 'invalid input data');
1185                                        }
1186
1187
1188                                        ExecMethod($ui_return,
1189                                                Array(
1190                                                        'cd'            => $datetime_check,
1191                                                        'readsess'      => 1
1192                                                )
1193                                        );
1194
1195                                        if(!$params['from_mobile'])
1196                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
1197                                        else
1198                                                return;
1199
1200                                }/*/
1201                                if($event['id'])
1202                                {
1203                                        $event_ids[] = $event['id'];
1204                                }
1205                                if($event['reference'])
1206                                {
1207                                        $event_ids[] = $event['reference'];
1208                                }
1209
1210                                $overlapping_events = $this->overlap(
1211                                        $this->maketime($event['start']),
1212                                        $this->maketime($event['end']),
1213                                        $event['participants'],
1214                                        $event['owner'],
1215                                        $event_ids
1216                                );
1217                        }
1218                        if(!$this->ex_participants)
1219                                $this->ex_participants = $event['ex_participants'];                     
1220                        if($overlapping_events)
1221                        {
1222
1223
1224                                if($send_to_ui)
1225                                {
1226                                        $event['ex_participants'] = $this->ex_participants;
1227                                        unset($GLOBALS['phpgw_info']['flags']['noheader']);
1228                                        unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
1229                                        ExecMethod($ui_overlap,
1230                                                Array(
1231                                                        'o_events'      => $overlapping_events,
1232                                                        'this_event'    => $event
1233                                                )
1234                                        );
1235                                        if(!$params['from_mobile'])
1236                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
1237                                        else
1238                                                return;
1239                                }
1240                                else
1241                                {
1242                                        return $overlapping_events;
1243                                }
1244                        }
1245                        else
1246                        {
1247
1248
1249
1250                                if(!$event['id'])
1251                                {
1252
1253
1254
1255                                        $this->so->add_entry($event);
1256                                        $this->send_update(MSG_ADDED,$event['participants'],'',$this->get_cached_event());
1257                                        print_debug('New Event ID',$event['id']);
1258                                }
1259                                else
1260                                {
1261
1262                                        print_debug('Updating Event ID',$event['id']);
1263                                        $new_event = $event;
1264                                        $old_event = $this->read_entry($event['id']);
1265                                        // if old event has alarm and the start-time changed => update them
1266                                        //echo "<p>checking ".count($old_event['alarm'])." alarms of event #$event[id] start moved from ".print_r($old_event['start'],True)." to ".print_r($event['start'],True)."</p>\n";
1267                                        if ($old_event['alarm'] &&
1268                                                $this->maketime($old_event['start']) != $this->maketime($event['start']))
1269                                        {
1270                                                $this->so->delete_alarms($old_event['id']);
1271                                                foreach($old_event['alarm'] as $id => $alarm)
1272                                                {
1273                                                        $alarm['time'] = $this->maketime($event['start']) - $alarm['offset'];
1274                                                        $event['alarm'][] = $alarm;
1275                                                }
1276                                                //echo "updated alarms<pre>".print_r($event['alarm'],True)."</pre>\n";
1277                                        }
1278                                        $this->so->cal->event = $event;
1279                                        $this->so->add_entry($event);
1280                                        $this->prepare_recipients($new_event,$old_event);
1281                                }
1282
1283                                $date = sprintf("%04d%02d%02d",$event['start']['year'],$event['start']['month'],$event['start']['mday']);
1284                                if($send_to_ui)
1285                                {
1286                                        $this->read_sessiondata();
1287                                        if ($this->return_to)
1288                                        {
1289                                                $GLOBALS['phpgw']->redirect_link('/index.php','menuaction='.$this->return_to);
1290                                                $GLOBALS['phpgw']->common->phpgw_exit();
1291                                        }
1292                                        Execmethod($ui_index);
1293                                }
1294                                else
1295                                {
1296                                        return (int)$event['id'];
1297                                }
1298                        }
1299                        return True;
1300                }
1301
1302                /* Private functions */
1303                function read_holidays($year=0)
1304                {
1305                        if(!$year)
1306                        {
1307                                $year = $this->year;
1308                        }
1309                        $holiday = CreateObject('infolog.boholiday');
1310                        $holiday->prepare_read_holidays($year,$this->owner);
1311                        $this->cached_holidays = $holiday->read_holiday();
1312                        unset($holiday);
1313                }
1314
1315                function user_is_a_member($event,$user)
1316                {
1317                        @reset($event['participants']);
1318                        $uim = False;
1319                        $security_equals = $GLOBALS['phpgw']->accounts->membership($user);
1320                        while(!$uim && $event['participants'] && $security_equals && list($participant,$status) = each($event['participants']))
1321                        {
1322                                if($GLOBALS['phpgw']->accounts->get_type($participant) == 'g')
1323                                {
1324                                        @reset($security_equals);
1325                                        while(list($key,$group_info) = each($security_equals))
1326                                        {
1327                                                if($group_info['account_id'] == $participant)
1328                                                {
1329                                                        return True;
1330                                                        $uim = True;
1331                                                }
1332                                        }
1333                                }
1334                        }
1335                        return $uim;
1336                }
1337
1338                function maketime($time)
1339                {
1340//echo "tttt".$time['month']."  ".$time['mday']."  ".$time['year']."<br>";
1341                        return mktime(intval($time['hour']),intval($time['min']),intval($time['sec']),intval($time['month']),intval($time['mday']),intval($time['year']));
1342                }
1343
1344function maketime2($hora,$min,$seg,$dia,$mes,$ano)
1345                {
1346
1347
1348                        return mktime(intval($hora),intval($min),intval($seg),intval($mes),intval($dia),intval($ano));
1349                }
1350                /*!
1351                @function time2array
1352                @abstract returns a date-array suitable for the start- or endtime of an event from a timestamp
1353                @syntax time2array($time,$alarm=0)
1354                @param $time the timestamp for the values of the array
1355                @param $alarm (optional) alarm field of the array, defaults to 0
1356                @author ralfbecker
1357                */
1358                function time2array($time,$alarm = 0)
1359                {
1360                        return array(
1361                                'year'  => (int)(date('Y',$time)),
1362                                'month' => (int)(date('m',$time)),
1363                                'mday'  => (int)(date('d',$time)),
1364                                'hour'  => (int)(date('H',$time)),
1365                                'min'   => (int)(date('i',$time)),
1366                                'sec'   => (int)(date('s',$time)),
1367                                'alarm' => (int)($alarm)
1368                        );
1369                }
1370
1371                /*!
1372                @function set_recur_date
1373                @abstract set the start- and enddates of a recuring event for a recur-date
1374                @syntax set_recur_date(&$event,$date)
1375                @param $event the event which fields to set (has to be the original event for start-/end-times)
1376                @param $date  the recuring date in form 'Ymd', eg. 20030226
1377                @author ralfbecker
1378                */
1379                function set_recur_date(&$event,$date)
1380                {
1381                        $org_start = $this->maketime($event['start']);
1382                        $org_end   = $this->maketime($event['end']);
1383                        $start = mktime($event['start']['hour'],$event['start']['min'],0,substr($date,4,2),substr($date,6,2),substr($date,0,4));
1384                        $end   = $org_end + $start - $org_start;
1385                        $event['start'] = $this->time2array($start);
1386                        $event['end']   = $this->time2array($end);
1387                }
1388
1389                function fix_update_time(&$time_param)
1390                {
1391                        if (isset($time_param['str']))
1392                        {
1393                                if (!is_object($this->jscal))
1394                                {
1395                                        $this->jscal = CreateObject('phpgwapi.jscalendar');
1396                                }
1397                                $time_param += $this->jscal->input2date($time_param['str'],False,'mday');
1398                                unset($time_param['str']);
1399                        }
1400                        if ($this->prefs['common']['timeformat'] == '12')
1401                        {
1402                                if ($time_param['ampm'] == 'pm')
1403                                {
1404                                        if ($time_param['hour'] <> 12)
1405                                        {
1406                                                $time_param['hour'] += 12;
1407                                        }
1408                                }
1409                                elseif ($time_param['ampm'] == 'am')
1410                                {
1411                                        if ($time_param['hour'] == 12)
1412                                        {
1413                                                $time_param['hour'] -= 12;
1414                                        }
1415                                }
1416
1417                                if($time_param['hour'] > 24)
1418                                {
1419                                        $time_param['hour'] -= 12;
1420                                }
1421                        }
1422                }
1423
1424                function validate_update($event)
1425                {
1426                        $error = 0;
1427                        // do a little form verifying
1428                        if (!count($event['participants']))
1429                        {
1430                                $error = 43;
1431                        }
1432                        elseif ($event['title'] == '')
1433                        {
1434                                $error = 40;
1435                        }
1436                        elseif (($GLOBALS['phpgw']->datetime->time_valid($event['start']['hour'],$event['start']['min'],0) == False) || ($GLOBALS['phpgw']->datetime->time_valid($event['end']['hour'],$event['end']['min'],0) == False))
1437                        {
1438                                $error = 41;
1439                        }
1440                        elseif (($GLOBALS['phpgw']->datetime->date_valid($event['start']['year'],$event['start']['month'],$event['start']['mday']) == False) || ($GLOBALS['phpgw']->datetime->date_valid($event['end']['year'],$event['end']['month'],$event['end']['mday']) == False) || ($GLOBALS['phpgw']->datetime->date_compare($event['start']['year'],$event['start']['month'],$event['start']['mday'],$event['end']['year'],$event['end']['month'],$event['end']['mday']) == 1))
1441                        {
1442                                $error = 42;
1443                        }
1444                        elseif ($GLOBALS['phpgw']->datetime->date_compare($event['start']['year'],$event['start']['month'],$event['start']['mday'],$event['end']['year'],$event['end']['month'],$event['end']['mday']) == 0)
1445                        {
1446                                if ($GLOBALS['phpgw']->datetime->time_compare($event['start']['hour'],$event['start']['min'],0,$event['end']['hour'],$event['end']['min'],0) == 1)
1447                                {
1448                                        $error = 42;
1449                                }
1450                        }
1451                        return $error;
1452                }
1453
1454                /*!
1455                @function participants_not_rejected($participants,$event)
1456                @abstract checks if any of the $particpants participates in $event and has not rejected it
1457                */
1458                function participants_not_rejected($participants,$event)
1459                {
1460                        //echo "participants_not_rejected()<br>participants =<pre>"; print_r($participants); echo "</pre><br>event[participants]=<pre>"; print_r($event['participants']); echo "</pre>\n";
1461                        foreach($participants as $uid => $status)
1462                        {
1463                                //echo "testing event[participants][uid=$uid] = '".$event['participants'][$uid]."'<br>\n";
1464                                if (isset($event['participants'][$uid]) && $event['participants'][$uid] != 'R' &&
1465                                        $status != 'R')
1466                                {
1467                                        return True;    // found not rejected participant in event
1468                                }
1469                        }
1470                        return False;
1471                }
1472
1473                function overlap($starttime,$endtime,$participants,$owner=0,$id=0,$restore_cache=False)
1474                {
1475//                      $retval = Array();
1476//                      $ok = False;
1477
1478/* This needs some attention.. by commenting this chunk of code it will fix bug #444265 */
1479
1480                        if($restore_cache)
1481                        {
1482                                $temp_cache_events = $this->cached_events;
1483                        }
1484
1485//                      $temp_start = (int)$GLOBALS['phpgw']->common->show_date($starttime,'Ymd');
1486//                      $temp_start_time = (int)($GLOBALS['phpgw']->common->show_date($starttime,'Hi');
1487//                      $temp_end = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Ymd');
1488//                      $temp_end_time = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Hi');
1489                        $temp_start = (int)(date('Ymd',$starttime));
1490                        $temp_start_time = (int)(date('Hi',$starttime));
1491                        $temp_end = (int)(date('Ymd',$endtime));
1492                        $temp_end_time = (int)(date('Hi',$endtime));
1493                        if($this->debug)
1494                        {
1495                                echo '<!-- Temp_Start: '.$temp_start.' -->'."\n";
1496                                echo '<!-- Temp_End: '.$temp_end.' -->'."\n";
1497                        }
1498
1499                        $users = Array();
1500                        if(count($participants))
1501                        {
1502                                while(list($user,$status) = each($participants))
1503                                {
1504                                        $users[] = $user;
1505                                }
1506                        }
1507                        else
1508                        {
1509                                $users[] = $this->owner;
1510                        }
1511
1512                        $possible_conflicts = $this->store_to_cache(
1513                                Array(
1514                                        'smonth'        => substr(strval($temp_start),4,2),
1515                                        'sday'  => substr(strval($temp_start),6,2),
1516                                        'syear' => substr(strval($temp_start),0,4),
1517                                        'emonth'        => substr(strval($temp_end),4,2),
1518                                        'eday'  => substr(strval($temp_end),6,2),
1519                                        'eyear' => substr(strval($temp_end),0,4),
1520                                        'owner' => $users
1521                                )
1522                        );
1523
1524                        if($this->debug)
1525                        {
1526                                echo '<!-- Possible Conflicts ('.($temp_start - 1).'): '.count($possible_conflicts[$temp_start - 1]).' -->'."\n";
1527                                echo '<!-- Possible Conflicts ('.$temp_start.'): '.count($possible_conflicts[$temp_start]).' '.count($id).' -->'."\n";
1528                        }
1529
1530                        if($possible_conflicts[$temp_start] || $possible_conflicts[$temp_end])
1531                        {
1532                                if($temp_start == $temp_end)
1533                                {
1534                                        if($this->debug)
1535                                        {
1536                                                echo '<!-- Temp_Start == Temp_End -->'."\n";
1537                                        }
1538                                        @reset($possible_conflicts[$temp_start]);
1539                                        while(list($key,$event) = each($possible_conflicts[$temp_start]))
1540                                        {
1541                                                $found = False;
1542                                                if($id)
1543                                                {
1544                                                        @reset($id);
1545                                                        while(list($key,$event_id) = each($id))
1546                                                        {
1547                                                                if($this->debug)
1548                                                                {
1549                                                                        echo '<!-- $id['.$key.'] = '.$id[$key].' = '.$event_id.' -->'."\n";
1550                                                                        echo '<!-- '.$event['id'].' == '.$event_id.' -->'."\n";
1551                                                                }
1552                                                                if($event['id'] == $event_id)
1553                                                                {
1554                                                                        $found = True;
1555                                                                }
1556                                                        }
1557                                                }
1558                                                if($this->debug)
1559                                                {
1560                                                        echo '<!-- Item found: '.$found.' -->'."<br>\n";
1561                                                }
1562                                                if(!$found)
1563                                                {
1564                                                        if($this->debug)
1565                                                        {
1566                                                                echo '<!-- Checking event id #'.$event['id'];
1567                                                        }
1568                                                        $temp_event_start = sprintf("%d%02d",$event['start']['hour'],$event['start']['min']);
1569                                                        $temp_event_end = sprintf("%d%02d",$event['end']['hour'],$event['end']['min']);
1570//                                                      if((($temp_start_time <= $temp_event_start) && ($temp_end_time >= $temp_event_start) && ($temp_end_time <= $temp_event_end)) ||
1571                                                        if(($temp_start_time <= $temp_event_start &&
1572                                                                $temp_end_time > $temp_event_start &&
1573                                                                $temp_end_time <= $temp_event_end ||
1574                                                                $temp_start_time >= $temp_event_start &&
1575                                                                $temp_start_time < $temp_event_end &&
1576                                                                $temp_end_time >= $temp_event_end ||
1577                                                                $temp_start_time <= $temp_event_start &&
1578                                                                $temp_end_time >= $temp_event_end ||
1579                                                                $temp_start_time >= $temp_event_start &&
1580                                                                $temp_end_time <= $temp_event_end) &&
1581                                                                $this->participants_not_rejected($participants,$event))
1582                                                        {
1583                                                                if($this->debug)
1584                                                                {
1585                                                                        echo ' Conflicts';
1586                                                                }
1587                                                                $retval[] = $event['id'];
1588                                                        }
1589                                                        if($this->debug)
1590                                                        {
1591                                                                echo ' -->'."\n";
1592                                                        }
1593                                                }
1594                                        }
1595                                }
1596                        }
1597                        else
1598                        {
1599                                $retval = False;
1600                        }
1601
1602                        if($restore_cache)
1603                        {
1604                                $this->cached_events = $temp_cache_events;
1605                        }
1606
1607                        return $retval;
1608                }
1609
1610                /*!
1611                @function check_perms( )
1612                @syntax check_perms($needed,$event=0,$other=0)
1613                @abstract Checks if the current user has the necessary ACL rights
1614                @author ralfbecker
1615                @discussion The check is performed on an event or general on the cal of an other user
1616                @param $needed necessary ACL right: PHPGW_ACL_{READ|EDIT|DELETE}
1617                @param $event event as array or the event-id or 0 for general check
1618                @param $other uid to check (if event==0) or 0 to check against $this->owner
1619                @note Participating in an event is considered as haveing read-access on that event, \
1620                        even if you have no general read-grant from that user.
1621                */
1622                function check_perms($needed,$event=0,$other=0)
1623                {
1624                        $event_in = $event;
1625                       
1626                        if (is_int($event) && $event == 0)
1627                        {
1628                                $owner = $other > 0 ? $other : $this->owner;
1629                        }
1630                        else
1631                        {
1632                                if (!is_array($event))
1633                                {
1634                                        $event = $this->so->read_entry((int) $event);
1635                                }
1636                                if (!is_array($event))
1637                                {
1638                                        if ($this->xmlrpc)
1639                                        {
1640                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['not_exist'],$GLOBALS['xmlrpcstr']['not_exist']);
1641                                        }
1642                                        return False;
1643                                }
1644                                $owner = $event['owner'];
1645                                $private = $event['public'] == False || $event['public'] == 0;
1646                        }
1647                        $user = $GLOBALS['phpgw_info']['user']['account_id'];
1648                        $grants = $this->grants[$owner];
1649
1650                        if (is_array($event) && $needed == PHPGW_ACL_READ)
1651                        {
1652                                // Check if the $user is one of the participants or has a read-grant from one of them
1653                                //
1654if($event['participants']){
1655                                foreach($event['participants'] as $uid => $accept)
1656                                {
1657                                        if ($this->grants[$uid] & PHPGW_ACL_READ || $uid == $user)
1658                                        {
1659                                                $grants |= PHPGW_ACL_READ;
1660                                                // if the $user is one of the participants read-grant private (restricted) too.
1661                                                if($uid == $user || ($this->grants[$uid] & PHPGW_ACL_PRIVATE)) {
1662                                                        $grants |= PHPGW_ACL_PRIVATE;
1663                                                }
1664                                                //break;
1665                                        }
1666                                }
1667}
1668                        }
1669
1670                        if ($GLOBALS['phpgw']->accounts->get_type($owner) == 'g' && $needed == PHPGW_ACL_ADD)
1671                        {
1672                                $access = False;        // a group can't be the owner of an event
1673                        }
1674                        else
1675                        {
1676                                $access = $user == $owner || $grants & $needed && (!$private || $grants & PHPGW_ACL_PRIVATE);
1677                        }
1678                        //echo "<p>".function_backtrace()." check_perms($needed,$event_id,$other) for user $user and needed_acl $needed: event='$event[title]': owner=$owner, private=$private, grants=$grants ==> access=$access</p>\n";
1679
1680                        return $access;
1681                }
1682
1683
1684                function display_status($user_status)
1685                {
1686                        if(@$this->prefs['infolog']['display_status'] && $user_status)
1687                        {
1688                                $user_status = substr($this->get_long_status($user_status),0,1);
1689
1690                                return ' ('.$user_status.')';
1691                        }
1692                        else
1693                        {
1694                                return '';
1695                        }
1696                }
1697
1698                function get_long_status($status_short)
1699                {
1700                        switch ($status_short)
1701                        {
1702                                case 'A':
1703                                        $status = lang('Accepted');
1704                                        break;
1705                                case 'R':
1706                                        $status = lang('Rejected');
1707                                        break;
1708                                case 'T':
1709                                        $status = lang('Tentative');
1710                                        break;
1711                                case 'U':
1712                                        $status = lang('No Response');
1713                                        break;
1714                        }
1715                        return $status;
1716                }
1717
1718                function is_private($event,$owner)
1719                {
1720                        if($owner == 0)
1721                        {
1722                                $owner = $this->owner;
1723                        }
1724                        if ($owner == $GLOBALS['phpgw_info']['user']['account_id'] || ($event['public']==1) || ($this->check_perms(PHPGW_ACL_PRIVATE,$event) && $event['public']==0) || $event['owner'] == $GLOBALS['phpgw_info']['user']['account_id'])
1725                        {
1726                                return False;
1727                        }
1728                        elseif($event['public'] == 0)
1729                        {
1730                                return True;
1731                        }
1732                        elseif($event['public'] == 2)
1733                        {
1734                                $is_private = True;
1735                                $groups = $GLOBALS['phpgw']->accounts->membership($owner);
1736                                while (list($key,$group) = each($groups))
1737                                {
1738                                        if (strpos(' '.implode(',',$event['groups']).' ',$group['account_id']))
1739                                        {
1740                                                return False;
1741                                        }
1742                                }
1743                        }
1744                        else
1745                        {
1746                                return False;
1747                        }
1748
1749                        return $is_private;
1750                }
1751
1752                function get_short_field($event,$is_private=True,$field='')
1753                {
1754
1755
1756                        if($is_private)
1757                        {
1758                                return lang('private');
1759                        }
1760
1761// cut off too long titles
1762                        elseif(strlen($event[$field]) > 19 && !$this->printer_friendly && $field=="title")
1763//                      elseif(strlen($event[$field]) > 19 && $this->printer_friendly)
1764                        {
1765// we dont use currently 160304
1766//                              return substr($event[$field], 0 , 19) . '&nbsp;...';
1767                                return $event[$field];
1768                        }
1769                        else
1770                        {
1771                                return $event[$field];
1772                        }
1773                }
1774
1775                function long_date($first,$last=0)
1776                {
1777                        if (!is_array($first))
1778                        {
1779                                $first = $this->time2array($raw = $first);
1780                                $first['raw'] = $raw;
1781                                $first['day'] = $first['mday'];
1782                        }
1783                        if ($last && !is_array($last))
1784                        {
1785                                $last = $this->time2array($raw = $last);
1786                                $last['raw'] = $raw;
1787                                $last['day'] = $last['mday'];
1788                        }
1789                        $datefmt = $this->prefs['common']['dateformat'];
1790
1791                        $month_before_day = strtolower($datefmt[0]) == 'm' ||
1792                                strtolower($datefmt[2]) == 'm' && $datefmt[4] == 'd';
1793
1794                        for ($i = 0; $i < 5; $i += 2)
1795                        {
1796                                switch($datefmt[$i])
1797                                {
1798                                        case 'd':
1799                                                $range .= $first['day'] . ($datefmt[1] == '.' ? '.' : '');
1800                                                if ($first['month'] != $last['month'] || $first['year'] != $last['year'])
1801                                                {
1802                                                        if (!$month_before_day)
1803                                                        {
1804                                                                $range .= ' '.lang(strftime('%B',$first['raw']));
1805                                                        }
1806                                                        if ($first['year'] != $last['year'] && $datefmt[0] != 'Y')
1807                                                        {
1808                                                                $range .= ($datefmt[0] != 'd' ? ', ' : ' ') . $first['year'];
1809                                                        }
1810                                                        if (!$last)
1811                                                        {
1812                                                                return $range;
1813                                                        }
1814                                                        $range .= ' - ';
1815
1816                                                        if ($first['year'] != $last['year'] && $datefmt[0] == 'Y')
1817                                                        {
1818                                                                $range .= $last['year'] . ', ';
1819                                                        }
1820
1821                                                        if ($month_before_day)
1822                                                        {
1823                                                                $range .= lang(strftime('%B',$last['raw']));
1824                                                        }
1825                                                }
1826                                                else
1827                                                {
1828                                                        $range .= ' - ';
1829                                                }
1830                                                $range .= ' ' . $last['day'] . ($datefmt[1] == '.' ? '.' : '');
1831                                                break;
1832                                        case 'm':
1833                                        case 'M':
1834                                                $range .= ' '.lang(strftime('%B',$month_before_day ? $first['raw'] : $last['raw'])) . ' ';
1835                                                break;
1836                                        case 'Y':
1837                                                $range .= ($datefmt[0] == 'm' ? ', ' : ' ') . ($datefmt[0] == 'Y' ? $first['year'].($datefmt[2] == 'd' ? ', ' : ' ') : $last['year'].' ');
1838                                                break;
1839                                }
1840                        }
1841                        return $range;
1842                }
1843
1844                function get_week_label()
1845                {
1846                        $first = $GLOBALS['phpgw']->datetime->gmtdate($GLOBALS['phpgw']->datetime->get_weekday_start($this->year, $this->month, $this->day));
1847                        $last = $GLOBALS['phpgw']->datetime->gmtdate($first['raw'] + 518400);
1848
1849                        return ($this->long_date($first,$last));
1850                }
1851
1852                function normalizeminutes(&$minutes)
1853                {
1854                        $hour = 0;
1855                        $min = (int)$minutes;
1856                        if($min >= 60)
1857                        {
1858                                $hour += $min / 60;
1859                                $min %= 60;
1860                        }
1861                        settype($minutes,'integer');
1862                        $minutes = $min;
1863                        return $hour;
1864                }
1865
1866                function splittime($time,$follow_24_rule=True)
1867                {
1868                        $temp = array('hour','minute','second','ampm');
1869                        $time = strrev($time);
1870                        $second = (int)(strrev(substr($time,0,2)));
1871                        $minute = (int)(strrev(substr($time,2,2)));
1872                        $hour   = (int)(strrev(substr($time,4)));
1873                        $hour += $this->normalizeminutes($minute);
1874                        $temp['second'] = $second;
1875                        $temp['minute'] = $minute;
1876                        $temp['hour']   = $hour;
1877                        $temp['ampm']   = '  ';
1878                        if($follow_24_rule == True)
1879                        {
1880                                if ($this->prefs['common']['timeformat'] == '24')
1881                                {
1882                                        return $temp;
1883                                }
1884
1885                                $temp['ampm'] = 'am';
1886
1887                                if ((int)$temp['hour'] > 12)
1888                                {
1889                                        $temp['hour'] = (int)((int)$temp['hour'] - 12);
1890                                        $temp['ampm'] = 'pm';
1891                                }
1892                                elseif ((int)$temp['hour'] == 12)
1893                                {
1894                                        $temp['ampm'] = 'pm';
1895                                }
1896                        }
1897                        return $temp;
1898                }
1899
1900                function get_exception_array($exception_str='')
1901                {
1902                        $exception = Array();
1903                        if(strpos(' '.$exception_str,','))
1904                        {
1905                                $exceptions = explode(',',$exception_str);
1906                                for($exception_count=0;$exception_count<count($exceptions);$exception_count++)
1907                                {
1908                                        $exception[] = (int)$exceptions[$exception_count];
1909                                }
1910                        }
1911                        elseif($exception_str != '')
1912                        {
1913                                $exception[] = (int)$exception_str;
1914                        }
1915                        return $exception;
1916                }
1917
1918                function build_time_for_display($fixed_time)
1919                {
1920                        $time = $this->splittime($fixed_time);
1921                        $str = $time['hour'].':'.((int)$time['minute']<=9?'0':'').$time['minute'];
1922
1923                        if ($this->prefs['common']['timeformat'] == '12')
1924                        {
1925                                $str .= ' ' . $time['ampm'];
1926                        }
1927
1928                        return $str;
1929                }
1930
1931                function sort_event($event,$date)
1932                {
1933                        $inserted = False;
1934                        if(isset($event['recur_exception']))
1935                        {
1936                                $event_time = mktime($event['start']['hour'],$event['start']['min'],0,(int)(substr($date,4,2)),(int)(substr($date,6,2)),(int)(substr($date,0,4))) - $GLOBALS['phpgw']->datetime->tz_offset;
1937                                while($inserted == False && list($key,$exception_time) = each($event['recur_exception']))
1938                                {
1939                                        if($this->debug)
1940                                        {
1941                                                echo '<!-- checking exception datetime '.$exception_time.' to event datetime '.$event_time.' -->'."\n";
1942                                        }
1943                                        if($exception_time == $event_time)
1944                                        {
1945                                                $inserted = True;
1946                                        }
1947                                }
1948                        }
1949                        if($this->cached_events[$date] && $inserted == False)
1950                        {
1951
1952                                if($this->debug)
1953                                {
1954                                        echo '<!-- Cached Events found for '.$date.' -->'."\n";
1955                                }
1956                                $year = substr($date,0,4);
1957                                $month = substr($date,4,2);
1958                                $day = substr($date,6,2);
1959
1960                                if($this->debug)
1961                                {
1962                                        echo '<!-- Date : '.$date.' Count : '.count($this->cached_events[$date]).' -->'."\n";
1963                                }
1964
1965                                for($i=0;$i<count($this->cached_events[$date]);$i++)
1966                                {
1967                                        if($this->cached_events[$date][$i]['id'] == $event['id'] || $this->cached_events[$date][$i]['reference'] == $event['id'])
1968                                        {
1969                                                if($this->debug)
1970                                                {
1971                                                        echo '<!-- Item already inserted! -->'."\n";
1972                                                }
1973                                                $inserted = True;
1974                                                break;
1975                                        }
1976                                        /* This puts all spanning events across multiple days up at the top. */
1977                                        if($this->cached_events[$date][$i]['recur_type'] == MCAL_RECUR_NONE)
1978                                        {
1979                                                if($this->cached_events[$date][$i]['start']['mday'] != $day && $this->cached_events[$date][$i]['end']['mday'] >= $day)
1980                                                {
1981                                                        continue;
1982                                                }
1983                                        }
1984                                        if(date('Hi',mktime($event['start']['hour'],$event['start']['min'],$event['start']['sec'],$month,$day,$year)) < date('Hi',mktime($this->cached_events[$date][$i]['start']['hour'],$this->cached_events[$date][$i]['start']['min'],$this->cached_events[$date][$i]['start']['sec'],$month,$day,$year)))
1985                                        {
1986                                                for($j=count($this->cached_events[$date]);$j>=$i;$j--)
1987                                                {
1988                                                        $this->cached_events[$date][$j] = $this->cached_events[$date][$j-1];
1989                                                }
1990                                                if($this->debug)
1991                                                {
1992                                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
1993                                                }
1994                                                $inserted = True;
1995                                                $this->cached_events[$date][$i] = $event;
1996                                                break;
1997                                        }
1998                                }
1999                        }
2000                        if(!$inserted)
2001                        {
2002                                if($this->debug)
2003                                {
2004                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
2005                                }
2006                                $this->cached_events[$date][] = $event;
2007                        }
2008                }
2009
2010                function check_repeating_events($datetime)
2011                {
2012                        @reset($this->repeating_events);
2013                        $search_date_full = date('Ymd',$datetime);
2014                        $search_date_year = date('Y',$datetime);
2015                        $search_date_month = date('m',$datetime);
2016                        $search_date_day = date('d',$datetime);
2017                        $search_date_dow = date('w',$datetime);
2018                        $search_beg_day = mktime(0,0,0,$search_date_month,$search_date_day,$search_date_year);
2019                        if($this->debug)
2020                        {
2021                                echo '<!-- Search Date Full = '.$search_date_full.' -->'."\n";
2022                        }
2023                        $repeated = $this->repeating_events;
2024                        $r_events = count($repeated);
2025                        for ($i=0;$i<$r_events;$i++)
2026                        {
2027                                $rep_events = $this->repeating_events[$i];
2028                                $id = $rep_events['id'];
2029                                $event_beg_day = mktime(0,0,0,$rep_events['start']['month'],$rep_events['start']['mday'],$rep_events['start']['year']);
2030                                if($rep_events['recur_enddate']['month'] != 0 && $rep_events['recur_enddate']['mday'] != 0 && $rep_events['recur_enddate']['year'] != 0)
2031                                {
2032                                        $event_recur_time = $this->maketime($rep_events['recur_enddate']);
2033                                }
2034                                else
2035                                {
2036                                        $event_recur_time = mktime(0,0,0,1,1,2030);
2037                                }
2038                                $end_recur_date = date('Ymd',$event_recur_time);
2039                                $full_event_date = date('Ymd',$event_beg_day);
2040
2041                                if($this->debug)
2042                                {
2043                                        echo '<!-- check_repeating_events - Processing ID - '.$id.' -->'."\n";
2044                                        echo '<!-- check_repeating_events - Recurring End Date - '.$end_recur_date.' -->'."\n";
2045                                }
2046
2047                                // only repeat after the beginning, and if there is an rpt_end before the end date
2048                                if (($search_date_full > $end_recur_date) || ($search_date_full < $full_event_date))
2049                                {
2050                                        continue;
2051                                }
2052
2053                                if ($search_date_full == $full_event_date)
2054                                {
2055                                        $this->sort_event($rep_events,$search_date_full);
2056                                        continue;
2057                                }
2058                                else
2059                                {
2060                                        $freq = $rep_events['recur_interval'];
2061                                        $freq = $freq ? $freq : 1;
2062                                        $type = $rep_events['recur_type'];
2063                                        switch($type)
2064                                        {
2065                                                case MCAL_RECUR_DAILY:
2066                                                        if($this->debug)
2067                                                        {
2068                                                                echo '<!-- check_repeating_events - MCAL_RECUR_DAILY - '.$id.' -->'."\n";
2069                                                        }
2070                                                       
2071                                                        if ($freq == 1 && $rep_events['recur_enddate']['month'] != 0 && $rep_events['recur_enddate']['mday'] != 0 && $rep_events['recur_enddate']['year'] != 0 && $search_date_full <= $end_recur_date)
2072                                                        {
2073                                                                $this->sort_event($rep_events,$search_date_full);
2074                                                        }
2075                                                        elseif (floor(($search_beg_day - $event_beg_day)/86400) % ($freq ? $freq : 1))
2076                                                        {
2077                                                                continue;
2078                                                        }
2079                                                        else
2080                                                        {
2081                                                                $this->sort_event($rep_events,$search_date_full);
2082                                                        }
2083                                                        break;
2084                                                case MCAL_RECUR_WEEKLY:
2085                                                        if (floor(($search_beg_day - $event_beg_day)/604800)  % ($freq ? $freq : 1))
2086                                                        {
2087                                                                continue;
2088                                                        }
2089                                                        $check = 0;
2090                                                        switch($search_date_dow)
2091                                                        {
2092                                                                case 0:
2093                                                                        $check = MCAL_M_SUNDAY;
2094                                                                        break;
2095                                                                case 1:
2096                                                                        $check = MCAL_M_MONDAY;
2097                                                                        break;
2098                                                                case 2:
2099                                                                        $check = MCAL_M_TUESDAY;
2100                                                                        break;
2101                                                                case 3:
2102                                                                        $check = MCAL_M_WEDNESDAY;
2103                                                                        break;
2104                                                                case 4:
2105                                                                        $check = MCAL_M_THURSDAY;
2106                                                                        break;
2107                                                                case 5:
2108                                                                        $check = MCAL_M_FRIDAY;
2109                                                                        break;
2110                                                                case 6:
2111                                                                        $check = MCAL_M_SATURDAY;
2112                                                                        break;
2113                                                        }
2114                                                        if ($rep_events['recur_data'] & $check)
2115                                                        {
2116                                                                $this->sort_event($rep_events,$search_date_full);
2117                                                        }
2118                                                        break;
2119                                                case MCAL_RECUR_MONTHLY_WDAY:
2120                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month']) % $freq)
2121                                                        {
2122                                                                continue;
2123                                                        }
2124
2125                                                        if (($GLOBALS['phpgw']->datetime->day_of_week($rep_events['start']['year'],$rep_events['start']['month'],$rep_events['start']['mday']) == $GLOBALS['phpgw']->datetime->day_of_week($search_date_year,$search_date_month,$search_date_day)) &&
2126                                                                (ceil($rep_events['start']['mday']/7) == ceil($search_date_day/7)))
2127                                                        {
2128                                                                $this->sort_event($rep_events,$search_date_full);
2129                                                        }
2130                                                        break;
2131                                                case MCAL_RECUR_MONTHLY_MDAY:
2132                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month'])  % ($freq ? $freq : 1))
2133                                                        {
2134                                                                continue;
2135                                                        }
2136                                                        if ($search_date_day == $rep_events['start']['mday'])
2137                                                        {
2138                                                                $this->sort_event($rep_events,$search_date_full);
2139                                                        }
2140                                                        break;
2141                                                case MCAL_RECUR_YEARLY:
2142                                                        if (($search_date_year - $rep_events['start']['year']) % ($freq ? $freq : 1))
2143                                                        {
2144                                                                continue;
2145                                                        }
2146                                                        if (date('dm',$datetime) == date('dm',$event_beg_day))
2147                                                        {
2148                                                                $this->sort_event($rep_events,$search_date_full);
2149                                                        }
2150                                                        break;
2151                                        }
2152                                }
2153                        }       // end for loop
2154                }       // end function
2155
2156                function store_to_cache($params)
2157                {
2158                        if(!is_array($params))
2159                        {
2160                                return False;
2161                        }
2162                        if (isset($params['start']) && ($datearr = $GLOBALS['server']->iso86012date($params['start'])))
2163                        {
2164                                $syear = $datearr['year'];
2165                                $smonth = $datearr['month'];
2166                                $sday = $datearr['mday'];
2167                                $this->xmlrpc = True;
2168                        }
2169                        else
2170                        {
2171                                $syear = $params['syear'];
2172                                $smonth = $params['smonth'];
2173                                $sday = $params['sday'];
2174                        }
2175                        if (isset($params['end']) && ($datearr = $GLOBALS['server']->iso86012date($params['end'])))
2176                        {
2177                                $eyear = $datearr['year'];
2178                                $emonth = $datearr['month'];
2179                                $eday = $datearr['mday'];
2180                                $this->xmlrpc = True;
2181                        }
2182                        else
2183                        {
2184                                $eyear = (isset($params['eyear'])?$params['eyear']:0);
2185                                $emonth = (isset($params['emonth'])?$params['emonth']:0);
2186                                $eday = (isset($params['eday'])?$params['eday']:0);
2187                        }
2188                        if (!isset($params['owner']) && @$this->xmlrpc)
2189                        {
2190                                $owner_id = $GLOBALS['phpgw_info']['user']['user_id'];
2191                        }
2192                        else
2193                        {
2194                                $owner_id = (isset($params['owner'])?$params['owner']:0);
2195                                if($owner_id==0 && $this->is_group)
2196                                {
2197                                        unset($owner_id);
2198                                        $owner_id = $this->g_owner;
2199                                        if($this->debug)
2200                                        {
2201                                                echo '<!-- owner_id in ('.implode(',',$owner_id).') -->'."\n";
2202                                        }
2203                                }
2204                        }
2205                        if(!$eyear && !$emonth && !$eday)
2206                        {
2207                                $edate = mktime(23,59,59,$smonth + 1,$sday + 1,$syear);
2208                                $eyear = date('Y',$edate);
2209                                $emonth = date('m',$edate);
2210                                $eday = date('d',$edate);
2211                        }
2212                        else
2213                        {
2214                                if(!$eyear)
2215                                {
2216                                        $eyear = $syear;
2217                                }
2218                                //Tratamento do valor final (mes) da pesquisa de eventos feita em $this->so->list_events.
2219                                //Se $emonth nao tem valor, recebe o valor de $smonth (que recebe $params['smonth']) e soma 1.
2220                                //O valor $params['emonth'] indica o mes final para a pesquisa de eventos, e passou a ser
2221                                //informado na a impressao de eventos mensais. Mudancas feitas em class.uiinfolog.inc.php,
2222                                //function display_month_print();
2223                                if(!$emonth)
2224                                {
2225                                        $emonth = $smonth + 1;
2226                                        if($emonth > 12)
2227                                        {
2228                                                $emonth = 1;
2229                                                $eyear++;
2230                                        }
2231                                }
2232                                if(!$eday)
2233                                {
2234                                        $eday = $sday + 1;
2235                                }
2236                                $edate = mktime(23,59,59,$emonth,$eday,$eyear);
2237                        }
2238                        //echo "<p>boinfolog::store_to_cache(".print_r($params,True).") syear=$syear, smonth=$smonth, sday=$sday, eyear=$eyear, emonth=$emonth, eday=$eday, xmlrpc='$param[xmlrpc]'</p>\n";
2239                        if($this->debug)
2240                        {
2241                                echo '<!-- Start Date : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2242                                echo '<!-- End   Date : '.sprintf("%04d%02d%02d",$eyear,$emonth,$eday).' -->'."\n";
2243                        }
2244                        //A variavel $month_print recebe o parametro 'saux' com o mes de inicio da pesquisa de eventos por
2245                        //$this->so->list_events. O valor do mes final da pesquisa e tratado no codigo acima;
2246                        //$month_ini = $params['saux'];
2247
2248                        if($owner_id)
2249                        {
2250                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2251                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2252                        }
2253                        else
2254                        {
2255                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2256                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2257                        }
2258
2259                        $c_cached_ids = count($cached_event_ids);
2260                        $c_cached_ids_repeating = count($cached_event_ids_repeating);
2261
2262                        if($this->debug)
2263                        {
2264                                echo '<!-- events cached : '.$c_cached_ids.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2265                                echo '<!-- repeating events cached : '.$c_cached_ids_repeating.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2266                        }
2267
2268                        $this->cached_events = Array();
2269
2270                        if($c_cached_ids == 0 && $c_cached_ids_repeating == 0)
2271                        {
2272                                return;
2273                        }
2274
2275                        $cache_start = (int)(sprintf("%04d%02d%02d",$syear,$smonth,$sday));
2276                        $cached_event=$this->get_cached_event();
2277                        if($c_cached_ids)
2278                        {
2279                                for($i=0;$i<$c_cached_ids;$i++)
2280                                {
2281                                        $event = $this->so->read_entry($cached_event_ids[$i]);
2282                                        if ($event['recur_type'])
2283                                        {
2284                                                continue;       // fetch recuring events only in 2. loop
2285                                        }
2286                                        $startdate = (int)(date('Ymd',$this->maketime($event['start'])));
2287                                        $enddate = (int)(date('Ymd',$this->maketime($event['end'])));
2288                                        $this->cached_events[$startdate][] = $event;
2289                                        if($startdate != $enddate)
2290                                        {
2291                                                $start['year'] = (int)(substr($startdate,0,4));
2292                                                $start['month'] = (int)(substr($startdate,4,2));
2293                                                $start['mday'] = (int)(substr($startdate,6,2));
2294                                                for($j=$startdate,$k=0;$j<=$enddate;$k++,$j=(int)(date('Ymd',mktime(0,0,0,$start['month'],$start['mday'] + $k,$start['year']))))
2295                                                {
2296                                                        $c_evt_day = count($this->cached_events[$j]) - 1;
2297                                                        if($c_evt_day < 0)
2298                                                        {
2299                                                                $c_evt_day = 0;
2300                                                        }
2301                                                        if($this->debug)
2302                                                        {
2303                                                                echo '<!-- Date: '.$j.' Count : '.$c_evt_day.' -->'."\n";
2304                                                        }
2305                                                        if($this->cached_events[$j][$c_evt_day]['id'] != $event['id'])
2306                                                        {
2307                                                                if($this->debug)
2308                                                                {
2309                                                                        echo '<!-- Adding Event for Date: '.$j.' -->'."\n";
2310                                                                }
2311                                                                $this->cached_events[$j][] = $event;
2312                                                        }
2313                                                        if ($j >= $cache_start && (@$params['no_doubles'] || @$this->xmlrpc))
2314                                                        {
2315                                                                break;  // add event only once on it's startdate
2316                                                        }
2317                                                }
2318                                        }
2319                                }
2320                        }
2321
2322                        $this->repeating_events = Array();
2323                        if($c_cached_ids_repeating)
2324                        {
2325                                for($i=0;$i<$c_cached_ids_repeating;$i++)
2326                                {
2327                                        $this->repeating_events[$i] = $this->so->read_entry($cached_event_ids_repeating[$i]);
2328                                        if($this->debug)
2329                                        {
2330                                                echo '<!-- Cached Events ID: '.$cached_event_ids_repeating[$i].' ('.sprintf("%04d%02d%02d",$this->repeating_events[$i]['start']['year'],$this->repeating_events[$i]['start']['month'],$this->repeating_events[$i]['start']['mday']).') -->'."\n";
2331                                        }
2332                                }
2333                                for($date=mktime(0,0,0,$smonth,$sday,$syear);$date<=$edate;$date += 86400)
2334                                {
2335                                        if($this->debug)
2336                                        {
2337                                                $search_date = date('Ymd',$date);
2338                                                echo '<!-- Calling check_repeating_events('.$search_date.') -->'."\n";
2339                                        }
2340                                        $this->check_repeating_events($date);
2341                                        if($this->debug)
2342                                        {
2343                                                echo '<!-- Total events found matching '.$search_date.' = '.count($this->cached_events[$search_date]).' -->'."\n";
2344                                                for($i=0;$i<count($this->cached_events[$search_date]);$i++)
2345                                                {
2346                                                        echo '<!-- Date: '.$search_date.' ['.$i.'] = '.$this->cached_events[$search_date][$i]['id'].' -->'."\n";
2347                                                }
2348                                        }
2349                                }
2350                        }
2351                        $retval = Array();
2352                        for($j=date('Ymd',mktime(0,0,0,$smonth,$sday,$syear)),$k=0;$j<=date('Ymd',mktime(0,0,0,$emonth,$eday,$eyear));$k++,$j=date('Ymd',mktime(0,0,0,$smonth,$sday + $k,$syear)))
2353                        {
2354                                if(is_array($this->cached_events[$j]))
2355                                {
2356                                        if ($this->xmlrpc)
2357                                        {
2358                                                foreach($this->cached_events[$j] as $event)
2359                                                {
2360                                                        $retval[] = $this->xmlrpc_prepare($event);
2361                                                }
2362                                        }
2363                                        else
2364                                        {
2365                                                $retval[$j] = $this->cached_events[$j];
2366                                        }
2367                                }
2368                        }
2369                        //echo "store_to_cache(".print_r($params,True).")=<pre>".print_r($retval,True)."</pre>\n";
2370                        $this->so->cal->event = $cached_event;
2371                        return $retval;
2372                }
2373
2374                function xmlrpc_prepare(&$event)
2375                {
2376                        $event['rights'] = $this->grants[$event['owner']];
2377
2378                        foreach(array('start','end','modtime','recur_enddate') as $name)
2379                        {
2380                                if (isset($event[$name]))
2381                                {
2382                                        $event[$name] = $GLOBALS['server']->date2iso8601($event[$name]);
2383                                }
2384                        }
2385                        if (is_array($event['recur_exception']))
2386                        {
2387                                foreach($event['recur_exception'] as $key => $timestamp)
2388                                {
2389                                        $event['recur_exception'][$key] = $GLOBALS['server']->date2iso8601($timestamp);
2390                                }
2391                        }
2392                        static $user_cache = array();
2393
2394                        if (!is_object($GLOBALS['phpgw']->perferences))
2395                        {
2396                                $GLOBALS['phpgw']->perferences = CreateObject('phpgwapi.preferences');
2397                        }
2398                        foreach($event['participants'] as $user_id => $status)
2399                        {
2400                                if (!isset($user_cache[$user_id]))
2401                                {
2402                                        $user_cache[$user_id] = array(
2403                                                'name'   => $GLOBALS['phpgw']->common->grab_owner_name($user_id),
2404                                                'email'  => $GLOBALS['phpgw']->perferences->email_address($user_id)
2405                                        );
2406                                }
2407                                $event['participants'][$user_id] = $user_cache[$user_id] + array(
2408                                        'status' => $status,
2409                                );
2410                        }
2411                        if (is_array($event['alarm']))
2412                        {
2413                                foreach($event['alarm'] as $id => $alarm)
2414                                {
2415                                        $event['alarm'][$id]['time'] = $GLOBALS['server']->date2iso8601($alarm['time']);
2416                                        if ($alarm['owner'] != $GLOBALS['phpgw_info']['user']['account_id'])
2417                                        {
2418                                                unset($event['alarm'][$id]);
2419                                        }
2420                                }
2421                        }
2422                        $event['category'] = $GLOBALS['server']->cats2xmlrpc(explode(',',$event['category']));
2423
2424                        // using access={public|privat} in all modules via xmlrpc
2425                        $event['access'] = $event['public'] ? 'public' : 'privat';
2426                        unset($event['public']);
2427
2428                        return $event;
2429                }
2430
2431                /* Begin Appsession Data */
2432                function store_to_appsession($event)
2433                {
2434                        $GLOBALS['phpgw']->session->appsession('entry','infolog',$event);
2435                }
2436
2437                function restore_from_appsession()
2438                {
2439//echo "quees";
2440                        $this->event_init();
2441                        $event = $GLOBALS['phpgw']->session->appsession('entry','infolog');
2442//echo "quees".$event;
2443                        $this->so->cal->event = $event;
2444                        return $event;
2445                }
2446                /* End Appsession Data */
2447
2448                /* Begin of SO functions */
2449                function get_cached_event()
2450                {
2451                        return $this->so->get_cached_event();
2452                }
2453
2454                function add_attribute($var,$value,$index='**(**')
2455                {
2456                        $this->so->add_attribute($var,$value,$index);
2457                }
2458
2459                function event_init()
2460                {
2461                        $this->so->event_init();
2462                }
2463
2464                function set_start($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2465                {
2466                        $this->so->set_start($year,$month,$day,$hour,$min,$sec);
2467                }
2468
2469                function set_end($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2470                {
2471                        $this->so->set_end($year,$month,$day,$hour,$min,$sec);
2472                }
2473
2474                function set_title($title='')
2475                {
2476                        $this->so->set_title($title);
2477                }
2478
2479                function set_description($description='')
2480                {
2481                        $this->so->set_description($description);
2482                }
2483
2484                function set_description1($description1='')
2485                {
2486                        $this->so->set_description1($description1);
2487                }
2488function set_participants1($participants1='')
2489                {
2490                        $this->so->set_participants1($participants1);
2491                }
2492                function set_ex_participants($ex_participants='')
2493                {
2494                        $this->so->set_ex_participants($ex_participants);
2495                }
2496
2497                function set_class($class)
2498                {
2499                        $this->so->set_class($class);
2500                }
2501
2502                function set_category($category='')
2503                {
2504                        $this->so->set_category($category);
2505                }
2506
2507                function set_alarm($alarm)
2508                {
2509                        $this->so->set_alarm($alarm);
2510                }
2511
2512                function set_recur_none()
2513                {
2514                        $this->so->set_recur_none();
2515                }
2516
2517                function set_recur_daily($year,$month,$day,$interval)
2518                {
2519                        $this->so->set_recur_daily($year,$month,$day,$interval);
2520                }
2521
2522                function set_recur_weekly($year,$month,$day,$interval,$weekdays)
2523                {
2524                        $this->so->set_recur_weekly($year,$month,$day,$interval,$weekdays);
2525                }
2526
2527                function set_recur_monthly_mday($year,$month,$day,$interval)
2528                {
2529                        $this->so->set_recur_monthly_mday($year,$month,$day,$interval);
2530                }
2531
2532                function set_recur_monthly_wday($year,$month,$day,$interval)
2533                {
2534                        $this->so->set_recur_monthly_wday($year,$month,$day,$interval);
2535                }
2536
2537                function set_recur_yearly($year,$month,$day,$interval)
2538                {
2539                        $this->so->set_recur_yearly($year,$month,$day,$interval);
2540                }
2541                /* End of SO functions */
2542
2543                function prepare_matrix($interval,$increment,$part,$fulldate)
2544                {
2545                        for($h=0;$h<24;$h++)
2546                        {
2547                                for($m=0;$m<$interval;$m++)
2548                                {
2549                                        $index = (($h * 10000) + (($m * $increment) * 100));
2550                                        $time_slice[$index]['marker'] = '&nbsp';
2551                                        $time_slice[$index]['description'] = '';
2552$time_slice[$index]['description1'] = '';
2553                                }
2554                        }
2555                        foreach($this->cached_events[$fulldate] as $event)
2556                        {
2557                                if ($event['participants'][$part] == 'R')
2558                                {
2559                                        continue;       // dont show rejected invitations, as they are free time
2560                                }
2561                                $eventstart = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset);
2562                                $eventend = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset);
2563                                $start = ($eventstart['hour'] * 10000) + ($eventstart['minute'] * 100);
2564                                $starttemp = $this->splittime("$start",False);
2565                                $subminute = 0;
2566                                for($m=0;$m<$interval;$m++)
2567                                {
2568                                        $minutes = $increment * $m;
2569                                        if((int)$starttemp['minute'] > $minutes && (int)$starttemp['minute'] < ($minutes + $increment))
2570                                        {
2571                                                $subminute = ($starttemp['minute'] - $minutes) * 100;
2572                                        }
2573                                }
2574                                $start -= $subminute;
2575                                $end =  ($eventend['hour'] * 10000) + ($eventend['minute'] * 100);
2576                                $endtemp = $this->splittime("$end",False);
2577                                $addminute = 0;
2578                                for($m=0;$m<$interval;$m++)
2579                                {
2580                                        $minutes = ($increment * $m);
2581                                        if($endtemp['minute'] < ($minutes + $increment) && $endtemp['minute'] > $minutes)
2582                                        {
2583                                                $addminute = ($minutes + $increment - $endtemp['minute']) * 100;
2584                                        }
2585                                }
2586                                $end += $addminute;
2587                                $starttemp = $this->splittime("$start",False);
2588                                $endtemp = $this->splittime("$end",False);
2589
2590                                for($h=$starttemp['hour'];$h<=$endtemp['hour'];$h++)
2591                                {
2592                                        $startminute = 0;
2593                                        $endminute = $interval;
2594                                        $hour = $h * 10000;
2595                                        if($h == (int)$starttemp['hour'])
2596                                        {
2597                                                $startminute = ($starttemp['minute'] / $increment);
2598                                        }
2599                                        if($h == (int)$endtemp['hour'])
2600                                        {
2601                                                $endminute = ($endtemp['minute'] / $increment);
2602                                        }
2603                                        $private = $this->is_private($event,$part);
2604                                        $time_display = $GLOBALS['phpgw']->common->show_date($eventstart['raw'],$this->users_timeformat).'-'.$GLOBALS['phpgw']->common->show_date($eventend['raw'],$this->users_timeformat);
2605                                        $time_description = '('.$time_display.') '.$this->get_short_field($event,$private,'title').$this->display_status($event['participants'][$part]);
2606                                        for($m=$startminute;$m<$endminute;$m++)
2607                                        {
2608                                                $index = ($hour + (($m * $increment) * 100));
2609                                                $time_slice[$index]['marker'] = '-';
2610                                                $time_slice[$index]['description'] = $time_description;
2611                                                $time_slice[$index]['id'] = $event['id'];
2612                                        }
2613                                }
2614                        }
2615                        return $time_slice;
2616                }
2617
2618                /*!
2619                @function set_status
2620                @abstract set the participant response $status for event $cal_id and notifies the owner of the event
2621                */
2622                function set_status($cal_id,$status)
2623                {
2624                        $status2msg = array(
2625                                REJECTED  => MSG_REJECTED,
2626                                TENTATIVE => MSG_TENTATIVE,
2627                                ACCEPTED  => MSG_ACCEPTED
2628                        );
2629                        if (!isset($status2msg[$status]))
2630                        {
2631                                return False;
2632                        }
2633                        $event = $this->so->read_entry($cal_id);
2634                        $account_id = $GLOBALS['phpgw_info']['user']['account_id'];
2635                        if(($status2msg[$status] == "5" && $event['participants'][$account_id] == "A") ||
2636                         ($status2msg[$status] == "3" && $event['participants'][$account_id] == "R")) {
2637                                return True;
2638                        }
2639                        $this->so->set_status($cal_id,$status);
2640                        $event = $this->so->read_entry($cal_id);
2641                        $this->send_update($status2msg[$status],$event['participants'],$event);
2642
2643                }
2644
2645                /*!
2646                @function update_requested
2647                @abstract checks if $userid has requested (in $part_prefs) updates for $msg_type
2648                @syntax update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2649                @param $userid numerical user-id
2650                @param $part_prefs preferces of the user $userid
2651                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2652                @param $old_event Event before the change
2653                @param $new_event Event after the change
2654                @returns 0 = no update requested, > 0 update requested
2655                */
2656                function update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2657                {
2658                        if ($msg_type == MSG_ALARM)
2659                        {
2660                                return True;    // always True for now
2661                        }
2662                        $want_update = 0;
2663
2664                        // the following switch fall-through all cases, as each included the following too
2665                        //
2666                        $msg_is_response = $msg_type == MSG_REJECTED || $msg_type == MSG_ACCEPTED || $msg_type == MSG_TENTATIVE;
2667
2668                        switch($ru = $part_prefs['infolog']['receive_updates'])
2669                        {
2670                                case 'responses':
2671                                        if ($msg_is_response)
2672                                        {
2673                                                ++$want_update;
2674                                        }
2675                                case 'modifications':
2676                                        if ($msg_type == MSG_MODIFIED)
2677                                        {
2678                                                ++$want_update;
2679                                        }
2680                                case 'time_change_4h':
2681                                case 'time_change':
2682                                        $diff = max(abs($this->maketime($old_event['start'])-$this->maketime($new_event['start'])),
2683                                                abs($this->maketime($old_event['end'])-$this->maketime($new_event['end'])));
2684                                        $check = $ru == 'time_change_4h' ? 4 * 60 * 60 - 1 : 0;
2685                                        if ($msg_type == MSG_MODIFIED && $diff > $check)
2686                                        {
2687                                                ++$want_update;
2688                                        }
2689                                case 'add_cancel':
2690                                        if ($old_event['owner'] == $userid && $msg_is_response ||
2691                                                $msg_type == MSG_DELETED || $msg_type == MSG_ADDED)
2692                                        {
2693                                                ++$want_update;
2694                                        }
2695                                        break;
2696                                case 'no':
2697                                        break;
2698                        }
2699                        //echo "<p>boinfolog::update_requested(user=$userid,pref=".$part_prefs['infolog']['receive_updates'] .",msg_type=$msg_type,".($old_event?$old_event['title']:'False').",".($old_event?$old_event['title']:'False').") = $want_update</p>\n";
2700                        return $want_update > 0;
2701                }
2702
2703        function create_vcard($event_array)
2704        {
2705        if(!is_array($event_array))
2706                return null;
2707        $tmpattach="BEGIN:Vinfolog\n"
2708        ."PRODID:-//Expresso Livre//infolog//EN\n"
2709        ."VERSION:1.0\n";
2710                foreach ($event_array as $event)
2711                {
2712                        // It translates int to string
2713                        if (!is_object($event) && !is_array($event) || !array_key_exists  ('end', $event))
2714                                $event = $event_array;
2715                        if ( $event['end']['month'] < 10 )
2716                                $end_event_month="0".$event['end']['month'];
2717                        else
2718                                $end_event_month=$event['end']['month'];
2719                        if ( $event['start']['month'] < 10 )
2720                                $start_event_month="0".$event['start']['month'];
2721                        else
2722                                $start_event_month=$event['start']['month'];
2723                        if ( $event['end']['mday'] < 10 )
2724                                $end_event_day="0".$event['end']['mday'];
2725                        else
2726                                $end_event_day=$event['end']['mday'];
2727                        if ( $event['start']['mday'] < 10 )
2728                                $start_event_day="0".$event['start']['mday'];
2729                        else
2730                                $start_event_day=$event['start']['mday'];
2731                        if ( $event['start']['hour'] < 10)
2732                                $start_event_hour="0".$event['start']['hour'];
2733                        else
2734                                $start_event_hour=$event['start']['hour'];
2735                        if ( $event['end']['hour'] < 10)
2736                                $end_event_hour="0".$event['end']['hour'];
2737                        else
2738                                $end_event_hour=$event['end']['hour'];
2739                               
2740                        if ( $event['start']['min'] < 10)
2741                                $start_event_min="0".$event['start']['min'];
2742                        else
2743                                $start_event_min=$event['start']['min'];
2744                        if ( $event['end']['min'] < 10)
2745                                $end_event_min="0".$event['end']['min'];
2746                        else
2747                                $end_event_min=$event['end']['min'];   
2748               
2749
2750                        $tmpattach.="BEGIN:VEVENT\n"
2751                        ."DTSTART:".$event['start'][year].$start_event_month.$start_event_day."T".$start_event_hour.$start_event_min."00Z\n"
2752                        ."DTEND:".$event[end][year].$end_event_month.$end_event_day."T".$end_event_hour.$end_event_min."00Z\n"
2753                        ."UID:Expresso-".$event[id].$event[uid]."\n"
2754                        ."LAST-MODIFIED:".time()."\n"
2755                        ."DESCRIPTION:".$event[description]."\n"
2756."DESCRIPTION1:".$event[description1]."\n"
2757."PARTICIPANTS1:".$event[participants1]."\n"
2758                        ."SUMMARY:".$event[title]."\n"
2759                        ."LOCATION:".$event[location]."\n"
2760                        ."END:VEVENT"."\n";
2761                }
2762                        $tmpattach.="END:Vinfolog\n";
2763                        return $tmpattach;
2764}
2765
2766                /*!
2767                @function send_update
2768                @abstract sends update-messages to certain participants of an event
2769                @syntax send_update($msg_type,$to_notify,$old_event,$new_event=False)
2770                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2771                @param $to_notify array with numerical user-ids as keys (!) (value is not used)
2772                @param $old_event Event before the change
2773                @param $new_event Event after the change
2774                */
2775                function send_update($msg_type,$to_notify,$old_event,$new_event=False,$user=False)
2776                {
2777                       
2778                        //echo "<p>boinfolog::send_update(type=$msg_type,to_notify="; print_r($to_notify); echo ", old_event="; print_r($old_event); echo ", new_event="; print_r($new_event); echo ", user=$user)</p>\n";
2779                        if (!is_array($to_notify))
2780                        {
2781                                $to_notify = array();
2782                        }
2783                        $owner = $old_event ? $old_event['owner'] : $new_event['owner'];
2784                        if ($owner && !isset($to_notify[$owner]) && $msg_type != MSG_ALARM)
2785                        {
2786                                $to_notify[$owner] = 'owner';   // always include the event-owner
2787                        }
2788                        $version = $GLOBALS['phpgw_info']['apps']['infolog']['version'];
2789
2790                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences();
2791                        $sender = $GLOBALS['phpgw_info']['user']['email'];
2792
2793                        $temp_tz_offset = $this->prefs['common']['tz_offset'];
2794                        $temp_timeformat = $this->prefs['common']['timeformat'];
2795                        $temp_dateformat = $this->prefs['common']['dateformat'];
2796
2797                        $tz_offset = ((60 * 60) * (int)$temp_tz_offset);
2798
2799                        if($old_event != False)
2800                        {
2801                                $t_old_start_time = $this->maketime($old_event['start']);
2802                                if($t_old_start_time < (time() - 86400))
2803                                {
2804                                        return False;
2805                                }
2806                        }
2807
2808                        $temp_user = $GLOBALS['phpgw_info']['user'];
2809
2810                        if (!$user)
2811                        {
2812                                $user = $this->owner;
2813                        }
2814                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences($user);
2815
2816                        $event = $msg_type == MSG_ADDED || $msg_type == MSG_MODIFIED ? $new_event : $old_event;
2817                        if($old_event != False)
2818                        {
2819                                $old_starttime = $t_old_start_time - $GLOBALS['phpgw']->datetime->tz_offset;
2820                        }
2821                        $starttime = $this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
2822                        $endtime   = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
2823
2824                        switch($msg_type)
2825                        {
2826                                case MSG_DELETED:
2827                                        $action = lang('Canceled');
2828                                        $msg = 'Canceled';
2829                                        $msgtype = '"infolog";';
2830                                        $method = 'cancel';
2831                                        $typesend = 1;
2832                                        break;
2833                                case MSG_MODIFIED:
2834                                        $action = lang('Modified');
2835                                        $msg = 'Modified';
2836                                        $msgtype = '"infolog"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2837                                        $method = 'request';
2838                                        $typesend = 2;
2839                                        break;
2840                                case MSG_ADDED:
2841                                        $action = lang('Added');
2842                                        $msg = 'Added';
2843                                        $msgtype = '"infolog"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2844                                        $method = 'request';
2845                                        $typesend = 3;
2846                                        break;
2847                                case MSG_REJECTED:
2848                                        $action = lang('Rejected');
2849                                        $msg = 'Response';
2850                                        $msgtype = '"infolog";';
2851                                        $method = 'reply';
2852                                        $typesend = 4;
2853                                        break;
2854                                case MSG_TENTATIVE:
2855                                        $action = lang('Tentative');
2856                                        $msg = 'Response';
2857                                        $msgtype = '"infolog";';
2858                                        $method = 'reply';
2859                                        $typesend = 5;
2860                                        break;
2861                                case MSG_ACCEPTED:
2862                                        $action = lang('Accepted');
2863                                        $msg = 'Response';
2864                                        $msgtype = '"infolog";';
2865                                        $method = 'reply';
2866                                        $typesend = 6;
2867                                        break;
2868                                case MSG_ALARM:
2869                                        $action = lang('Alarm');
2870                                        $msg = 'Alarm';
2871                                        $msgtype = '"infolog";';
2872                                        $method = 'publish';    // duno if thats right
2873                                        $typesend = 7;
2874                                        break;
2875                                default:
2876                                        $method = 'publish';
2877                                        $typesend = 8;
2878                        }
2879                        $notify_msg = $this->prefs['infolog']['notify'.$msg];
2880                        if (empty($notify_msg))
2881                        {
2882                                $notify_msg = $this->prefs['infolog']['notifyAdded'];   // use a default
2883                        }
2884                        $details = array(                       // event-details for the notify-msg
2885                                'id'          => $msg_type == MSG_ADDED ? $new_event['id'] : $old_event['id'],
2886                                'action'      => $action,
2887                        );
2888                        $event_arr = $this->event2array($event);
2889                        foreach($event_arr as $key => $val)
2890                        {
2891                                $details[$key] = $val['data'];
2892                        }
2893                       
2894                        $details['participants'] = implode("\n",$details['participants']);
2895
2896                        $details['link'] = $GLOBALS['phpgw_info']['server']['webserver_url'].'/index.php?menuaction=infolog.uiinfolog.view&cal_id='.$event['id'];
2897                        // if url is only a path, try guessing the rest ;-)
2898                        if ($GLOBALS['phpgw_info']['server']['webserver_url'][0] == '/')
2899                        {
2900                                $details['link'] = ($GLOBALS['phpgw_info']['server']['enforce_ssl'] ? 'https://' : 'http://').
2901                                        ($GLOBALS['phpgw_info']['server']['hostname'] ? $GLOBALS['phpgw_info']['server']['hostname'] : 'localhost').
2902                                        $details['link'];
2903                        }
2904                       
2905                        //Seta o email usando phpmailer
2906                        define('PHPGW_INCLUDE_ROOT','../');     
2907                        define('PHPGW_API_INC','../phpgwapi/inc');     
2908                        include_once(PHPGW_API_INC.'/class.phpmailer.inc.php');
2909                        $mail = new PHPMailer();
2910                        $mail->IsSMTP();
2911                        $boemailadmin = CreateObject('emailadmin.bo');
2912                        $emailadmin_profile = $boemailadmin->getProfileList();
2913                        $emailadmin = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
2914               
2915                        $mail->Host = $emailadmin['smtpServer'];
2916                        $mail->Port = $emailadmin['smtpPort'];
2917                        $mail->From = $GLOBALS['phpgw']->preferences->values['email'];
2918                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
2919                        $mail->IsHTML(true);
2920
2921                        // Aqui ï¿œ enviado o email
2922                        foreach($to_notify as $userid => $statusid)
2923                        {
2924                                $mail->ClearAttachments();
2925                               
2926                                $userid = (int)$userid;
2927
2928                                if ($statusid == 'R' || $GLOBALS['phpgw']->accounts->get_type($userid) == 'g')
2929                                {
2930                                        continue;       // dont notify rejected participants
2931                                }
2932                                if($userid != $GLOBALS['phpgw_info']['user']['account_id'] ||  $msg_type == MSG_ALARM)
2933                                {
2934                                        print_debug('Msg Type',$msg_type);
2935                                        print_debug('UserID',$userid);
2936
2937                                        $preferences = CreateObject('phpgwapi.preferences',$userid);
2938                                        $part_prefs = $preferences->read_repository();
2939
2940                                        if (!$this->update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event))
2941                                        {
2942                                                continue;
2943                                        }
2944                                        $GLOBALS['phpgw']->accounts->get_account_name($userid,$lid,$details['to-firstname'],$details['to-lastname']);
2945                                        $details['to-fullname'] = $GLOBALS['phpgw']->common->display_fullname('',$details['to-firstname'],$details['to-lastname']);
2946
2947                                        $to = $preferences->email_address($userid);
2948                                       
2949                                        if (empty($to) || $to[0] == '@' || $to[0] == '$')       // we have no valid email-address
2950                                        {
2951                                                //echo "<p>boinfolog::send_update: Empty email adress for user '".$details['to-fullname']."' ==> ignored !!!</p>\n";
2952                                                continue;
2953                                        }
2954                                        print_debug('Email being sent to',$to);
2955
2956                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $part_prefs['common']['tz_offset'];
2957                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $part_prefs['common']['timeformat'];
2958                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $part_prefs['common']['dateformat'];
2959
2960                                        $GLOBALS['phpgw']->datetime->tz_offset = ((60 * 60) * (int)$GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset']);
2961
2962                                        if($old_starttime)
2963                                        {
2964                                                $details['olddate'] = $GLOBALS['phpgw']->common->show_date($old_starttime);
2965                                        }
2966                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
2967                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
2968                                       
2969                                       
2970                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
2971                                       
2972                                        switch($part_prefs['infolog']['update_format'])
2973                                        {
2974                                                case  'extended':
2975                                                        //$body .= "\n\n".lang('Event Details follow').":\n";
2976                                                        $body = '';
2977                                                        $body .= "<br>".lang('Event Details follow')." :: ";
2978                                                        foreach($event_arr as $key => $val)
2979                                                        {
2980                                                                // titulo
2981                                                                if($key =='title')
2982                                                                {
2983                                                                        $var1 = $val['field'];
2984                                                                        $vardata1 = $details[$key];
2985                                                                }
2986                                                                //descricao
2987                                                                if($key =='description')
2988                                                                {
2989                                                                        $var2 = $val['field'];
2990                                                                        $vardata2 = $details[$key];
2991                                                                }
2992if($key =='description1')
2993                                                                {
2994                                                                        $var2 = $val['field'];
2995                                                                        $vardata2 = $details[$key];
2996                                                                }
2997
2998if($key =='participants1')
2999                                                                {
3000                                                                        $var2 = $val['field'];
3001                                                                        $vardata2 = $details[$key];
3002                                                                }
3003
3004                                                                //dt inicio
3005                                                                if($key =='startdate')
3006                                                                {
3007                                                                        switch(trim($part_prefs['common']['dateformat']))
3008                                                                        {
3009                                                                               
3010                                                                                case ($part_prefs['common']['dateformat'] === "m/d/Y" || $part_prefs['common']['dateformat'] === "m-d-Y" || $part_prefs['common']['dateformat'] === "m.d.Y"):
3011                                                                                        $var3 = $val['field'];
3012                                                                                        $vardata3 = $details[$key];
3013                                                                                        $newmounth3 = substr($vardata3,0,2);
3014                                                                                        $newday3 = substr($vardata3,3,2);
3015                                                                                        $newyear3 = substr($vardata3,6,4);
3016                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3017                                                                                        break;
3018                                                                                       
3019                                                                                case    ($part_prefs['common']['dateformat'] === "Y/d/m" || $part_prefs['common']['dateformat'] === "Y-d-m" || $part_prefs['common']['dateformat'] === "Y.d.m"):
3020
3021                                                                                        $var3 = $val['field'];
3022                                                                                        $vardata3 = $details[$key];
3023                                                                                        $newyear3 = substr($vardata3,0,4);
3024                                                                                        $newday3 = substr($vardata3,5,2);
3025                                                                                        $newmounth3 = substr($vardata3,8,2);
3026                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3027                                                                                        break;
3028
3029                                                                                case ($part_prefs['common']['dateformat'] === "Y/m/d" || $part_prefs['common']['dateformat'] === "Y-m-d" || $part_prefs['common']['dateformat'] === "Y.m.d"):
3030
3031                                                                                        $var3 = $val['field'];
3032                                                                                        $vardata3 = $details[$key];
3033                                                                                        $newyear3 = substr($vardata3,0,4);
3034                                                                                        $newmounth3 = substr($vardata3,5,2);
3035                                                                                        $newday3 = substr($vardata3,8,2);
3036                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3037                                                                                        break;
3038
3039                                                                                case ($part_prefs['common']['dateformat'] === "d/m/Y" || $part_prefs['common']['dateformat'] === "d-m-Y" || $part_prefs['common']['dateformat'] === "d.m.Y" || $part_prefs['common']['dateformat'] === "d-M-Y"):
3040                                                                               
3041                                                                                        $var3 = $val['field'];
3042                                                                                        $vardata3 = $details[$key];
3043                                                                                        $newday3 = substr($vardata3,0,2);
3044                                                                                        $newmounth3 = substr($vardata3,3,2);
3045                                                                                        $newyear3 = substr($vardata3,6,4);
3046                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3047                                                                                        break;
3048                                                                       
3049                                                                        }
3050                                                                       
3051                                                                }
3052                                                                //dt final
3053                                                                if($key =='enddate')
3054                                                                {
3055                                                                        $var4 = $val['field'];
3056                                                                        $vardata4 = $details[$key];
3057                                                                }
3058                                                                //localizacao
3059                                                                if($key =='location')
3060                                                                {
3061                                                                        $var8 = $val['field'];
3062                                                                        $vardata8 = $details[$key];
3063                                                                }
3064                                                                //participantes
3065                                                                if($key =='participants')
3066                                                                {
3067                                                                        $var5 = $val['field'];
3068                                                                        foreach($val['data'] as $NewKey => $NewVal)
3069                                                                        {
3070                                                                                //Research inside of ldap ( Pesquisa dentro do ldap )
3071                                                                                $newvalue = $this->so->search_uidNumber($to);
3072                                                                                foreach($newvalue as $tmp)
3073                                                                                {
3074                                                                                        $tmpmail = $tmp['mail'][0];
3075                                                                                        $tmpuid = $tmp['uidnumber'][0];
3076                                                                                        if( trim($tmpmail) == trim($to) & trim($tmpuid) == trim($NewKey))
3077                                                                                        {
3078                                                                                                        if($typesend == 3)
3079                                                                                                        {
3080
3081                                                                                                                $lang1 = lang("To See Commitment");
3082                                                                                                                $varbuttom = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=infolog.uiinfolog.view&cal_id=$event[id]&date=$newall3' method='POST'>
3083                                                                                                                                                                  <input type='submit' value='$lang1'>
3084                                                                                                                                                                   </form>";
3085                                                                                                                $lang2 = lang("To accept");
3086                                                                                                                $varbuttom1 ="<input type='submit' value='$lang2' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=infolog.uiinfolog.set_action&cal_id=$event[id]&action=3&response=1\",\"frontpage\",\"height=100,width=400,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
3087
3088                                                                                                                $lang3 = lang("To reject");
3089                                                                                                                $varbuttom2 ="<input type='submit' value='$lang3' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=infolog.uiinfolog.set_action&cal_id=$event[id]&action=0&response=0\",\"frontpage\",\"height=100,width=400,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
3090                                                                                                               
3091                                                                                                                $lang4 = lang("Alarm");
3092                                                                                                                $varbuttom3 = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=infolog.uialarm.manager method='POST'>
3093                                                                                                                                                                  <input type='submit' value='$lang4'>
3094                                                                                                                                                                  <input type='hidden' name='cal_id' value=$event[id]>
3095                                                                                                                                                                   </form>";
3096                                                                                                        }
3097                                                                                                        else
3098                                                                                                        {
3099                                                                                                                        $varbuttom  = "";
3100                                                                                                                        $varbuttom1 = "";
3101                                                                                                                        $varbuttom2 = "";
3102                                                                                                                        $varbuttom3 = "";
3103                                                                                                        }
3104                                                                                        }
3105                                                                                        // It only mounts variavel with the name of the participants of the list ( Monta a variavel somente com o nome dos participantes da lista)
3106                                                                                        if($typesend == 3)
3107                                                                                        {
3108                                                                                                list($tmpvardata5,$tmp2vardata5) = explode("(",$NewVal);
3109                                                                                                $vardata5 = $tmpvardata5."<br>";
3110                                                                                        }
3111                                                                                        else
3112                                                                                        {
3113                                                                                                $vardata5 = $NewVal."<br>";
3114                                                                                        }
3115                                                                               
3116                                                                                }
3117                                                                                $vardata6 .= $vardata5;
3118                                                                                unset($vardata5);
3119                                                                        }
3120                                                                }               
3121                                                        }
3122                                                        //To mount the message as text/html (Para montar a mensagem como text/html - /phpgwapi/inc/class.send.inc.php )
3123                                                        $content_type = "text/html";
3124                                                        //It mounts the body of the message (Monta o corpo da mensagem)
3125                                                       
3126                                                        // A constante PHPGW_APP_TPL nao existe para envio de alarmes (cront, asyncservice).
3127                                                        define ("PHPGW_APP_TPL",PHPGW_API_INC . "/../../infolog/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."");
3128                                                       
3129                                                        $body = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
3130                                                        $body->set_file(Array('infolog' => 'body_email.tpl'));
3131                                                        $body->set_block('infolog','list');
3132                                                        $var = Array(
3133                                                                'script'                        => $script,
3134                                                                'subject'                       => $body1,
3135                                                                'var1'                          => $var1,
3136                                                                'vardata1'                      => $vardata1,
3137                                                                'var2'                          => $var2,
3138                                                                'vardata2'                      => $vardata2,
3139                                                                'var3'                          => $var3,
3140                                                                'vardata3'                      => $vardata3,
3141                                                                'var4'                          => $var4,
3142                                                                'vardata4'                      => $vardata4,
3143                                                                'var5'                          => $var5,
3144                                                                'vardata6'                      => $vardata6,
3145                                                                'var8'                          => $var8,
3146                                                                'vardata8'                      => $vardata8,                                                   
3147                                                                'varbuttom'                     => $varbuttom,
3148                                                                'varbuttom1'            => $varbuttom1,
3149                                                                'varbuttom2'            => $varbuttom2,
3150                                                                'varbuttom3'            => $varbuttom3
3151                                                               
3152                                                        );
3153                                                        $body->set_var($var);
3154                                                        $tmpbody = $body->fp('out','list');
3155                                                                                                               
3156                                                        break;
3157
3158                                                case 'ical':
3159                                                        $content_type = "infolog; method=$method; name=infolog.ics";
3160/*                                                      if ($body != '')
3161                                                        {
3162                                                                $boundary = '----Message-Boundary';
3163                                                                $body .= "\n\n\n$boundary\nContent-type: text/$content_type\n".
3164                                                                        "Content-Disposition: inline\nContent-transfer-encoding: 7BIT\n\n";
3165                                                                $content_type = '';
3166                                                        }
3167*/
3168                                                        $body = ExecMethod('infolog.boiinfolog.export',array(
3169                                                                'l_event_id'  => $event['id'],
3170                                                                'method'      => $method,
3171                                                                'chunk_split' => False
3172                                                        ));
3173                                                        break;
3174                                        }
3175                                        $mail->AddAddress($to);
3176                                        $mail->Body = $tmpbody;
3177                                        $mail->From = $sender;
3178                                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3179                                        $mail->Sender = $mail->From;
3180                                        $mail->SenderName = $mail->FromName;
3181                                        $mail->Subject = $subject;
3182                                        unset($vardata5);
3183                                        unset($vardata6);
3184                                }
3185                        }
3186
3187                        //Inicializa variï¿œvel de retorno.
3188                        $returncode=true;                       
3189                        if(count($mail->to)) {                         
3190                                // Envia aviso a todos os participantes.
3191                                if(!$mail->Send()) {                           
3192                                        $returncode = false;
3193                                        $errorInfo['participants'] = $mail->ErrorInfo;
3194                                }
3195                                else
3196                                        $returncode =  true;
3197                        }
3198                       
3199                        if(count($to_notify) && $this->ex_participants){
3200                                $mail->ClearAllRecipients();
3201                                $var = explode(",",trim($this->ex_participants));
3202                                $to = array();
3203                                if(!$subject) {
3204                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
3205                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
3206                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
3207                                }
3208                               
3209                                foreach($var as $index => $ex_participant){
3210                                        $ex_participant = trim($ex_participant);
3211                                        $ex_participant = preg_replace('#"(.*)" <(.*)\@(.*)\.(.*)>#','\\2@\\3.\\4',$ex_participant);
3212                                                if($ex_participant)
3213                                                        $to[] = $ex_participant;
3214                                }               
3215                               
3216                                foreach($to as $i => $to_array)
3217                                        $mail->AddAddress($to_array);
3218                               
3219                                $_body = explode("<hr size='1' width='100%'>",$tmpbody);
3220                                $tmpbody = $_body[0] ? $_body[0] : $subject ;
3221                                $tmpbody.= "<br><b>".lang("external participants").":: </b> ".htmlentities($this->ex_participants);
3222                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3223                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";
3224                                $tmpbody.= "<br><br><hr size='1' width='100%'><font color='red'>"
3225                                .lang("This message was sent by server. You must send a message to sender to confirm this event")."<br>"
3226                                .lang("This is an external event. Even if it added to your expresso its can be changed any time at all")."</font><br>";
3227                               
3228                                if ($GLOBALS['boinfolog']->so->cal->event[start][month] > 10)
3229                                        $event_month=$GLOBALS['boinfolog']->so->cal->event[start][month];
3230                                else
3231                                        $event_month="0".$GLOBALS['boinfolog']->so->cal->event[start][month];
3232                                //attach extern vcard                   
3233                                // define('context','$GLOBALS.boinfolog.so.cal.event');
3234                                $tmpattach = $this->create_vcard($GLOBALS['boinfolog']->so->cal->event);
3235                                if($tmpattach){                                 
3236                                        $tmpbody .="<a href='../index.php?menuaction=infolog.uiinfolog.add&date="
3237                                        .$GLOBALS['boinfolog']->so->cal->event[start][year]
3238                                .$event_month
3239                                .$GLOBALS['boinfolog']->so->cal->event[start][mday]
3240                                        ."&hour=".$GLOBALS['boinfolog']->so->cal->event[start][hour]
3241                                        ."&minute=".$GLOBALS['boinfolog']->so->cal->event[start][min]
3242                                        ."&title=".$GLOBALS['boinfolog']->so->cal->event['title']
3243                                        ."&description=".$GLOBALS['boinfolog']->so->cal->event['description']
3244."&description1=".$GLOBALS['boinfolog']->so->cal->event['description1']
3245."&participants1=".$GLOBALS['boinfolog']->so->cal->event['participants1']
3246                                        ."&location=".$GLOBALS['boinfolog']->so->cal->event['location']."'>"
3247                                        ."<h2>".lang("Add to my expresso")."</h2>";
3248                                        $tempdir = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
3249                                        srand((double)microtime()*1000000);
3250                                        $random_number = rand(100000000,999999999);
3251                                        $newfilename = md5(time() . getenv("REMOTE_ADDR") . $random_number );
3252                                        $filename = $tempdir . $newfilename;
3253                                        $attach_fd = fopen($filename,"w+");
3254                                        fwrite($attach_fd,$tmpattach);
3255                                        $mail->AddAttachment($filename, "extern.vcard", "base64", "text/plain"); // "application/octet-stream"
3256                                        fclose($attach_fd);
3257                                }
3258                                $mail->From = $sender;
3259                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3260                                $mail->Sender = $mail->From;
3261                                $mail->SenderName = $mail->FromName;
3262                                $mail->Subject = lang("External event from Expresso");
3263                                $mail->Body = $tmpbody;
3264                                                                                                                                               
3265                                if(!$mail->Send())
3266                                {
3267                                        $returncode=false;
3268                                        $errorInfo['ex_participants'] = $mail->ErrorInfo;
3269                                }
3270                                else
3271                                {
3272                                        $returncode=true;
3273                                }
3274                        }
3275
3276
3277                        if((is_int($this->user) && $this->user != $temp_user['account_id']) ||
3278                                (is_string($this->user) && $this->user != $temp_user['account_lid']))
3279                        {
3280                                $GLOBALS['phpgw_info']['user'] = $temp_user;
3281                        }       
3282
3283                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $temp_tz_offset;
3284                        $GLBOALS['phpgw']->datetime->tz_offset = ((60 * 60) * $temp_tz_offset);
3285                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $temp_timeformat;
3286                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $temp_dateformat;
3287                       
3288                        // Notifica por email o criador do compromisso, com as possï¿œveis falhas.                                             
3289                        if($errorInfo) {
3290                                $tmpbody = "<font color='red'>".lang("The following commitment had problems for DELIVERING the NOTIFICATION messages.").".</font><br>";
3291                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3292                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";                         
3293                                $tmpbody.= "<br><u>".lang("Failed to delivery")."</u><br>";
3294                                $failed = false;                               
3295                                if(strstr($errorInfo['participants'],"recipients_failed")){
3296                                        $failed = explode("recipients_failed",$errorInfo['participants']);
3297                                        $tmpbody.= lang("to").": ".$failed[1];
3298                                }
3299                                if(strstr($errorInfo['ex_participants'],"recipients_failed")){
3300                                        $failed = explode("recipients_failed",$errorInfo['ex_participants']);
3301                                        $tmpbody.= lang("to").": ".$failed[1];
3302                                }                       
3303                                if(!$failed) {
3304                                        $tmpbody.= lang("Description").":<br>";
3305$tmpbody.= lang("Description1").":<br>";
3306$tmpbody.= lang("participants1").":<br>";
3307                                        $tmpbody.= $errorInfo['participants'];
3308                                        $tmpbody.= "<br>".$errorInfo['ex_participants'];
3309                                }
3310                                $tmpbody.= "<br>".lang("Subject").": ".$subject;
3311                                // Reinicializa o objeto, devido ao erro anterior na entrega.
3312                               
3313                                $mail = new PHPMailer();
3314                                $mail->IsSMTP();
3315                                $mail->Host = $emailadmin['smtpServer'];
3316                                $mail->Port = $emailadmin['smtpPort'];
3317                                $mail->From = $sender;
3318                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3319                                $mail->Sender = $mail->From;
3320                                $mail->SenderName = $mail->FromName;
3321                                $mail->IsHTML(True);
3322                                $mail->Subject = lang("infolog event")." - ".lang("email notification");                                                       
3323                                $mail->Body = $tmpbody;                                 
3324                                $mail->AddAddress($sender);
3325                                if(!$mail->Send())                     
3326                                        $returncode = false;
3327                                else
3328                                        $returncode =  true;
3329                        }
3330                        return $returncode;
3331                }
3332               
3333                function send_alarm($alarm)
3334                {
3335                        //echo "<p>boinfolog::send_alarm("; print_r($alarm); echo ")</p>\n";
3336                       
3337                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->owner = $alarm['owner'];
3338
3339                        if (!$alarm['enabled'] || !$alarm['owner'] || !$alarm['cal_id'] || !($event = $this->so->read_entry($alarm['cal_id'])))
3340                        {
3341                                return False;   // event not found
3342                        }
3343                        if ($alarm['all'])
3344                        {
3345                                $to_notify = $event['participants'];
3346                        }
3347                        elseif ($this->check_perms(PHPGW_ACL_READ,$event))      // checks agains $this->owner set to $alarm[owner]
3348                        {
3349                                $to_notify[$alarm['owner']] = 'A';
3350                        }
3351                        else
3352                        {
3353                                return False;   // no rights
3354                        }
3355                        return $this->send_update(MSG_ALARM,$to_notify,$event,False,$alarm['owner']);
3356                }
3357
3358                function get_alarms($event_id)
3359                {
3360                        return $this->so->get_alarm($event_id);
3361                }
3362
3363                function alarm_today($event,$today,$starttime)
3364                {
3365                        $found = False;
3366                        @reset($event['alarm']);
3367                        $starttime_hi = $GLOBALS['phpgw']->common->show_date($starttime,'Hi');
3368                        $t_appt['month'] =$GLOBALS['phpgw']->common->show_date($today,'m');
3369                        $t_appt['mday'] = $GLOBALS['phpgw']->common->show_date($today,'d');
3370                        $t_appt['year'] = $GLOBALS['phpgw']->common->show_date($today,'Y');
3371                        $t_appt['hour'] = $GLOBALS['phpgw']->common->show_date($starttime,'H');
3372                        $t_appt['min']  = $GLOBALS['phpgw']->common->show_date($starttime,'i');
3373                        $t_appt['sec']  = 0;
3374                        $t_time = $this->maketime($t_appt) - $GLOBALS['phpgw']->datetime->tz_offset;
3375                        $y_time = $t_time - 86400;
3376                        $tt_time = $t_time + 86399;
3377                        print_debug('T_TIME',$t_time.' : '.$GLOBALS['phpgw']->common->show_date($t_time));
3378                        print_debug('Y_TIME',$y_time.' : '.$GLOBALS['phpgw']->common->show_date($y_time));
3379                        print_debug('TT_TIME',$tt_time.' : '.$GLOBALS['phpgw']->common->show_date($tt_time));
3380                        while(list($key,$alarm) = each($event['alarm']))
3381                        {
3382                                if($alarm['enabled'])
3383                                {
3384                                        print_debug('TIME',$alarm['time'].' : '.$GLOBALS['phpgw']->common->show_date($alarm['time']).' ('.$event['id'].')');
3385                                        if($event['recur_type'] != MCAL_RECUR_NONE)   /* Recurring Event */
3386                                        {
3387                                                print_debug('Recurring Event');
3388                                                if($alarm['time'] > $y_time && $GLOBALS['phpgw']->common->show_date($alarm['time'],'Hi') < $starttime_hi && $alarm['time'] < $t_time)
3389                                                {
3390                                                        $found = True;
3391                                                }
3392                                        }
3393                                        elseif($alarm['time'] > $y_time && $alarm['time'] < $t_time)
3394                                        {
3395                                                $found = True;
3396                                        }
3397                                }
3398                        }
3399                        print_debug('Found',$found);
3400                        return $found;
3401                }
3402
3403                function prepare_recipients(&$new_event,$old_event)
3404                {
3405                                               
3406                        // Find modified and deleted users.....
3407                        while(list($old_userid,$old_status) = each($old_event['participants']))
3408                        {
3409                                if(isset($new_event['participants'][$old_userid]))
3410                                {
3411                                        print_debug('Modifying event for user',$old_userid);
3412                                        $this->modified[(int)$old_userid] = $new_status;
3413                                }
3414                                else
3415                                {
3416                                        print_debug('Deleting user from the event',$old_userid);
3417                                        $this->deleted[(int)$old_userid] = $old_status;
3418                                }
3419                        }
3420                        // Find new users.....
3421                        while(list($new_userid,$new_status) = each($new_event['participants']))
3422                        {
3423                                if(!isset($old_event['participants'][$new_userid]))
3424                                {
3425                                        print_debug('Adding event for user',$new_userid);
3426                                        $this->added[$new_userid] = 'U';
3427                                        $new_event['participants'][$new_userid] = 'U';
3428                                }
3429                        }
3430                       
3431                        if(count($this->added) > 0 || count($this->modified) > 0 || count($this->deleted) > 0)
3432                        {
3433                                if(count($this->added) > 0)
3434                                {
3435                                        $this->ex_participants = '';
3436                                        $this->send_update(MSG_ADDED,$this->added,'',$new_event);
3437                                }
3438                                if(count($this->modified) > 0)
3439                                {
3440                                        $this->send_update(MSG_MODIFIED,$this->modified,$old_event,$new_event);
3441                                }
3442                                if(count($this->deleted) > 0)
3443                                {
3444                                        $this->ex_participants = '';
3445                                        $this->send_update(MSG_DELETED,$this->deleted,$old_event);
3446                                }
3447                        }
3448                }
3449
3450                function remove_doubles_in_cache($firstday,$lastday)
3451                {
3452                        $already_moved = Array();
3453                        for($v=$firstday;$v<=$lastday;$v++)
3454                        {
3455                                if (!$this->cached_events[$v])
3456                                {
3457                                        continue;
3458                                }
3459                                $cached = $this->cached_events[$v];
3460                                $this->cached_events[$v] = array();
3461                                while (list($g,$event) = each($cached))
3462                                {
3463                                        $end = date('Ymd',$this->maketime($event['end']));
3464                                        print_debug('EVENT',_debug_array($event,False));
3465                                        print_debug('start',$start);
3466                                        print_debug('v',$v);
3467
3468                                        if (!isset($already_moved[$event['id']]) || $event['recur_type'] && $v > $end)
3469                                        {
3470                                                $this->cached_events[$v][] = $event;
3471                                                $already_moved[$event['id']] = 1;
3472                                                print_debug('Event moved');
3473                                        }
3474                                }
3475                        }
3476                }
3477
3478                function get_dirty_entries($lastmod=-1)
3479                {
3480                        $events = false;
3481                        $event_ids = $this->so->cal->list_dirty_events($lastmod);
3482                        if(is_array($event_ids))
3483                        {
3484                                foreach($event_ids as $key => $id)
3485                                {
3486                                        $events[$id] = $this->so->cal->fetch_event($id);
3487                                }
3488                        }
3489                        unset($event_ids);
3490
3491                        $rep_event_ids = $this->so->cal->list_dirty_events($lastmod,$true);
3492                        if(is_array($rep_event_ids))
3493                        {
3494                                foreach($rep_event_ids as $key => $id)
3495                                {
3496                                        $events[$id] = $this->so->cal->fetch_event($id);
3497                                }
3498                        }
3499                        unset($rep_event_ids);
3500
3501                        return $events;
3502                }
3503
3504                function _debug_array($data)
3505                {
3506                        echo '<br>UI:';
3507                        _debug_array($data);
3508                }
3509
3510                /*!
3511                @function rejected_no_show
3512                @abstract checks if event is rejected from user and he's not the owner and dont want rejected
3513                @param $event to check
3514                @returns True if event should not be shown
3515                */
3516                function rejected_no_show($event)
3517                {
3518                        $ret = !$this->prefs['infolog']['show_rejected'] &&
3519                                $event['owner'] != $this->owner &&
3520                                $event['participants'][$this->owner] == 'R';
3521                        //echo "<p>rejected_no_show($event[title])='$ret': user=$this->owner, event-owner=$event[owner], status='".$event['participants'][$this->owner]."', show_rejected='".$this->prefs['infolog']['show_rejected']."'</p>\n";
3522                        return $ret;
3523                }
3524
3525                /* This is called only by list_cals().  It was moved here to remove fatal error in php5 beta4 */
3526                function list_cals_add($id,&$users,&$groups)
3527                {
3528                        $name = $GLOBALS['phpgw']->common->grab_owner_name($id);
3529                        if (($type = $GLOBALS['phpgw']->accounts->get_type($id)) == 'g')
3530                        {
3531                                $arr = &$groups;
3532                        }
3533                        else
3534                        {
3535                                $arr = &$users;
3536                        }
3537                        $arr[$name] = Array(
3538                                'grantor' => $id,
3539                                'value'   => ($type == 'g' ? 'g_' : '') . $id,
3540                                'name'    => $name
3541                        );
3542                }
3543
3544                /*!
3545                @function list_cals
3546                @abstract generate list of user- / group-infologs for the selectbox in the header
3547                @returns alphabeticaly sorted array with groups first and then users
3548                */
3549                function list_cals()
3550                {
3551                        $users = $groups = array();
3552                        foreach($this->grants as $id => $rights)
3553                        {
3554                                $this->list_cals_add($id,$users,$groups);
3555                        }
3556                       
3557                        //by JakJr, melhora de performance na abertura da agenda
3558                        /*if ($memberships = $GLOBALS['phpgw']->accounts->membership($GLOBALS['phpgw_info']['user']['account_id']))
3559                        {
3560                                foreach($memberships as $group_info)
3561                                {
3562                                        $this->list_cals_add($group_info['account_id'],$users,$groups);
3563
3564                                        if ($account_perms = $GLOBALS['phpgw']->acl->get_ids_for_location($group_info['account_id'],PHPGW_ACL_READ,'infolog'))
3565                                        {
3566                                                foreach($account_perms as $id)
3567                                                {
3568                                                        $this->list_cals_add($id,$users,$groups);
3569                                                }
3570                                        }
3571                                }
3572                        }*/
3573                        uksort($users,'strnatcasecmp');
3574                        uksort($groups,'strnatcasecmp');
3575
3576                        return $users + $groups;        // users first and then groups, both alphabeticaly
3577                }
3578
3579          function translate($key,$vars=false, $not_found='*' )
3580          {
3581            if ($this->async)
3582              return $GLOBALS['phpgw']->translation->translate_async($key, $vars);
3583            return lang($key, $vars);
3584          }
3585
3586                /*!
3587                @function event2array
3588                @abstract create array with name, translated name and readable content of each attributes of an event
3589                @syntax event2array($event,$sep='<br>')
3590                @param $event event to use
3591                @returns array of attributes with fieldname as key and array with the 'field'=translated name \
3592                        'data' = readable content (for participants this is an array !)
3593                */
3594                function event2array($event)
3595                {
3596                       
3597                       
3598                  $var['title'] = Array(
3599                                'field'         => $this->translate('Title'),
3600                                'data'          => $event['title']
3601                        );
3602
3603                        // Some browser add a \n when its entered in the database. Not a big deal
3604                        // this will be printed even though its not needed.
3605                        $var['description'] = Array(
3606                                'field' => $this->translate('Description'),
3607                                'data'  => $event['description']
3608                        );
3609$var['description1'] = Array(
3610                                'field' => $this->translate('Description1'),
3611                                'data'  => $event['description1']
3612                        );
3613
3614
3615$var['participants1'] = Array(
3616                                'field' => $this->translate('participants1'),
3617                                'data'  => $event['participants1']
3618                        );
3619
3620                        $var['ex_participants'] = Array(
3621                                'field' => $this->translate('External Participants'),
3622                                'data'  => $event['ex_participants']
3623                        );
3624                       
3625                        $cats = Array();
3626                        $this->cat->categories($this->bo->owner,'infolog');
3627                        if(strpos($event['category'],','))
3628                        {
3629                                $cats = explode(',',$event['category']);
3630                        }
3631                        else
3632                        {
3633                                $cats[] = $event['category'];
3634                        }
3635                        foreach($cats as $cat_id)
3636                        {
3637                                list($cat) = $this->cat->return_single($cat_id);
3638                                $cat_string[] = $cat['name'];
3639                        }
3640                        $var['category'] = Array(
3641                                'field' => $this->translate('Category'),
3642                                'data'  => implode(', ',$cat_string)
3643                        );
3644
3645                        $var['location'] = Array(
3646                                'field' => $this->translate('Location'),
3647                                'data'  => $event['location']
3648                        );
3649
3650                        $var['startdate'] = Array(
3651                                'field' => $this->translate('Start Date/Time'),
3652                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset),
3653                        );
3654
3655                        $var['enddate'] = Array(
3656                                'field' => $this->translate('End Date/Time'),
3657                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset)
3658                        );
3659
3660                        $pri = Array(
3661                                1       => lang('Low'),
3662                                2       => lang('Normal'),
3663                                3       => lang('High')
3664                        );
3665                        $var['priority'] = Array(
3666                                'field' => lang('Priority'),
3667                                'data'  => $pri[$event['priority']]
3668                        );
3669
3670                        $var['owner'] = Array(
3671                                'field' => lang('Created By'),
3672                                'data'  => $GLOBALS['phpgw']->common->grab_owner_name($event['owner'])
3673                        );
3674
3675                        $var['updated'] = Array(
3676                                'field' => lang('Updated'),
3677                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['modtime']) - $GLOBALS['phpgw']->datetime->tz_offset)
3678                        );
3679
3680                        $var['access'] = Array(
3681                                'field' => lang('Access'),
3682                                'data'  => $event['public'] ? lang('Public') : lang('Private')
3683                        );
3684
3685                        if(@isset($event['groups'][0]))
3686                        {
3687                                $cal_grps = '';
3688                                for($i=0;$i<count($event['groups']);$i++)
3689                                {
3690                                        if($GLOBALS['phpgw']->accounts->exists($event['groups'][$i]))
3691                                        {
3692                                                $cal_grps .= ($i>0?'<br>':'').$GLOBALS['phpgw']->accounts->id2name($event['groups'][$i]);
3693                                        }
3694                                }
3695
3696                                $var['groups'] = Array(
3697                                        'field' => lang('Groups'),
3698                                        'data'  => $cal_grps
3699                                );
3700                        }
3701
3702                        $participants = array();
3703                        foreach($event['participants'] as $user => $short_status)
3704                        {
3705                                if($GLOBALS['phpgw']->accounts->exists($user))
3706                                {
3707                                        $participants[$user] = $GLOBALS['phpgw']->common->grab_owner_name($user).' ('.$this->get_long_status($short_status).')';
3708                                }
3709                        }
3710                        $var['participants'] = Array(
3711                                'field' => $this->translate('Participants'),
3712                                'data'  => $participants
3713                        );
3714
3715                        // Repeated Events
3716                        if($event['recur_type'] != MCAL_RECUR_NONE)
3717                        {
3718                                $str = lang($this->rpt_type[$event['recur_type']]);
3719
3720                                $str_extra = array();
3721                                if ($event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['month'] != 0 && $event['recur_enddate']['year'] != 0)
3722                                {
3723                                        $recur_end = $this->maketime($event['recur_enddate']);
3724                                        if($recur_end != 0)
3725                                        {
3726                                                $recur_end -= $GLOBALS['phpgw']->datetime->tz_offset;
3727                                                $str_extra[] = lang('ends').': '.lang($GLOBALS['phpgw']->common->show_date($recur_end,'l')).', '.$this->long_date($recur_end).' ';
3728                                        }
3729                                }
3730                                // only weekly uses the recur-data (days) !!!
3731                                if($event['recur_type'] == MCAL_RECUR_WEEKLY)
3732                                {
3733                                        $repeat_days = array();
3734                                        foreach ($this->rpt_day as $mcal_mask => $dayname)
3735                                        {
3736                                                if ($event['recur_data'] & $mcal_mask)
3737                                                {
3738                                                        $repeat_days[] = lang($dayname);
3739                                                }
3740                                        }
3741                                        if(count($repeat_days))
3742                                        {
3743                                                $str_extra[] = lang('days repeated').': '.implode(', ',$repeat_days);
3744                                        }
3745                                }
3746                                if($event['recur_interval'] != 0)
3747                                {
3748                                        $str_extra[] = lang('Interval').': '.$event['recur_interval'];
3749                                }
3750
3751                                if(count($str_extra))
3752                                {
3753                                        $str .= ' ('.implode(', ',$str_extra).')';
3754                                }
3755
3756                                $var['recure_type'] = Array(
3757                                        'field' => lang('Repetition'),
3758                                        'data'  => $str,
3759                                );
3760                        }
3761
3762                        if (!isset($this->fields))
3763                        {
3764                                $this->custom_fields = CreateObject('infolog.bocustom_fields');
3765                                $this->fields = &$this->custom_fields->fields;
3766                                $this->stock_fields = &$this->custom_fields->stock_fields;
3767                        }
3768                        foreach($this->fields as $field => $data)
3769                        {
3770                                if (!$data['disabled'])
3771                                {
3772                                        if (isset($var[$field]))
3773                                        {
3774                                                $sorted[$field] = $var[$field];
3775                                        }
3776                                        elseif (!isset($this->stock_fields[$field]) && strlen($event[$field]))  // Custom field
3777                                        {
3778                                                $lang = lang($name = substr($field,1));
3779                                                $sorted[$field] = array(
3780                                                        'field' => $lang == $name.'*' ? $name : $lang,
3781                                                        'data'  => $event[$field]
3782                                                );
3783                                        }
3784                                }
3785                                unset($var[$field]);
3786                        }
3787                        foreach($var as $name => $v)
3788                        {
3789                                $sorted[$name] = $v;
3790
3791                        }
3792                        return $sorted;
3793                }
3794
3795                /*!
3796                @function check_set_default_prefs
3797                @abstract sets the default prefs, if they are not already set (on a per pref. basis)
3798                @note It sets a flag in the app-session-data to be called only once per session
3799                */
3800                function check_set_default_prefs()
3801                {
3802                        if (($set = $GLOBALS['phpgw']->session->appsession('default_prefs_set','infolog')))
3803                        {
3804                                return;
3805                        }
3806                        $GLOBALS['phpgw']->session->appsession('default_prefs_set','infolog','set');
3807
3808                        //$default_prefs = $GLOBALS['phpgw']->preferences->default['infolog']; jakjr
3809
3810                        $subject = $this->translate('infolog Event') . ' - $$action$$: $$startdate$$ $$title$$'."\n";
3811                        $defaults = array(
3812                                'defaultinfolog' => 'week',
3813                                'mainscreen_showevents' => '0',
3814                                'summary'         => 'no',
3815                                'receive_updates' => 'no',
3816                                'update_format'   => 'extended',        // leave it to extended for now, as iCal kills the message-body
3817                                'notifyAdded'     => $subject . $this->translate ('You have a meeting scheduled for %1',array('$$startdate$$')),
3818                                'notifyCanceled'  => $subject . $this->translate ('Your meeting scheduled for %1 has been canceled',array('$$startdate$$')),
3819                                'notifyModified'  => $subject . $this->translate ('Your meeting that had been scheduled for %1 has been rescheduled to %2',array('$$olddate$$','$$startdate$$')),
3820                                'notifyResponse'  => $subject . $this->translate ('On %1 %2 %3 your meeting request for %4', array('$$date$$','$$fullname$$','$$action$$','$$startdate$$')),
3821                                'notifyAlarm'     => $this->translate('Alarm for %1 at %2 in %3',array('$$title$$','$$startdate$$','$$location$$')) . "\n" . $this->translate('Here is your requested alarm.'),
3822                                'show_rejected'   => '0',
3823                                'hide_event_conflict'   => '0',
3824                                'display_status'  => '1',
3825                                'weekdaystarts'   => 'Monday',
3826                                'workdaystarts'   => '9',
3827                                'workdayends'     => '17',
3828                                'interval'        => '30',
3829                                'defaultlength'   => '60',
3830                                'planner_start_with_group' => $GLOBALS['phpgw']->accounts->name2id('Default'),
3831                                'planner_intervals_per_day'=> '4',
3832                                'defaultfilter'   => 'all',
3833                                'default_private' => '0',
3834                                'display_minicals'=> '1',
3835                                'print_black_white'=>'0'
3836                        );
3837                        foreach($defaults as $var => $default)
3838                        {
3839                                if (!isset($default_prefs[$var]) || $default_prefs[$var] == '')
3840                                {
3841                                        $GLOBALS['phpgw']->preferences->add('infolog',$var,$default,'default');
3842                                        $need_save = True;
3843                                }
3844                        }
3845                        if ($need_save)
3846                        {
3847                                $prefs = $GLOBALS['phpgw']->preferences->save_repository(False,'default');
3848                                $this->prefs['infolog'] = $prefs['infolog'];
3849                        }
3850                        if ($this->prefs['infolog']['send_updates'] && !isset($this->prefs['infolog']['receive_updates']))
3851                        {
3852                                $this->prefs['infolog']['receive_updates'] = $this->prefs['infolog']['send_updates'];
3853                                $GLOBALS['phpgw']->preferences->add('infolog','receive_updates',$this->prefs['infolog']['send_updates']);
3854                                $GLOBALS['phpgw']->preferences->delete('infolog','send_updates');
3855                                $prefs = $GLOBALS['phpgw']->preferences->save_repository();
3856                        }
3857                }
3858
3859                // return array with all infolog categories (for xmlrpc)
3860                function categories($complete = False)
3861                {
3862                        return $GLOBALS['server']->categories($complete);
3863                }
3864/******************************************/
3865
3866function insert($params='')
3867                {
3868
3869                        if($params['from_mobile']) {
3870                                $ui_return = "mobile.ui_mobileinfolog.edit";
3871                                $ui_index = "mobile.ui_mobileinfolog.index";
3872                                $ui_overlap = "mobile.ui_mobileinfolog.overlap";
3873                        }
3874                        else {
3875                                $ui_return = "infolog.uiinfolog.edit";
3876                                $ui_index = "infolog.uiinfolog.index";         
3877                                $ui_overlap = "infolog.uiinfolog.overlap";
3878                        }
3879
3880                        if(!is_object($GLOBALS['phpgw']->datetime))
3881                        {
3882                                $GLOBALS['phpgw']->datetime = createobject('phpgwapi.date_time');
3883                        }
3884                        //$l_cal = (@isset($params['info_type']) && $params['info_type']?$params['info_type']:$_POST['info_type']);
3885                        $l_participants = (@$params['participants']?$params['participants']:$_POST['participants']);
3886                        $this->ex_participants = (@$params['ex_participants']?$params['ex_participants']:$_POST['ex_participants']);
3887                        $l_categories = (@$params['categories']?$params['categories']:$_POST['categories']);
3888                        $l_start = (@isset($params['start']) && $params['start']?$params['start']:$_POST['start']);
3889                        $l_end = (@isset($params['end']) && $params['end']?$params['end']:$_POST['end']);
3890                        $l_recur_enddate = (@isset($params['recur_enddate']) && $params['recur_enddate']?$params['recur_enddate']:$_POST['recur_enddate']);
3891
3892                       
3893                        $send_to_ui = True;
3894                        //if ((!is_array($l_start) || !is_array($l_end)) && !isset($_GET['readsess']))  // xmlrpc call
3895                        if ($this->xmlrpc)      // xmlrpc call
3896                        {
3897
3898                                $send_to_ui = False;
3899
3900                                $l_cal = $params;       // no extra array
3901
3902                                foreach(array('start','end','recur_enddate') as $name)
3903                                {
3904                                        $var = 'l_'.$name;
3905                                        $$var = $GLOBALS['server']->iso86012date($params[$name]);
3906                                        unset($l_cal[$name]);
3907                                }
3908
3909                                if (!is_array($l_participants) || !count($l_participants))
3910                                {
3911                                        $l_participants = array($GLOBALS['phpgw_info']['user']['account_id'].'A');
3912                                }
3913                                else
3914                                {
3915                                        $l_participants = array();
3916                                        foreach($params['participants'] as $user => $data)
3917                                        {
3918                                                $l_participants[] = $user.$data['status'];
3919                                        }
3920                                }
3921
3922                                unset($l_cal['participants']);
3923
3924                                if (!is_object($GLOBALS['phpgw']->categories))
3925                                {
3926                                        $GLOBALS['phpgw']->categories = CreateObject('phpgwapi.categories');
3927                                }
3928
3929                                $l_categories = $GLOBALS['server']->xmlrpc2cats($params['category']);
3930                                unset($l_cal['category']);
3931
3932                                // using access={public|private} in all modules via xmlrpc
3933                                $l_cal['public'] = $params['access'] != 'private';
3934                                unset($l_cal['access']);
3935/*
3936                                $fp = fopen('/tmp/xmlrpc.log','a+');
3937                                ob_start();
3938                                echo "\nboinfolog::update("; print_r($params); echo ")\n";
3939                                //echo "\nl_start="; print_r($l_start);
3940                                //echo "\nl_end="; print_r($l_end);
3941                                fwrite($fp,ob_get_contents());
3942                                ob_end_clean();
3943                                fclose($fp);
3944*/
3945                        }
3946
3947                        print_debug('ID',$l_cal['id']);
3948
3949                        // don't wrap to the next day for no time
3950                        if ($l_end['hour'] == 24 && $l_end['min'] == 0)
3951                        {
3952                                $l_end['hour'] = 23;
3953                                $l_end['min'] = 59;
3954                        }
3955
3956                        if(isset($_GET['readsess']))
3957                        {
3958
3959                                $event = $this->restore_from_appsession();
3960                                $event['title'] = stripslashes($event['title']);
3961                                $event['description'] = stripslashes($event['description']);
3962$event['description1'] = stripslashes($event['description1']);
3963$event['participants1'] = stripslashes($event['participants1']);
3964                                $event['ex_participants'] = stripslashes($event['ex_participants']);
3965                                $datetime_check = $this->validate_update($event);
3966                                if($datetime_check)
3967                                {
3968                                        ExecMethod($ui_return,
3969                                                Array(
3970                                                        'cd'            => $datetime_check,
3971                                                        'readsess'      => 1
3972                                                )
3973                                        );
3974                                        if(!$params['from_mobile'])
3975                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
3976                                        else
3977                                                return;
3978                                }
3979                                $overlapping_events = False;
3980                        }
3981                        else
3982                        {
3983
3984                                if((!$l_cal['id'] && !$this->check_perms(PHPGW_ACL_ADD)) ||
3985                                   ($l_cal['id'] && !$this->check_perms(PHPGW_ACL_EDIT,$l_cal['id'])))
3986                                {
3987
3988                                        if ($this->xmlrpc)
3989                                        {
3990                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
3991                                        }
3992                                        if (!$send_to_ui)
3993                                        {
3994                                                return array(($l_cal['id']?1:2) => 'permission denied');
3995                                        }
3996
3997                                        ExecMethod($ui_index);
3998
3999
4000                                        if(!$params['from_mobile'])
4001                                                $GLOBALS['phpgw']->common->phpgw_exit();
4002                                        else
4003                                                return;
4004                                }
4005
4006                                print_debug('Prior to fix_update_time()');
4007
4008                                $this->fix_update_time($l_start);
4009
4010                                $this->fix_update_time($l_end);
4011
4012                                if(!isset($l_cal['ex_participants']))
4013                                {
4014                                        $l_cal['ex_participants'] = $this->ex_participants;
4015                                }
4016
4017                                if(!isset($l_categories))
4018                                {
4019                                        $l_categories = 0;
4020                                }
4021
4022                                $is_public = ($l_cal['type'] != 'private' && $l_cal['type'] != 'privateHiddenFields');
4023
4024                                $this->so->event_init();
4025
4026                        $this->add_attribute('uid',$l_cal['uid']);
4027
4028                                $this->add_attribute('type',$l_cal['type']);
4029
4030                                if($l_cal['ex_participants']) {
4031                                        $this->add_attribute('ex_participants',$l_cal['ex_participants']);
4032                                }
4033                                if(count($l_categories) >= 2)
4034                                {
4035                                        $this->so->set_category(implode(',',$l_categories));
4036                                }
4037                                else
4038                                {
4039                                        $this->so->set_category(strval($l_categories[0]));
4040                                }
4041                                $this->so->set_title($l_cal['title']);
4042                                $this->so->set_description($l_cal['description']);
4043$this->so->set_description1($l_cal['description1']);
4044$this->so->set_participants1($l_cal['participants1']);
4045                                $this->so->set_ex_participants($l_cal['ex_participants']);
4046                                $this->so->set_start($l_start['year'],$l_start['month'],$l_start['mday'],$l_start['hour'],$l_start['min'],0);
4047                                $this->so->set_end($l_end['year'],$l_end['month'],$l_end['mday'],$l_end['hour'],$l_end['min'],0);
4048                                $this->so->set_class($is_public);
4049                                $this->so->add_attribute('reference',(@isset($l_cal['reference']) && $l_cal['reference']?$l_cal['reference']:0));
4050                                $this->so->add_attribute('location',(@isset($l_cal['location']) && $l_cal['location']?$l_cal['location']:''));
4051                                if($l_cal['id'])
4052                                {
4053                                        $this->so->add_attribute('id',$l_cal['id']);
4054                                }
4055
4056                                if($l_cal['rpt_use_end'] != 'y')
4057                                {
4058                                        $l_recur_enddate['year'] = 0;
4059                                        $l_recur_enddate['month'] = 0;
4060                                        $l_recur_enddate['mday'] = 0;
4061                                }
4062                                elseif (isset($l_recur_enddate['str']))
4063                                {
4064                                        $l_recur_enddate = $this->jscal->input2date($l_recur_enddate['str'],False,'mday');
4065                                }
4066
4067                                switch((int)$l_cal['recur_type'])
4068                                {
4069
4070
4071                                        case MCAL_RECUR_NONE:
4072                                                $this->so->set_recur_none();
4073
4074                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4075
4076                                                break;
4077                                        case MCAL_RECUR_DAILY:
4078                                                $this->so->set_recur_daily((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
4079
4080                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4081
4082                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
4083                                                $init_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_init[1]),$tmp_init[0],$tmp_init[2]); // transforma a data inicial + hora + minuto em UNIX timestamp;
4084
4085                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
4086                                                {
4087
4088                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
4089                                                        $end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
4090
4091                                                }else { // se nao existe data final da repeticao (agendamento infinito):
4092
4093                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
4094                                                }
4095                                                break;
4096                                        case MCAL_RECUR_WEEKLY:
4097
4098                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4099
4100                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
4101                                                $init_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_init[1]),$tmp_init[0],$tmp_init[2]); // transforma a data inicial + hora + minuto em UNIX timestamp;
4102
4103                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
4104                                                {
4105
4106                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
4107                                                        $end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
4108
4109                                                }else { // se nao existe data final da repeticao (agendamento infinito):
4110
4111                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
4112                                                }
4113
4114                                                foreach(array('rpt_sun','rpt_mon','rpt_tue','rpt_wed','rpt_thu','rpt_fri','rpt_sat') as $rpt_day)
4115                                                {
4116                                                        $l_cal['recur_data'] += (int)$l_cal[$rpt_day];
4117                                                }
4118                                                if (is_array($l_cal['rpt_day']))
4119                                                {
4120                                                        foreach ($l_cal['rpt_day'] as $mask)
4121                                                        {
4122                                                                $l_cal['recur_data'] |= (int)$mask;
4123                                                                $rpt_wdays = $l_cal['recur_data']; // recebe os dias da semana (somatorio) para repetir o alarme;
4124                                                        }
4125                                                }
4126                                                $this->so->set_recur_weekly((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval'],$l_cal['recur_data']);
4127                                                break;
4128                                        case MCAL_RECUR_MONTHLY_MDAY:
4129                                                $this->so->set_recur_monthly_mday((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
4130
4131                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4132
4133                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
4134                                                $init_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_init[1]),$tmp_init[0],$tmp_init[2]); // transforma a data inicial + hora + minuto em UNIX timestamp;
4135
4136                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
4137                                                {
4138
4139                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
4140                                                        $end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
4141
4142                                                }else { // se nao existe data final da repeticao (agendamento infinito):
4143
4144                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
4145                                                }
4146                                                break;
4147                                        case MCAL_RECUR_MONTHLY_WDAY:
4148                                                $this->so->set_recur_monthly_wday((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
4149                                                break;
4150                                        case MCAL_RECUR_YEARLY:
4151                                                $this->so->set_recur_yearly((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
4152
4153                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4154
4155                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
4156                                                $init_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_init[1]),$tmp_init[0],$tmp_init[2]); // transforma a data inicial + hora + minuto em UNIX timestamp;
4157
4158                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
4159                                                {
4160
4161                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
4162                                                        $end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
4163
4164                                                }else { // se nao existe data final da repeticao (agendamento infinito):
4165
4166                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
4167                                                }
4168                                                break;
4169                                }
4170
4171                                if($l_participants)
4172                                {
4173                                        $parts = $l_participants;
4174                                        $minparts = min($l_participants);
4175                                        $part = Array();
4176                                        for($i=0;$i<count($parts);$i++)
4177                                        {
4178                                                if (($accept_type = substr($parts[$i],-1,1)) == '0' || (int)$accept_type > 0)
4179                                                {
4180                                                        $accept_type = 'U';
4181                                                }
4182                                                $acct_type = $GLOBALS['phpgw']->accounts->get_type((int)$parts[$i]);
4183                                                if($acct_type == 'u')
4184                                                {
4185                                                        $part[(int)$parts[$i]] = $accept_type;
4186                                                }
4187                                                elseif($acct_type == 'g')
4188                                                {
4189                                                        $part[(int)$parts[$i]] = $accept_type;
4190                                                        $groups[] = $parts[$i];
4191                                                        /* This pulls ALL users of a group and makes them as participants to the event */
4192                                                        /* I would like to turn this back into a group thing. */
4193                                                        $acct = CreateObject('phpgwapi.accounts',(int)$parts[$i]);
4194                                                        $members = $acct->member((int)$parts[$i]);
4195                                                        unset($acct);
4196                                                        if($members == False)
4197                                                        {
4198                                                                continue;
4199                                                        }
4200                                                        while($member = each($members))
4201                                                        {
4202                                                                $part[$member[1]['account_id']] = $accept_type;
4203                                                        }
4204                                                }
4205                                        }
4206                                }
4207                                else
4208                                {
4209                                        $part = False;
4210                                }
4211
4212                                if($part)
4213                                {
4214                                        @reset($part);
4215                                        while(list($key,$accept_type) = each($part))
4216                                        {
4217                                                $this->so->add_attribute('participants',$accept_type,(int)$key);
4218                                        }
4219                                }
4220
4221                                if($groups)
4222                                {
4223                                        @reset($groups);
4224                                        $this->so->add_attribute('groups',(int)$group_id);
4225                                }
4226
4227                                $event = $this->get_cached_event();
4228                                if(!is_int($minparts))
4229                                {
4230                                        $minparts = $this->owner;
4231                                }
4232                                if(!@isset($event['participants'][$l_cal['owner']]))
4233                                {
4234                                        $this->so->add_attribute('owner',$minparts);
4235                                }
4236                                else
4237                                {
4238                                        $this->so->add_attribute('owner',$l_cal['owner']);
4239                                }
4240                                $this->so->add_attribute('priority',$l_cal['priority']);
4241
4242                                foreach($l_cal as $name => $value)
4243                                {
4244                                        if ($name[0] == '#')    // Custom field
4245                                        {
4246                                                $this->so->add_attribute($name,stripslashes($value));
4247                                        }
4248                                }
4249                                if (isset($_POST['preserved']) && is_array($preserved = unserialize(stripslashes($_POST['preserved']))))
4250                                {
4251                                        foreach($preserved as $name => $value)
4252                                        {
4253                                                switch($name)
4254                                                {
4255                                                        case 'owner':
4256                                                                $this->so->add_attribute('participants',$value,$l_cal['owner']);
4257                                                                break;
4258                                                        default:
4259                                                                $this->so->add_attribute($name,str_replace(array('&amp;','&quot;','&lt;','&gt;'),array('&','"','<','>'),$value));
4260                                                }
4261                                        }
4262                                }
4263                                $event = $this->get_cached_event();
4264
4265                                if ($l_cal['alarmdays'] > 0 || $l_cal['alarmhours'] > 0 ||
4266                                                $l_cal['alarmminutes'] > 0)
4267                                {
4268                                        $offset = ($l_cal['alarmdays'] * 24 * 3600) +
4269                                                ($l_cal['alarmhours'] * 3600) + ($l_cal['alarmminutes'] * 60);
4270
4271                                        $time = $this->maketime($event['start']) - $offset;
4272
4273                                        $event['alarm'][] = Array(
4274                                                'time'    => $time,
4275                                                'offset'  => $offset,
4276                                                'owner'   => $this->owner,
4277                                                'enabled' => 1,
4278                                                'repeat'  => $repetido, // para repetir alarme;
4279                                                'init_rept' => $init_rept, // inicio repeticao;
4280                                                'end_rept' => $end_rept, // fim repeticao;
4281                                                'rpt_wdays' => $rpt_wdays // dias repeticao da semana;
4282                                        );
4283                                }
4284
4285                                $this->store_to_appsession($event);
4286                                $datetime_check = $this->validate_update($event);
4287                                print_debug('bo->validated_update() returnval',$datetime_check);
4288
4289                                /*if($datetime_check)
4290                                {
4291
4292
4293                                        if (!$send_to_ui)
4294                                        {
4295                                                return array($datetime_check => 'invalid input data');
4296                                        }
4297
4298
4299                                        ExecMethod($ui_return,
4300                                                Array(
4301                                                        'cd'            => $datetime_check,
4302                                                        'readsess'      => 1
4303                                                )
4304                                        );
4305
4306                                        if(!$params['from_mobile'])
4307                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
4308                                        else
4309                                                return;
4310
4311                                }/*/
4312                                if($event['id'])
4313                                {
4314                                        $event_ids[] = $event['id'];
4315                                }
4316                                if($event['reference'])
4317                                {
4318                                        $event_ids[] = $event['reference'];
4319                                }
4320
4321                                $overlapping_events = $this->overlap(
4322                                        $this->maketime($event['start']),
4323                                        $this->maketime($event['end']),
4324                                        $event['participants'],
4325                                        $event['owner'],
4326                                        $event_ids
4327                                );
4328                        }
4329                        if(!$this->ex_participants)
4330                                $this->ex_participants = $event['ex_participants'];                     
4331                        if($overlapping_events)
4332                        {
4333
4334
4335                                if($send_to_ui)
4336                                {
4337                                        $event['ex_participants'] = $this->ex_participants;
4338                                        unset($GLOBALS['phpgw_info']['flags']['noheader']);
4339                                        unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
4340                                        ExecMethod($ui_overlap,
4341                                                Array(
4342                                                        'o_events'      => $overlapping_events,
4343                                                        'this_event'    => $event
4344                                                )
4345                                        );
4346                                        if(!$params['from_mobile'])
4347                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
4348                                        else
4349                                                return;
4350                                }
4351                                else
4352                                {
4353                                        return $overlapping_events;
4354                                }
4355                        }
4356                        else
4357                        {
4358
4359
4360
4361                                if(!$event['id'])
4362                                {
4363
4364
4365
4366                                        $this->so->add_entry($event);
4367                                        $this->send_update(MSG_ADDED,$event['participants'],'',$this->get_cached_event());
4368                                        print_debug('New Event ID',$event['id']);
4369                                }
4370                                else
4371                                {
4372
4373                                        print_debug('Updating Event ID',$event['id']);
4374                                        $new_event = $event;
4375                                        $old_event = $this->read_entry($event['id']);
4376                                        // if old event has alarm and the start-time changed => update them
4377                                        //echo "<p>checking ".count($old_event['alarm'])." alarms of event #$event[id] start moved from ".print_r($old_event['start'],True)." to ".print_r($event['start'],True)."</p>\n";
4378                                        if ($old_event['alarm'] &&
4379                                                $this->maketime($old_event['start']) != $this->maketime($event['start']))
4380                                        {
4381                                                $this->so->delete_alarms($old_event['id']);
4382                                                foreach($old_event['alarm'] as $id => $alarm)
4383                                                {
4384                                                        $alarm['time'] = $this->maketime($event['start']) - $alarm['offset'];
4385                                                        $event['alarm'][] = $alarm;
4386                                                }
4387                                                //echo "updated alarms<pre>".print_r($event['alarm'],True)."</pre>\n";
4388                                        }
4389                                        $this->so->cal->event = $event;
4390                                        $this->so->add_entry($event);
4391                                        $this->prepare_recipients($new_event,$old_event);
4392                                }
4393
4394                                $date = sprintf("%04d%02d%02d",$event['start']['year'],$event['start']['month'],$event['start']['mday']);
4395                                if($send_to_ui)
4396                                {
4397                                        $this->read_sessiondata();
4398                                        if ($this->return_to)
4399                                        {
4400                                                $GLOBALS['phpgw']->redirect_link('/index.php','menuaction='.$this->return_to);
4401                                                $GLOBALS['phpgw']->common->phpgw_exit();
4402                                        }
4403                                        Execmethod($ui_index);
4404                                }
4405                                else
4406                                {
4407                                        return (int)$event['id'];
4408                                }
4409                        }
4410                        return True;
4411                }
4412
4413
4414/***********************************************/
4415        }
4416?>
Note: See TracBrowser for help on using the repository browser.