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

Revision 588, 116.5 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #386

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