source: trunk/calendar/inc/class.bocalendar.inc.php @ 582

Revision 582, 116.1 KB checked in by niltonneto, 15 years ago (diff)

Resolve #391

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