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

Revision 641, 116.8 KB checked in by niltonneto, 15 years ago (diff)

Resolve #417

  • 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                       
1583                        if (is_int($event) && $event == 0)
1584                        {
1585                                $owner = $other > 0 ? $other : $this->owner;
1586                        }
1587                        else
1588                        {
1589                                if (!is_array($event))
1590                                {
1591                                        $event = $this->so->read_entry((int) $event);
1592                                }
1593                                if (!is_array($event))
1594                                {
1595                                        if ($this->xmlrpc)
1596                                        {
1597                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['not_exist'],$GLOBALS['xmlrpcstr']['not_exist']);
1598                                        }
1599                                        return False;
1600                                }
1601                                $owner = $event['owner'];
1602                                $private = $event['public'] == False || $event['public'] == 0;
1603                        }
1604                        $user = $GLOBALS['phpgw_info']['user']['account_id'];
1605                        $grants = $this->grants[$owner];
1606
1607                        if (is_array($event) && $needed == PHPGW_ACL_READ)
1608                        {
1609                                // Check if the $user is one of the participants or has a read-grant from one of them
1610                                //
1611                                foreach($event['participants'] as $uid => $accept)
1612                                {
1613                                        if ($this->grants[$uid] & PHPGW_ACL_READ || $uid == $user)
1614                                        {
1615                                                $grants |= PHPGW_ACL_READ;
1616                                                // if the $user is one of the participants read-grant private (restricted) too.
1617                                                if($uid == $user || ($this->grants[$uid] & PHPGW_ACL_PRIVATE)) {
1618                                                        $grants |= PHPGW_ACL_PRIVATE;
1619                                                }
1620                                                //break;
1621                                        }
1622                                }
1623                        }
1624
1625                        if ($GLOBALS['phpgw']->accounts->get_type($owner) == 'g' && $needed == PHPGW_ACL_ADD)
1626                        {
1627                                $access = False;        // a group can't be the owner of an event
1628                        }
1629                        else
1630                        {
1631                                $access = $user == $owner || $grants & $needed && (!$private || $grants & PHPGW_ACL_PRIVATE);
1632                        }
1633                        //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";
1634
1635                        return $access;
1636                }
1637
1638
1639                function display_status($user_status)
1640                {
1641                        if(@$this->prefs['calendar']['display_status'] && $user_status)
1642                        {
1643                                $user_status = substr($this->get_long_status($user_status),0,1);
1644
1645                                return ' ('.$user_status.')';
1646                        }
1647                        else
1648                        {
1649                                return '';
1650                        }
1651                }
1652
1653                function get_long_status($status_short)
1654                {
1655                        switch ($status_short)
1656                        {
1657                                case 'A':
1658                                        $status = lang('Accepted');
1659                                        break;
1660                                case 'R':
1661                                        $status = lang('Rejected');
1662                                        break;
1663                                case 'T':
1664                                        $status = lang('Tentative');
1665                                        break;
1666                                case 'U':
1667                                        $status = lang('No Response');
1668                                        break;
1669                        }
1670                        return $status;
1671                }
1672
1673                function is_private($event,$owner)
1674                {
1675                        if($owner == 0)
1676                        {
1677                                $owner = $this->owner;
1678                        }
1679                        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'])
1680                        {
1681                                return False;
1682                        }
1683                        elseif($event['public'] == 0)
1684                        {
1685                                return True;
1686                        }
1687                        elseif($event['public'] == 2)
1688                        {
1689                                $is_private = True;
1690                                $groups = $GLOBALS['phpgw']->accounts->membership($owner);
1691                                while (list($key,$group) = each($groups))
1692                                {
1693                                        if (strpos(' '.implode(',',$event['groups']).' ',$group['account_id']))
1694                                        {
1695                                                return False;
1696                                        }
1697                                }
1698                        }
1699                        else
1700                        {
1701                                return False;
1702                        }
1703
1704                        return $is_private;
1705                }
1706
1707                function get_short_field($event,$is_private=True,$field='')
1708                {
1709                        if($is_private)
1710                        {
1711                                return lang('private');
1712                        }
1713
1714// cut off too long titles
1715                        elseif(strlen($event[$field]) > 19 && !$this->printer_friendly && $field=="title")
1716//                      elseif(strlen($event[$field]) > 19 && $this->printer_friendly)
1717                        {
1718// we dont use currently 160304
1719//                              return substr($event[$field], 0 , 19) . '&nbsp;...';
1720                                return $event[$field];
1721                        }
1722                        else
1723                        {
1724                                return $event[$field];
1725                        }
1726                }
1727
1728                function long_date($first,$last=0)
1729                {
1730                        if (!is_array($first))
1731                        {
1732                                $first = $this->time2array($raw = $first);
1733                                $first['raw'] = $raw;
1734                                $first['day'] = $first['mday'];
1735                        }
1736                        if ($last && !is_array($last))
1737                        {
1738                                $last = $this->time2array($raw = $last);
1739                                $last['raw'] = $raw;
1740                                $last['day'] = $last['mday'];
1741                        }
1742                        $datefmt = $this->prefs['common']['dateformat'];
1743
1744                        $month_before_day = strtolower($datefmt[0]) == 'm' ||
1745                                strtolower($datefmt[2]) == 'm' && $datefmt[4] == 'd';
1746
1747                        for ($i = 0; $i < 5; $i += 2)
1748                        {
1749                                switch($datefmt[$i])
1750                                {
1751                                        case 'd':
1752                                                $range .= $first['day'] . ($datefmt[1] == '.' ? '.' : '');
1753                                                if ($first['month'] != $last['month'] || $first['year'] != $last['year'])
1754                                                {
1755                                                        if (!$month_before_day)
1756                                                        {
1757                                                                $range .= ' '.lang(strftime('%B',$first['raw']));
1758                                                        }
1759                                                        if ($first['year'] != $last['year'] && $datefmt[0] != 'Y')
1760                                                        {
1761                                                                $range .= ($datefmt[0] != 'd' ? ', ' : ' ') . $first['year'];
1762                                                        }
1763                                                        if (!$last)
1764                                                        {
1765                                                                return $range;
1766                                                        }
1767                                                        $range .= ' - ';
1768
1769                                                        if ($first['year'] != $last['year'] && $datefmt[0] == 'Y')
1770                                                        {
1771                                                                $range .= $last['year'] . ', ';
1772                                                        }
1773
1774                                                        if ($month_before_day)
1775                                                        {
1776                                                                $range .= lang(strftime('%B',$last['raw']));
1777                                                        }
1778                                                }
1779                                                else
1780                                                {
1781                                                        $range .= ' - ';
1782                                                }
1783                                                $range .= ' ' . $last['day'] . ($datefmt[1] == '.' ? '.' : '');
1784                                                break;
1785                                        case 'm':
1786                                        case 'M':
1787                                                $range .= ' '.lang(strftime('%B',$month_before_day ? $first['raw'] : $last['raw'])) . ' ';
1788                                                break;
1789                                        case 'Y':
1790                                                $range .= ($datefmt[0] == 'm' ? ', ' : ' ') . ($datefmt[0] == 'Y' ? $first['year'].($datefmt[2] == 'd' ? ', ' : ' ') : $last['year'].' ');
1791                                                break;
1792                                }
1793                        }
1794                        return $range;
1795                }
1796
1797                function get_week_label()
1798                {
1799                        $first = $GLOBALS['phpgw']->datetime->gmtdate($GLOBALS['phpgw']->datetime->get_weekday_start($this->year, $this->month, $this->day));
1800                        $last = $GLOBALS['phpgw']->datetime->gmtdate($first['raw'] + 518400);
1801
1802                        return ($this->long_date($first,$last));
1803                }
1804
1805                function normalizeminutes(&$minutes)
1806                {
1807                        $hour = 0;
1808                        $min = (int)$minutes;
1809                        if($min >= 60)
1810                        {
1811                                $hour += $min / 60;
1812                                $min %= 60;
1813                        }
1814                        settype($minutes,'integer');
1815                        $minutes = $min;
1816                        return $hour;
1817                }
1818
1819                function splittime($time,$follow_24_rule=True)
1820                {
1821                        $temp = array('hour','minute','second','ampm');
1822                        $time = strrev($time);
1823                        $second = (int)(strrev(substr($time,0,2)));
1824                        $minute = (int)(strrev(substr($time,2,2)));
1825                        $hour   = (int)(strrev(substr($time,4)));
1826                        $hour += $this->normalizeminutes($minute);
1827                        $temp['second'] = $second;
1828                        $temp['minute'] = $minute;
1829                        $temp['hour']   = $hour;
1830                        $temp['ampm']   = '  ';
1831                        if($follow_24_rule == True)
1832                        {
1833                                if ($this->prefs['common']['timeformat'] == '24')
1834                                {
1835                                        return $temp;
1836                                }
1837
1838                                $temp['ampm'] = 'am';
1839
1840                                if ((int)$temp['hour'] > 12)
1841                                {
1842                                        $temp['hour'] = (int)((int)$temp['hour'] - 12);
1843                                        $temp['ampm'] = 'pm';
1844                                }
1845                                elseif ((int)$temp['hour'] == 12)
1846                                {
1847                                        $temp['ampm'] = 'pm';
1848                                }
1849                        }
1850                        return $temp;
1851                }
1852
1853                function get_exception_array($exception_str='')
1854                {
1855                        $exception = Array();
1856                        if(strpos(' '.$exception_str,','))
1857                        {
1858                                $exceptions = explode(',',$exception_str);
1859                                for($exception_count=0;$exception_count<count($exceptions);$exception_count++)
1860                                {
1861                                        $exception[] = (int)$exceptions[$exception_count];
1862                                }
1863                        }
1864                        elseif($exception_str != '')
1865                        {
1866                                $exception[] = (int)$exception_str;
1867                        }
1868                        return $exception;
1869                }
1870
1871                function build_time_for_display($fixed_time)
1872                {
1873                        $time = $this->splittime($fixed_time);
1874                        $str = $time['hour'].':'.((int)$time['minute']<=9?'0':'').$time['minute'];
1875
1876                        if ($this->prefs['common']['timeformat'] == '12')
1877                        {
1878                                $str .= ' ' . $time['ampm'];
1879                        }
1880
1881                        return $str;
1882                }
1883
1884                function sort_event($event,$date)
1885                {
1886                        $inserted = False;
1887                        if(isset($event['recur_exception']))
1888                        {
1889                                $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;
1890                                while($inserted == False && list($key,$exception_time) = each($event['recur_exception']))
1891                                {
1892                                        if($this->debug)
1893                                        {
1894                                                echo '<!-- checking exception datetime '.$exception_time.' to event datetime '.$event_time.' -->'."\n";
1895                                        }
1896                                        if($exception_time == $event_time)
1897                                        {
1898                                                $inserted = True;
1899                                        }
1900                                }
1901                        }
1902                        if($this->cached_events[$date] && $inserted == False)
1903                        {
1904
1905                                if($this->debug)
1906                                {
1907                                        echo '<!-- Cached Events found for '.$date.' -->'."\n";
1908                                }
1909                                $year = substr($date,0,4);
1910                                $month = substr($date,4,2);
1911                                $day = substr($date,6,2);
1912
1913                                if($this->debug)
1914                                {
1915                                        echo '<!-- Date : '.$date.' Count : '.count($this->cached_events[$date]).' -->'."\n";
1916                                }
1917
1918                                for($i=0;$i<count($this->cached_events[$date]);$i++)
1919                                {
1920                                        if($this->cached_events[$date][$i]['id'] == $event['id'] || $this->cached_events[$date][$i]['reference'] == $event['id'])
1921                                        {
1922                                                if($this->debug)
1923                                                {
1924                                                        echo '<!-- Item already inserted! -->'."\n";
1925                                                }
1926                                                $inserted = True;
1927                                                break;
1928                                        }
1929                                        /* This puts all spanning events across multiple days up at the top. */
1930                                        if($this->cached_events[$date][$i]['recur_type'] == MCAL_RECUR_NONE)
1931                                        {
1932                                                if($this->cached_events[$date][$i]['start']['mday'] != $day && $this->cached_events[$date][$i]['end']['mday'] >= $day)
1933                                                {
1934                                                        continue;
1935                                                }
1936                                        }
1937                                        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)))
1938                                        {
1939                                                for($j=count($this->cached_events[$date]);$j>=$i;$j--)
1940                                                {
1941                                                        $this->cached_events[$date][$j] = $this->cached_events[$date][$j-1];
1942                                                }
1943                                                if($this->debug)
1944                                                {
1945                                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
1946                                                }
1947                                                $inserted = True;
1948                                                $this->cached_events[$date][$i] = $event;
1949                                                break;
1950                                        }
1951                                }
1952                        }
1953                        if(!$inserted)
1954                        {
1955                                if($this->debug)
1956                                {
1957                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
1958                                }
1959                                $this->cached_events[$date][] = $event;
1960                        }
1961                }
1962
1963                function check_repeating_events($datetime)
1964                {
1965                        @reset($this->repeating_events);
1966                        $search_date_full = date('Ymd',$datetime);
1967                        $search_date_year = date('Y',$datetime);
1968                        $search_date_month = date('m',$datetime);
1969                        $search_date_day = date('d',$datetime);
1970                        $search_date_dow = date('w',$datetime);
1971                        $search_beg_day = mktime(0,0,0,$search_date_month,$search_date_day,$search_date_year);
1972                        if($this->debug)
1973                        {
1974                                echo '<!-- Search Date Full = '.$search_date_full.' -->'."\n";
1975                        }
1976                        $repeated = $this->repeating_events;
1977                        $r_events = count($repeated);
1978                        for ($i=0;$i<$r_events;$i++)
1979                        {
1980                                $rep_events = $this->repeating_events[$i];
1981                                $id = $rep_events['id'];
1982                                $event_beg_day = mktime(0,0,0,$rep_events['start']['month'],$rep_events['start']['mday'],$rep_events['start']['year']);
1983                                if($rep_events['recur_enddate']['month'] != 0 && $rep_events['recur_enddate']['mday'] != 0 && $rep_events['recur_enddate']['year'] != 0)
1984                                {
1985                                        $event_recur_time = $this->maketime($rep_events['recur_enddate']);
1986                                }
1987                                else
1988                                {
1989                                        $event_recur_time = mktime(0,0,0,1,1,2030);
1990                                }
1991                                $end_recur_date = date('Ymd',$event_recur_time);
1992                                $full_event_date = date('Ymd',$event_beg_day);
1993
1994                                if($this->debug)
1995                                {
1996                                        echo '<!-- check_repeating_events - Processing ID - '.$id.' -->'."\n";
1997                                        echo '<!-- check_repeating_events - Recurring End Date - '.$end_recur_date.' -->'."\n";
1998                                }
1999
2000                                // only repeat after the beginning, and if there is an rpt_end before the end date
2001                                if (($search_date_full > $end_recur_date) || ($search_date_full < $full_event_date))
2002                                {
2003                                        continue;
2004                                }
2005
2006                                if ($search_date_full == $full_event_date)
2007                                {
2008                                        $this->sort_event($rep_events,$search_date_full);
2009                                        continue;
2010                                }
2011                                else
2012                                {
2013                                        $freq = $rep_events['recur_interval'];
2014                                        $freq = $freq ? $freq : 1;
2015                                        $type = $rep_events['recur_type'];
2016                                        switch($type)
2017                                        {
2018                                                case MCAL_RECUR_DAILY:
2019                                                        if($this->debug)
2020                                                        {
2021                                                                echo '<!-- check_repeating_events - MCAL_RECUR_DAILY - '.$id.' -->'."\n";
2022                                                        }
2023                                                       
2024                                                        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)
2025                                                        {
2026                                                                $this->sort_event($rep_events,$search_date_full);
2027                                                        }
2028                                                        elseif (floor(($search_beg_day - $event_beg_day)/86400) % ($freq ? $freq : 1))
2029                                                        {
2030                                                                continue;
2031                                                        }
2032                                                        else
2033                                                        {
2034                                                                $this->sort_event($rep_events,$search_date_full);
2035                                                        }
2036                                                        break;
2037                                                case MCAL_RECUR_WEEKLY:
2038                                                        if (floor(($search_beg_day - $event_beg_day)/604800)  % ($freq ? $freq : 1))
2039                                                        {
2040                                                                continue;
2041                                                        }
2042                                                        $check = 0;
2043                                                        switch($search_date_dow)
2044                                                        {
2045                                                                case 0:
2046                                                                        $check = MCAL_M_SUNDAY;
2047                                                                        break;
2048                                                                case 1:
2049                                                                        $check = MCAL_M_MONDAY;
2050                                                                        break;
2051                                                                case 2:
2052                                                                        $check = MCAL_M_TUESDAY;
2053                                                                        break;
2054                                                                case 3:
2055                                                                        $check = MCAL_M_WEDNESDAY;
2056                                                                        break;
2057                                                                case 4:
2058                                                                        $check = MCAL_M_THURSDAY;
2059                                                                        break;
2060                                                                case 5:
2061                                                                        $check = MCAL_M_FRIDAY;
2062                                                                        break;
2063                                                                case 6:
2064                                                                        $check = MCAL_M_SATURDAY;
2065                                                                        break;
2066                                                        }
2067                                                        if ($rep_events['recur_data'] & $check)
2068                                                        {
2069                                                                $this->sort_event($rep_events,$search_date_full);
2070                                                        }
2071                                                        break;
2072                                                case MCAL_RECUR_MONTHLY_WDAY:
2073                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month']) % $freq)
2074                                                        {
2075                                                                continue;
2076                                                        }
2077
2078                                                        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)) &&
2079                                                                (ceil($rep_events['start']['mday']/7) == ceil($search_date_day/7)))
2080                                                        {
2081                                                                $this->sort_event($rep_events,$search_date_full);
2082                                                        }
2083                                                        break;
2084                                                case MCAL_RECUR_MONTHLY_MDAY:
2085                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month'])  % ($freq ? $freq : 1))
2086                                                        {
2087                                                                continue;
2088                                                        }
2089                                                        if ($search_date_day == $rep_events['start']['mday'])
2090                                                        {
2091                                                                $this->sort_event($rep_events,$search_date_full);
2092                                                        }
2093                                                        break;
2094                                                case MCAL_RECUR_YEARLY:
2095                                                        if (($search_date_year - $rep_events['start']['year']) % ($freq ? $freq : 1))
2096                                                        {
2097                                                                continue;
2098                                                        }
2099                                                        if (date('dm',$datetime) == date('dm',$event_beg_day))
2100                                                        {
2101                                                                $this->sort_event($rep_events,$search_date_full);
2102                                                        }
2103                                                        break;
2104                                        }
2105                                }
2106                        }       // end for loop
2107                }       // end function
2108
2109                function store_to_cache($params)
2110                {
2111                        if(!is_array($params))
2112                        {
2113                                return False;
2114                        }
2115                        if (isset($params['start']) && ($datearr = $GLOBALS['server']->iso86012date($params['start'])))
2116                        {
2117                                $syear = $datearr['year'];
2118                                $smonth = $datearr['month'];
2119                                $sday = $datearr['mday'];
2120                                $this->xmlrpc = True;
2121                        }
2122                        else
2123                        {
2124                                $syear = $params['syear'];
2125                                $smonth = $params['smonth'];
2126                                $sday = $params['sday'];
2127                        }
2128                        if (isset($params['end']) && ($datearr = $GLOBALS['server']->iso86012date($params['end'])))
2129                        {
2130                                $eyear = $datearr['year'];
2131                                $emonth = $datearr['month'];
2132                                $eday = $datearr['mday'];
2133                                $this->xmlrpc = True;
2134                        }
2135                        else
2136                        {
2137                                $eyear = (isset($params['eyear'])?$params['eyear']:0);
2138                                $emonth = (isset($params['emonth'])?$params['emonth']:0);
2139                                $eday = (isset($params['eday'])?$params['eday']:0);
2140                        }
2141                        if (!isset($params['owner']) && @$this->xmlrpc)
2142                        {
2143                                $owner_id = $GLOBALS['phpgw_info']['user']['user_id'];
2144                        }
2145                        else
2146                        {
2147                                $owner_id = (isset($params['owner'])?$params['owner']:0);
2148                                if($owner_id==0 && $this->is_group)
2149                                {
2150                                        unset($owner_id);
2151                                        $owner_id = $this->g_owner;
2152                                        if($this->debug)
2153                                        {
2154                                                echo '<!-- owner_id in ('.implode(',',$owner_id).') -->'."\n";
2155                                        }
2156                                }
2157                        }
2158                        if(!$eyear && !$emonth && !$eday)
2159                        {
2160                                $edate = mktime(23,59,59,$smonth + 1,$sday + 1,$syear);
2161                                $eyear = date('Y',$edate);
2162                                $emonth = date('m',$edate);
2163                                $eday = date('d',$edate);
2164                        }
2165                        else
2166                        {
2167                                if(!$eyear)
2168                                {
2169                                        $eyear = $syear;
2170                                }
2171                                if(!$emonth)
2172                                {
2173                                        $emonth = $smonth + 1;
2174                                        if($emonth > 12)
2175                                        {
2176                                                $emonth = 1;
2177                                                $eyear++;
2178                                        }
2179                                }
2180                                if(!$eday)
2181                                {
2182                                        $eday = $sday + 1;
2183                                }
2184                                $edate = mktime(23,59,59,$emonth,$eday,$eyear);
2185                        }
2186                        //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";
2187                        if($this->debug)
2188                        {
2189                                echo '<!-- Start Date : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2190                                echo '<!-- End   Date : '.sprintf("%04d%02d%02d",$eyear,$emonth,$eday).' -->'."\n";
2191                        }
2192
2193                        if($owner_id)
2194                        {
2195                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2196                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2197                        }
2198                        else
2199                        {
2200                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2201                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2202                        }
2203
2204                        $c_cached_ids = count($cached_event_ids);
2205                        $c_cached_ids_repeating = count($cached_event_ids_repeating);
2206
2207                        if($this->debug)
2208                        {
2209                                echo '<!-- events cached : '.$c_cached_ids.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2210                                echo '<!-- repeating events cached : '.$c_cached_ids_repeating.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2211                        }
2212
2213                        $this->cached_events = Array();
2214
2215                        if($c_cached_ids == 0 && $c_cached_ids_repeating == 0)
2216                        {
2217                                return;
2218                        }
2219
2220                        $cache_start = (int)(sprintf("%04d%02d%02d",$syear,$smonth,$sday));
2221                        $cached_event=$this->get_cached_event();
2222                        if($c_cached_ids)
2223                        {
2224                                for($i=0;$i<$c_cached_ids;$i++)
2225                                {
2226                                        $event = $this->so->read_entry($cached_event_ids[$i]);
2227                                        if ($event['recur_type'])
2228                                        {
2229                                                continue;       // fetch recuring events only in 2. loop
2230                                        }
2231                                        $startdate = (int)(date('Ymd',$this->maketime($event['start'])));
2232                                        $enddate = (int)(date('Ymd',$this->maketime($event['end'])));
2233                                        $this->cached_events[$startdate][] = $event;
2234                                        if($startdate != $enddate)
2235                                        {
2236                                                $start['year'] = (int)(substr($startdate,0,4));
2237                                                $start['month'] = (int)(substr($startdate,4,2));
2238                                                $start['mday'] = (int)(substr($startdate,6,2));
2239                                                for($j=$startdate,$k=0;$j<=$enddate;$k++,$j=(int)(date('Ymd',mktime(0,0,0,$start['month'],$start['mday'] + $k,$start['year']))))
2240                                                {
2241                                                        $c_evt_day = count($this->cached_events[$j]) - 1;
2242                                                        if($c_evt_day < 0)
2243                                                        {
2244                                                                $c_evt_day = 0;
2245                                                        }
2246                                                        if($this->debug)
2247                                                        {
2248                                                                echo '<!-- Date: '.$j.' Count : '.$c_evt_day.' -->'."\n";
2249                                                        }
2250                                                        if($this->cached_events[$j][$c_evt_day]['id'] != $event['id'])
2251                                                        {
2252                                                                if($this->debug)
2253                                                                {
2254                                                                        echo '<!-- Adding Event for Date: '.$j.' -->'."\n";
2255                                                                }
2256                                                                $this->cached_events[$j][] = $event;
2257                                                        }
2258                                                        if ($j >= $cache_start && (@$params['no_doubles'] || @$this->xmlrpc))
2259                                                        {
2260                                                                break;  // add event only once on it's startdate
2261                                                        }
2262                                                }
2263                                        }
2264                                }
2265                        }
2266
2267                        $this->repeating_events = Array();
2268                        if($c_cached_ids_repeating)
2269                        {
2270                                for($i=0;$i<$c_cached_ids_repeating;$i++)
2271                                {
2272                                        $this->repeating_events[$i] = $this->so->read_entry($cached_event_ids_repeating[$i]);
2273                                        if($this->debug)
2274                                        {
2275                                                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";
2276                                        }
2277                                }
2278                                for($date=mktime(0,0,0,$smonth,$sday,$syear);$date<=$edate;$date += 86400)
2279                                {
2280                                        if($this->debug)
2281                                        {
2282                                                $search_date = date('Ymd',$date);
2283                                                echo '<!-- Calling check_repeating_events('.$search_date.') -->'."\n";
2284                                        }
2285                                        $this->check_repeating_events($date);
2286                                        if($this->debug)
2287                                        {
2288                                                echo '<!-- Total events found matching '.$search_date.' = '.count($this->cached_events[$search_date]).' -->'."\n";
2289                                                for($i=0;$i<count($this->cached_events[$search_date]);$i++)
2290                                                {
2291                                                        echo '<!-- Date: '.$search_date.' ['.$i.'] = '.$this->cached_events[$search_date][$i]['id'].' -->'."\n";
2292                                                }
2293                                        }
2294                                }
2295                        }
2296                        $retval = Array();
2297                        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)))
2298                        {
2299                                if(is_array($this->cached_events[$j]))
2300                                {
2301                                        if ($this->xmlrpc)
2302                                        {
2303                                                foreach($this->cached_events[$j] as $event)
2304                                                {
2305                                                        $retval[] = $this->xmlrpc_prepare($event);
2306                                                }
2307                                        }
2308                                        else
2309                                        {
2310                                                $retval[$j] = $this->cached_events[$j];
2311                                        }
2312                                }
2313                        }
2314                        //echo "store_to_cache(".print_r($params,True).")=<pre>".print_r($retval,True)."</pre>\n";
2315                        $this->so->cal->event = $cached_event;
2316                        return $retval;
2317                }
2318
2319                function xmlrpc_prepare(&$event)
2320                {
2321                        $event['rights'] = $this->grants[$event['owner']];
2322
2323                        foreach(array('start','end','modtime','recur_enddate') as $name)
2324                        {
2325                                if (isset($event[$name]))
2326                                {
2327                                        $event[$name] = $GLOBALS['server']->date2iso8601($event[$name]);
2328                                }
2329                        }
2330                        if (is_array($event['recur_exception']))
2331                        {
2332                                foreach($event['recur_exception'] as $key => $timestamp)
2333                                {
2334                                        $event['recur_exception'][$key] = $GLOBALS['server']->date2iso8601($timestamp);
2335                                }
2336                        }
2337                        static $user_cache = array();
2338
2339                        if (!is_object($GLOBALS['phpgw']->perferences))
2340                        {
2341                                $GLOBALS['phpgw']->perferences = CreateObject('phpgwapi.preferences');
2342                        }
2343                        foreach($event['participants'] as $user_id => $status)
2344                        {
2345                                if (!isset($user_cache[$user_id]))
2346                                {
2347                                        $user_cache[$user_id] = array(
2348                                                'name'   => $GLOBALS['phpgw']->common->grab_owner_name($user_id),
2349                                                'email'  => $GLOBALS['phpgw']->perferences->email_address($user_id)
2350                                        );
2351                                }
2352                                $event['participants'][$user_id] = $user_cache[$user_id] + array(
2353                                        'status' => $status,
2354                                );
2355                        }
2356                        if (is_array($event['alarm']))
2357                        {
2358                                foreach($event['alarm'] as $id => $alarm)
2359                                {
2360                                        $event['alarm'][$id]['time'] = $GLOBALS['server']->date2iso8601($alarm['time']);
2361                                        if ($alarm['owner'] != $GLOBALS['phpgw_info']['user']['account_id'])
2362                                        {
2363                                                unset($event['alarm'][$id]);
2364                                        }
2365                                }
2366                        }
2367                        $event['category'] = $GLOBALS['server']->cats2xmlrpc(explode(',',$event['category']));
2368
2369                        // using access={public|privat} in all modules via xmlrpc
2370                        $event['access'] = $event['public'] ? 'public' : 'privat';
2371                        unset($event['public']);
2372
2373                        return $event;
2374                }
2375
2376                /* Begin Appsession Data */
2377                function store_to_appsession($event)
2378                {
2379                        $GLOBALS['phpgw']->session->appsession('entry','calendar',$event);
2380                }
2381
2382                function restore_from_appsession()
2383                {
2384                        $this->event_init();
2385                        $event = $GLOBALS['phpgw']->session->appsession('entry','calendar');
2386                        $this->so->cal->event = $event;
2387                        return $event;
2388                }
2389                /* End Appsession Data */
2390
2391                /* Begin of SO functions */
2392                function get_cached_event()
2393                {
2394                        return $this->so->get_cached_event();
2395                }
2396
2397                function add_attribute($var,$value,$index='**(**')
2398                {
2399                        $this->so->add_attribute($var,$value,$index);
2400                }
2401
2402                function event_init()
2403                {
2404                        $this->so->event_init();
2405                }
2406
2407                function set_start($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2408                {
2409                        $this->so->set_start($year,$month,$day,$hour,$min,$sec);
2410                }
2411
2412                function set_end($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2413                {
2414                        $this->so->set_end($year,$month,$day,$hour,$min,$sec);
2415                }
2416
2417                function set_title($title='')
2418                {
2419                        $this->so->set_title($title);
2420                }
2421
2422                function set_description($description='')
2423                {
2424                        $this->so->set_description($description);
2425                }
2426                function set_ex_participants($ex_participants='')
2427                {
2428                        $this->so->set_ex_participants($ex_participants);
2429                }
2430
2431                function set_class($class)
2432                {
2433                        $this->so->set_class($class);
2434                }
2435
2436                function set_category($category='')
2437                {
2438                        $this->so->set_category($category);
2439                }
2440
2441                function set_alarm($alarm)
2442                {
2443                        $this->so->set_alarm($alarm);
2444                }
2445
2446                function set_recur_none()
2447                {
2448                        $this->so->set_recur_none();
2449                }
2450
2451                function set_recur_daily($year,$month,$day,$interval)
2452                {
2453                        $this->so->set_recur_daily($year,$month,$day,$interval);
2454                }
2455
2456                function set_recur_weekly($year,$month,$day,$interval,$weekdays)
2457                {
2458                        $this->so->set_recur_weekly($year,$month,$day,$interval,$weekdays);
2459                }
2460
2461                function set_recur_monthly_mday($year,$month,$day,$interval)
2462                {
2463                        $this->so->set_recur_monthly_mday($year,$month,$day,$interval);
2464                }
2465
2466                function set_recur_monthly_wday($year,$month,$day,$interval)
2467                {
2468                        $this->so->set_recur_monthly_wday($year,$month,$day,$interval);
2469                }
2470
2471                function set_recur_yearly($year,$month,$day,$interval)
2472                {
2473                        $this->so->set_recur_yearly($year,$month,$day,$interval);
2474                }
2475                /* End of SO functions */
2476
2477                function prepare_matrix($interval,$increment,$part,$fulldate)
2478                {
2479                        for($h=0;$h<24;$h++)
2480                        {
2481                                for($m=0;$m<$interval;$m++)
2482                                {
2483                                        $index = (($h * 10000) + (($m * $increment) * 100));
2484                                        $time_slice[$index]['marker'] = '&nbsp';
2485                                        $time_slice[$index]['description'] = '';
2486                                }
2487                        }
2488                        foreach($this->cached_events[$fulldate] as $event)
2489                        {
2490                                if ($event['participants'][$part] == 'R')
2491                                {
2492                                        continue;       // dont show rejected invitations, as they are free time
2493                                }
2494                                $eventstart = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset);
2495                                $eventend = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset);
2496                                $start = ($eventstart['hour'] * 10000) + ($eventstart['minute'] * 100);
2497                                $starttemp = $this->splittime("$start",False);
2498                                $subminute = 0;
2499                                for($m=0;$m<$interval;$m++)
2500                                {
2501                                        $minutes = $increment * $m;
2502                                        if((int)$starttemp['minute'] > $minutes && (int)$starttemp['minute'] < ($minutes + $increment))
2503                                        {
2504                                                $subminute = ($starttemp['minute'] - $minutes) * 100;
2505                                        }
2506                                }
2507                                $start -= $subminute;
2508                                $end =  ($eventend['hour'] * 10000) + ($eventend['minute'] * 100);
2509                                $endtemp = $this->splittime("$end",False);
2510                                $addminute = 0;
2511                                for($m=0;$m<$interval;$m++)
2512                                {
2513                                        $minutes = ($increment * $m);
2514                                        if($endtemp['minute'] < ($minutes + $increment) && $endtemp['minute'] > $minutes)
2515                                        {
2516                                                $addminute = ($minutes + $increment - $endtemp['minute']) * 100;
2517                                        }
2518                                }
2519                                $end += $addminute;
2520                                $starttemp = $this->splittime("$start",False);
2521                                $endtemp = $this->splittime("$end",False);
2522
2523                                for($h=$starttemp['hour'];$h<=$endtemp['hour'];$h++)
2524                                {
2525                                        $startminute = 0;
2526                                        $endminute = $interval;
2527                                        $hour = $h * 10000;
2528                                        if($h == (int)$starttemp['hour'])
2529                                        {
2530                                                $startminute = ($starttemp['minute'] / $increment);
2531                                        }
2532                                        if($h == (int)$endtemp['hour'])
2533                                        {
2534                                                $endminute = ($endtemp['minute'] / $increment);
2535                                        }
2536                                        $private = $this->is_private($event,$part);
2537                                        $time_display = $GLOBALS['phpgw']->common->show_date($eventstart['raw'],$this->users_timeformat).'-'.$GLOBALS['phpgw']->common->show_date($eventend['raw'],$this->users_timeformat);
2538                                        $time_description = '('.$time_display.') '.$this->get_short_field($event,$private,'title').$this->display_status($event['participants'][$part]);
2539                                        for($m=$startminute;$m<$endminute;$m++)
2540                                        {
2541                                                $index = ($hour + (($m * $increment) * 100));
2542                                                $time_slice[$index]['marker'] = '-';
2543                                                $time_slice[$index]['description'] = $time_description;
2544                                                $time_slice[$index]['id'] = $event['id'];
2545                                        }
2546                                }
2547                        }
2548                        return $time_slice;
2549                }
2550
2551                /*!
2552                @function set_status
2553                @abstract set the participant response $status for event $cal_id and notifies the owner of the event
2554                */
2555                function set_status($cal_id,$status)
2556                {
2557                        $status2msg = array(
2558                                REJECTED  => MSG_REJECTED,
2559                                TENTATIVE => MSG_TENTATIVE,
2560                                ACCEPTED  => MSG_ACCEPTED
2561                        );
2562                        if (!isset($status2msg[$status]))
2563                        {
2564                                return False;
2565                        }
2566                        $event = $this->so->read_entry($cal_id);
2567                        $account_id = $GLOBALS['phpgw_info']['user']['account_id'];
2568                        if(($status2msg[$status] == "5" && $event['participants'][$account_id] == "A") ||
2569                         ($status2msg[$status] == "3" && $event['participants'][$account_id] == "R")) {
2570                                return True;
2571                        }
2572                        $this->so->set_status($cal_id,$status);
2573                        $event = $this->so->read_entry($cal_id);
2574                        $this->send_update($status2msg[$status],$event['participants'],$event);
2575
2576                }
2577
2578                /*!
2579                @function update_requested
2580                @abstract checks if $userid has requested (in $part_prefs) updates for $msg_type
2581                @syntax update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2582                @param $userid numerical user-id
2583                @param $part_prefs preferces of the user $userid
2584                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2585                @param $old_event Event before the change
2586                @param $new_event Event after the change
2587                @returns 0 = no update requested, > 0 update requested
2588                */
2589                function update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2590                {
2591                        if ($msg_type == MSG_ALARM)
2592                        {
2593                                return True;    // always True for now
2594                        }
2595                        $want_update = 0;
2596
2597                        // the following switch fall-through all cases, as each included the following too
2598                        //
2599                        $msg_is_response = $msg_type == MSG_REJECTED || $msg_type == MSG_ACCEPTED || $msg_type == MSG_TENTATIVE;
2600
2601                        switch($ru = $part_prefs['calendar']['receive_updates'])
2602                        {
2603                                case 'responses':
2604                                        if ($msg_is_response)
2605                                        {
2606                                                ++$want_update;
2607                                        }
2608                                case 'modifications':
2609                                        if ($msg_type == MSG_MODIFIED)
2610                                        {
2611                                                ++$want_update;
2612                                        }
2613                                case 'time_change_4h':
2614                                case 'time_change':
2615                                        $diff = max(abs($this->maketime($old_event['start'])-$this->maketime($new_event['start'])),
2616                                                abs($this->maketime($old_event['end'])-$this->maketime($new_event['end'])));
2617                                        $check = $ru == 'time_change_4h' ? 4 * 60 * 60 - 1 : 0;
2618                                        if ($msg_type == MSG_MODIFIED && $diff > $check)
2619                                        {
2620                                                ++$want_update;
2621                                        }
2622                                case 'add_cancel':
2623                                        if ($old_event['owner'] == $userid && $msg_is_response ||
2624                                                $msg_type == MSG_DELETED || $msg_type == MSG_ADDED)
2625                                        {
2626                                                ++$want_update;
2627                                        }
2628                                        break;
2629                                case 'no':
2630                                        break;
2631                        }
2632                        //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";
2633                        return $want_update > 0;
2634                }
2635
2636        function create_vcard($event_array)
2637        {
2638        if(!is_array($event_array))
2639                return null;
2640        $tmpattach="BEGIN:VCALENDAR\n"
2641        ."PRODID:-//Expresso Livre//Calendar//EN\n"
2642        ."VERSION:1.0\n";
2643                foreach ($event_array as $event)
2644                {
2645                        // It translates int to string
2646                        if (!is_object($event) && !is_array($event) || !array_key_exists  ('end', $event))
2647                                $event = $event_array;
2648                        if ( $event['end']['month'] < 10 )
2649                                $end_event_month="0".$event['end']['month'];
2650                        else
2651                                $end_event_month=$event['end']['month'];
2652                        if ( $event['start']['month'] < 10 )
2653                                $start_event_month="0".$event['start']['month'];
2654                        else
2655                                $start_event_month=$event['start']['month'];
2656                        if ( $event['end']['mday'] < 10 )
2657                                $end_event_day="0".$event['end']['mday'];
2658                        else
2659                                $end_event_day=$event['end']['mday'];
2660                        if ( $event['start']['mday'] < 10 )
2661                                $start_event_day="0".$event['start']['mday'];
2662                        else
2663                                $start_event_day=$event['start']['mday'];
2664                        if ( $event['start']['hour'] < 10)
2665                                $start_event_hour="0".$event['start']['hour'];
2666                        else
2667                                $start_event_hour=$event['start']['hour'];
2668                        if ( $event['end']['hour'] < 10)
2669                                $end_event_hour="0".$event['end']['hour'];
2670                        else
2671                                $end_event_hour=$event['end']['hour'];
2672                               
2673                        if ( $event['start']['min'] < 10)
2674                                $start_event_min="0".$event['start']['min'];
2675                        else
2676                                $start_event_min=$event['start']['min'];
2677                        if ( $event['end']['min'] < 10)
2678                                $end_event_min="0".$event['end']['min'];
2679                        else
2680                                $end_event_min=$event['end']['min'];   
2681               
2682
2683                        $tmpattach.="BEGIN:VEVENT\n"
2684                        ."DTSTART:".$event['start'][year].$start_event_month.$start_event_day."T".$start_event_hour.$start_event_min."00Z\n"
2685                        ."DTEND:".$event[end][year].$end_event_month.$end_event_day."T".$end_event_hour.$end_event_min."00Z\n"
2686                        ."UID:Expresso-".$event[id].$event[uid]."\n"
2687                        ."LAST-MODIFIED:".time()."\n"
2688                        ."DESCRIPTION:".$event[description]."\n"
2689                        ."SUMMARY:".$event[title]."\n"
2690                        ."LOCATION:".$event[location]."\n"
2691                        ."END:VEVENT"."\n";
2692                }
2693                        $tmpattach.="END:VCALENDAR\n";
2694                        return $tmpattach;
2695}
2696
2697                /*!
2698                @function send_update
2699                @abstract sends update-messages to certain participants of an event
2700                @syntax send_update($msg_type,$to_notify,$old_event,$new_event=False)
2701                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2702                @param $to_notify array with numerical user-ids as keys (!) (value is not used)
2703                @param $old_event Event before the change
2704                @param $new_event Event after the change
2705                */
2706                function send_update($msg_type,$to_notify,$old_event,$new_event=False,$user=False)
2707                {
2708                       
2709                        //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";
2710                        if (!is_array($to_notify))
2711                        {
2712                                $to_notify = array();
2713                        }
2714                        $owner = $old_event ? $old_event['owner'] : $new_event['owner'];
2715                        if ($owner && !isset($to_notify[$owner]) && $msg_type != MSG_ALARM)
2716                        {
2717                                $to_notify[$owner] = 'owner';   // always include the event-owner
2718                        }
2719                        $version = $GLOBALS['phpgw_info']['apps']['calendar']['version'];
2720
2721                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences();
2722                        $sender = $GLOBALS['phpgw_info']['user']['email'];
2723
2724                        $temp_tz_offset = $this->prefs['common']['tz_offset'];
2725                        $temp_timeformat = $this->prefs['common']['timeformat'];
2726                        $temp_dateformat = $this->prefs['common']['dateformat'];
2727
2728                        $tz_offset = ((60 * 60) * (int)$temp_tz_offset);
2729
2730                        if($old_event != False)
2731                        {
2732                                $t_old_start_time = $this->maketime($old_event['start']);
2733                                if($t_old_start_time < (time() - 86400))
2734                                {
2735                                        return False;
2736                                }
2737                        }
2738
2739                        $temp_user = $GLOBALS['phpgw_info']['user'];
2740
2741                        if (!$user)
2742                        {
2743                                $user = $this->owner;
2744                        }
2745                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences($user);
2746
2747                        $event = $msg_type == MSG_ADDED || $msg_type == MSG_MODIFIED ? $new_event : $old_event;
2748                        if($old_event != False)
2749                        {
2750                                $old_starttime = $t_old_start_time - $GLOBALS['phpgw']->datetime->tz_offset;
2751                        }
2752                        $starttime = $this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
2753                        $endtime   = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
2754
2755                        switch($msg_type)
2756                        {
2757                                case MSG_DELETED:
2758                                        $action = lang('Canceled');
2759                                        $msg = 'Canceled';
2760                                        $msgtype = '"calendar";';
2761                                        $method = 'cancel';
2762                                        $typesend = 1;
2763                                        break;
2764                                case MSG_MODIFIED:
2765                                        $action = lang('Modified');
2766                                        $msg = 'Modified';
2767                                        $msgtype = '"calendar"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2768                                        $method = 'request';
2769                                        $typesend = 2;
2770                                        break;
2771                                case MSG_ADDED:
2772                                        $action = lang('Added');
2773                                        $msg = 'Added';
2774                                        $msgtype = '"calendar"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2775                                        $method = 'request';
2776                                        $typesend = 3;
2777                                        break;
2778                                case MSG_REJECTED:
2779                                        $action = lang('Rejected');
2780                                        $msg = 'Response';
2781                                        $msgtype = '"calendar";';
2782                                        $method = 'reply';
2783                                        $typesend = 4;
2784                                        break;
2785                                case MSG_TENTATIVE:
2786                                        $action = lang('Tentative');
2787                                        $msg = 'Response';
2788                                        $msgtype = '"calendar";';
2789                                        $method = 'reply';
2790                                        $typesend = 5;
2791                                        break;
2792                                case MSG_ACCEPTED:
2793                                        $action = lang('Accepted');
2794                                        $msg = 'Response';
2795                                        $msgtype = '"calendar";';
2796                                        $method = 'reply';
2797                                        $typesend = 6;
2798                                        break;
2799                                case MSG_ALARM:
2800                                        $action = lang('Alarm');
2801                                        $msg = 'Alarm';
2802                                        $msgtype = '"calendar";';
2803                                        $method = 'publish';    // duno if thats right
2804                                        $typesend = 7;
2805                                        break;
2806                                default:
2807                                        $method = 'publish';
2808                                        $typesend = 8;
2809                        }
2810                        $notify_msg = $this->prefs['calendar']['notify'.$msg];
2811                        if (empty($notify_msg))
2812                        {
2813                                $notify_msg = $this->prefs['calendar']['notifyAdded'];  // use a default
2814                        }
2815                        $details = array(                       // event-details for the notify-msg
2816                                'id'          => $msg_type == MSG_ADDED ? $new_event['id'] : $old_event['id'],
2817                                'action'      => $action,
2818                        );
2819                        $event_arr = $this->event2array($event);
2820                        foreach($event_arr as $key => $val)
2821                        {
2822                                $details[$key] = $val['data'];
2823                        }
2824                       
2825                        $details['participants'] = implode("\n",$details['participants']);
2826
2827                        $details['link'] = $GLOBALS['phpgw_info']['server']['webserver_url'].'/index.php?menuaction=calendar.uicalendar.view&cal_id='.$event['id'];
2828                        // if url is only a path, try guessing the rest ;-)
2829                        if ($GLOBALS['phpgw_info']['server']['webserver_url'][0] == '/')
2830                        {
2831                                $details['link'] = ($GLOBALS['phpgw_info']['server']['enforce_ssl'] ? 'https://' : 'http://').
2832                                        ($GLOBALS['phpgw_info']['server']['hostname'] ? $GLOBALS['phpgw_info']['server']['hostname'] : 'localhost').
2833                                        $details['link'];
2834                        }
2835                       
2836                        //Seta o email usando phpmailer
2837                        define('PHPGW_INCLUDE_ROOT','../');     
2838                        define('PHPGW_API_INC','../phpgwapi/inc');     
2839                        include_once(PHPGW_API_INC.'/class.phpmailer.inc.php');
2840                        $mail = new PHPMailer();
2841                        $mail->IsSMTP();
2842                        $boemailadmin = CreateObject('emailadmin.bo');
2843                        $emailadmin_profile = $boemailadmin->getProfileList();
2844                        $emailadmin = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
2845               
2846                        $mail->Host = $emailadmin['smtpServer'];
2847                        $mail->Port = $emailadmin['smtpPort'];
2848                        $mail->From = $GLOBALS['phpgw']->preferences->values['email'];
2849                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
2850                        $mail->IsHTML(true);
2851
2852                        // Aqui ï¿œ enviado o email
2853                        foreach($to_notify as $userid => $statusid)
2854                        {
2855                                $mail->ClearAttachments();
2856                               
2857                                $userid = (int)$userid;
2858
2859                                if ($statusid == 'R' || $GLOBALS['phpgw']->accounts->get_type($userid) == 'g')
2860                                {
2861                                        continue;       // dont notify rejected participants
2862                                }
2863                                if($userid != $GLOBALS['phpgw_info']['user']['account_id'] ||  $msg_type == MSG_ALARM)
2864                                {
2865                                        print_debug('Msg Type',$msg_type);
2866                                        print_debug('UserID',$userid);
2867
2868                                        $preferences = CreateObject('phpgwapi.preferences',$userid);
2869                                        $part_prefs = $preferences->read_repository();
2870
2871                                        if (!$this->update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event))
2872                                        {
2873                                                continue;
2874                                        }
2875                                        $GLOBALS['phpgw']->accounts->get_account_name($userid,$lid,$details['to-firstname'],$details['to-lastname']);
2876                                        $details['to-fullname'] = $GLOBALS['phpgw']->common->display_fullname('',$details['to-firstname'],$details['to-lastname']);
2877
2878                                        $to = $preferences->email_address($userid);
2879                                       
2880                                        if (empty($to) || $to[0] == '@' || $to[0] == '$')       // we have no valid email-address
2881                                        {
2882                                                //echo "<p>bocalendar::send_update: Empty email adress for user '".$details['to-fullname']."' ==> ignored !!!</p>\n";
2883                                                continue;
2884                                        }
2885                                        print_debug('Email being sent to',$to);
2886
2887                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $part_prefs['common']['tz_offset'];
2888                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $part_prefs['common']['timeformat'];
2889                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $part_prefs['common']['dateformat'];
2890
2891                                        $GLOBALS['phpgw']->datetime->tz_offset = ((60 * 60) * (int)$GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset']);
2892
2893                                        if($old_starttime)
2894                                        {
2895                                                $details['olddate'] = $GLOBALS['phpgw']->common->show_date($old_starttime);
2896                                        }
2897                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
2898                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
2899                                       
2900                                       
2901                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
2902                                       
2903                                        switch($part_prefs['calendar']['update_format'])
2904                                        {
2905                                                case  'extended':
2906                                                        //$body .= "\n\n".lang('Event Details follow').":\n";
2907                                                        $body = '';
2908                                                        $body .= "<br>".lang('Event Details follow')." :: ";
2909                                                        foreach($event_arr as $key => $val)
2910                                                        {
2911                                                                // titulo
2912                                                                if($key =='title')
2913                                                                {
2914                                                                        $var1 = $val['field'];
2915                                                                        $vardata1 = $details[$key];
2916                                                                }
2917                                                                //descricao
2918                                                                if($key =='description')
2919                                                                {
2920                                                                        $var2 = $val['field'];
2921                                                                        $vardata2 = $details[$key];
2922                                                                }
2923                                                                //dt inicio
2924                                                                if($key =='startdate')
2925                                                                {
2926                                                                        switch(trim($part_prefs['common']['dateformat']))
2927                                                                        {
2928                                                                               
2929                                                                                case ($part_prefs['common']['dateformat'] === "m/d/Y" || $part_prefs['common']['dateformat'] === "m-d-Y" || $part_prefs['common']['dateformat'] === "m.d.Y"):
2930                                                                                        $var3 = $val['field'];
2931                                                                                        $vardata3 = $details[$key];
2932                                                                                        $newmounth3 = substr($vardata3,0,2);
2933                                                                                        $newday3 = substr($vardata3,3,2);
2934                                                                                        $newyear3 = substr($vardata3,6,4);
2935                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
2936                                                                                        break;
2937                                                                                       
2938                                                                                case    ($part_prefs['common']['dateformat'] === "Y/d/m" || $part_prefs['common']['dateformat'] === "Y-d-m" || $part_prefs['common']['dateformat'] === "Y.d.m"):
2939
2940                                                                                        $var3 = $val['field'];
2941                                                                                        $vardata3 = $details[$key];
2942                                                                                        $newyear3 = substr($vardata3,0,4);
2943                                                                                        $newday3 = substr($vardata3,5,2);
2944                                                                                        $newmounth3 = substr($vardata3,8,2);
2945                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
2946                                                                                        break;
2947
2948                                                                                case ($part_prefs['common']['dateformat'] === "Y/m/d" || $part_prefs['common']['dateformat'] === "Y-m-d" || $part_prefs['common']['dateformat'] === "Y.m.d"):
2949
2950                                                                                        $var3 = $val['field'];
2951                                                                                        $vardata3 = $details[$key];
2952                                                                                        $newyear3 = substr($vardata3,0,4);
2953                                                                                        $newmounth3 = substr($vardata3,5,2);
2954                                                                                        $newday3 = substr($vardata3,8,2);
2955                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
2956                                                                                        break;
2957
2958                                                                                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"):
2959                                                                               
2960                                                                                        $var3 = $val['field'];
2961                                                                                        $vardata3 = $details[$key];
2962                                                                                        $newday3 = substr($vardata3,0,2);
2963                                                                                        $newmounth3 = substr($vardata3,3,2);
2964                                                                                        $newyear3 = substr($vardata3,6,4);
2965                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
2966                                                                                        break;
2967                                                                       
2968                                                                        }
2969                                                                       
2970                                                                }
2971                                                                //dt final
2972                                                                if($key =='enddate')
2973                                                                {
2974                                                                        $var4 = $val['field'];
2975                                                                        $vardata4 = $details[$key];
2976                                                                }
2977                                                                //localizacao
2978                                                                if($key =='location')
2979                                                                {
2980                                                                        $var8 = $val['field'];
2981                                                                        $vardata8 = $details[$key];
2982                                                                }
2983                                                                //participantes
2984                                                                if($key =='participants')
2985                                                                {
2986                                                                        $var5 = $val['field'];
2987                                                                        foreach($val['data'] as $NewKey => $NewVal)
2988                                                                        {
2989                                                                                //Research inside of ldap ( Pesquisa dentro do ldap )
2990                                                                                $newvalue = $this->so->search_uidNumber($to);
2991                                                                                foreach($newvalue as $tmp)
2992                                                                                {
2993                                                                                        $tmpmail = $tmp['mail'][0];
2994                                                                                        $tmpuid = $tmp['uidnumber'][0];
2995                                                                                        if( trim($tmpmail) == trim($to) & trim($tmpuid) == trim($NewKey))
2996                                                                                        {
2997                                                                                                        if($typesend == 3)
2998                                                                                                        {
2999
3000                                                                                                                $lang1 = lang("To See Commitment");
3001                                                                                                                $varbuttom = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.view&cal_id=$event[id]&date=$newall3' method='POST'>
3002                                                                                                                                                                  <input type='submit' value='$lang1'>
3003                                                                                                                                                                   </form>";
3004                                                                                                                $lang2 = lang("To accept");
3005                                                                                                                $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\")'>";
3006
3007                                                                                                                $lang3 = lang("To reject");
3008                                                                                                                $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\")'>";
3009                                                                                                               
3010                                                                                                                $lang4 = lang("Alarm");
3011                                                                                                                $varbuttom3 = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uialarm.manager method='POST'>
3012                                                                                                                                                                  <input type='submit' value='$lang4'>
3013                                                                                                                                                                  <input type='hidden' name='cal_id' value=$event[id]>
3014                                                                                                                                                                   </form>";
3015                                                                                                        }
3016                                                                                                        else
3017                                                                                                        {
3018                                                                                                                        $varbuttom  = "";
3019                                                                                                                        $varbuttom1 = "";
3020                                                                                                                        $varbuttom2 = "";
3021                                                                                                                        $varbuttom3 = "";
3022                                                                                                        }
3023                                                                                        }
3024                                                                                        // It only mounts variavel with the name of the participants of the list ( Monta a variavel somente com o nome dos participantes da lista)
3025                                                                                        if($typesend == 3)
3026                                                                                        {
3027                                                                                                list($tmpvardata5,$tmp2vardata5) = explode("(",$NewVal);
3028                                                                                                $vardata5 = $tmpvardata5."<br>";
3029                                                                                        }
3030                                                                                        else
3031                                                                                        {
3032                                                                                                $vardata5 = $NewVal."<br>";
3033                                                                                        }
3034                                                                               
3035                                                                                }
3036                                                                                $vardata6 .= $vardata5;
3037                                                                                unset($vardata5);
3038                                                                        }
3039                                                                }               
3040                                                        }
3041                                                        //To mount the message as text/html (Para montar a mensagem como text/html - /phpgwapi/inc/class.send.inc.php )
3042                                                        $content_type = "text/html";
3043                                                        //It mounts the body of the message (Monta o corpo da mensagem)
3044                                                       
3045                                                        // A constante PHPGW_APP_TPL nao existe para envio de alarmes (cront, asyncservice).
3046                                                        define ("PHPGW_APP_TPL",PHPGW_API_INC . "/../../calendar/templates/celepar");
3047                                                       
3048                                                        $body = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
3049                                                        $body->set_file(Array('calendar' => 'body_email.tpl'));
3050                                                        $body->set_block('calendar','list');
3051                                                        $var = Array(
3052                                                                'script'                        => $script,
3053                                                                'subject'                       => $body1,
3054                                                                'var1'                          => $var1,
3055                                                                'vardata1'                      => $vardata1,
3056                                                                'var2'                          => $var2,
3057                                                                'vardata2'                      => $vardata2,
3058                                                                'var3'                          => $var3,
3059                                                                'vardata3'                      => $vardata3,
3060                                                                'var4'                          => $var4,
3061                                                                'vardata4'                      => $vardata4,
3062                                                                'var5'                          => $var5,
3063                                                                'vardata6'                      => $vardata6,
3064                                                                'var8'                          => $var8,
3065                                                                'vardata8'                      => $vardata8,                                                   
3066                                                                'varbuttom'                     => $varbuttom,
3067                                                                'varbuttom1'            => $varbuttom1,
3068                                                                'varbuttom2'            => $varbuttom2,
3069                                                                'varbuttom3'            => $varbuttom3
3070                                                               
3071                                                        );
3072                                                        $body->set_var($var);
3073                                                        $tmpbody = $body->fp('out','list');
3074                                                                                                               
3075                                                        break;
3076
3077                                                case 'ical':
3078                                                        $content_type = "calendar; method=$method; name=calendar.ics";
3079/*                                                      if ($body != '')
3080                                                        {
3081                                                                $boundary = '----Message-Boundary';
3082                                                                $body .= "\n\n\n$boundary\nContent-type: text/$content_type\n".
3083                                                                        "Content-Disposition: inline\nContent-transfer-encoding: 7BIT\n\n";
3084                                                                $content_type = '';
3085                                                        }
3086*/
3087                                                        $body = ExecMethod('calendar.boicalendar.export',array(
3088                                                                'l_event_id'  => $event['id'],
3089                                                                'method'      => $method,
3090                                                                'chunk_split' => False
3091                                                        ));
3092                                                        break;
3093                                        }
3094                                        $mail->AddAddress($to);
3095                                        $mail->Body = $tmpbody;
3096                                        $mail->From = $sender;
3097                                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3098                                        $mail->Sender = $mail->From;
3099                                        $mail->SenderName = $mail->FromName;
3100                                        $mail->Subject = $subject;
3101                                        unset($vardata5);
3102                                        unset($vardata6);
3103                                }
3104                        }
3105
3106                        //Inicializa variï¿œvel de retorno.
3107                        $returncode=true;                       
3108                        if(count($mail->to)) {                         
3109                                // Envia aviso a todos os participantes.
3110                                if(!$mail->Send()) {                           
3111                                        $returncode = false;
3112                                        $errorInfo['participants'] = $mail->ErrorInfo;
3113                                }
3114                                else
3115                                        $returncode =  true;
3116                        }
3117                       
3118                        if(count($to_notify) && $this->ex_participants){
3119                                $mail->ClearAllRecipients();
3120                                $var = explode(",",trim($this->ex_participants));
3121                                $to = array();
3122                                if(!$subject) {
3123                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
3124                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
3125                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
3126                                }
3127                               
3128                                foreach($var as $index => $ex_participant){
3129                                        $ex_participant = trim($ex_participant);
3130                                        $ex_participant = preg_replace('#"(.*)" <(.*)\@(.*)\.(.*)>#','\\2@\\3.\\4',$ex_participant);
3131                                                if($ex_participant)
3132                                                        $to[] = $ex_participant;
3133                                }               
3134                               
3135                                foreach($to as $i => $to_array)
3136                                        $mail->AddAddress($to_array);
3137                               
3138                                $_body = explode("<hr size='1' width='100%'>",$tmpbody);
3139                                $tmpbody = $_body[0] ? $_body[0] : $subject ;
3140                                $tmpbody.= "<br><b>".lang("external participants").":: </b> ".htmlentities($this->ex_participants);
3141                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3142                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";
3143                                $tmpbody.= "<br><br><hr size='1' width='100%'><font color='red'>"
3144                                .lang("This message was sent by server. You must send a message to sender to confirm this event")."<br>"
3145                                .lang("This is an external event. Even if it added to your expresso its can be changed any time at all")."</font><br>";
3146                               
3147                                if ($GLOBALS['bocalendar']->so->cal->event[start][month] > 10)
3148                                        $event_month=$GLOBALS['bocalendar']->so->cal->event[start][month];
3149                                else
3150                                        $event_month="0".$GLOBALS['bocalendar']->so->cal->event[start][month];
3151                                //attach extern vcard                   
3152                                // define('context','$GLOBALS.bocalendar.so.cal.event');
3153                                $tmpattach = $this->create_vcard($GLOBALS['bocalendar']->so->cal->event);
3154                                if($tmpattach){                                 
3155                                        $tmpbody .="<a href='../index.php?menuaction=calendar.uicalendar.add&date="
3156                                        .$GLOBALS['bocalendar']->so->cal->event[start][year]
3157                                .$event_month
3158                                .$GLOBALS['bocalendar']->so->cal->event[start][mday]
3159                                        ."&hour=".$GLOBALS['bocalendar']->so->cal->event[start][hour]
3160                                        ."&minute=".$GLOBALS['bocalendar']->so->cal->event[start][min]
3161                                        ."&title=".$GLOBALS['bocalendar']->so->cal->event['title']
3162                                        ."&description=".$GLOBALS['bocalendar']->so->cal->event['description']
3163                                        ."&location=".$GLOBALS['bocalendar']->so->cal->event['location']."'>"
3164                                        ."<h2>".lang("Add to my expresso")."</h2>";
3165                                        $tempdir = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
3166                                        srand((double)microtime()*1000000);
3167                                        $random_number = rand(100000000,999999999);
3168                                        $newfilename = md5(time() . getenv("REMOTE_ADDR") . $random_number );
3169                                        $filename = $tempdir . $newfilename;
3170                                        $attach_fd = fopen($filename,"w+");
3171                                        fwrite($attach_fd,$tmpattach);
3172                                        $mail->AddAttachment($filename, "extern.vcard", "base64", "text/plain"); // "application/octet-stream"
3173                                        fclose($attach_fd);
3174                                }
3175                                $mail->From = $sender;
3176                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3177                                $mail->Sender = $mail->From;
3178                                $mail->SenderName = $mail->FromName;
3179                                $mail->Subject = lang("External event from Expresso");
3180                                $mail->Body = $tmpbody;
3181                                                                                                                                               
3182                                if(!$mail->Send())
3183                                {
3184                                        $returncode=false;
3185                                        $errorInfo['ex_participants'] = $mail->ErrorInfo;
3186                                }
3187                                else
3188                                {
3189                                        $returncode=true;
3190                                }
3191                        }
3192
3193
3194                        if((is_int($this->user) && $this->user != $temp_user['account_id']) ||
3195                                (is_string($this->user) && $this->user != $temp_user['account_lid']))
3196                        {
3197                                $GLOBALS['phpgw_info']['user'] = $temp_user;
3198                        }       
3199
3200                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $temp_tz_offset;
3201                        $GLBOALS['phpgw']->datetime->tz_offset = ((60 * 60) * $temp_tz_offset);
3202                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $temp_timeformat;
3203                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $temp_dateformat;
3204                       
3205                        // Notifica por email o criador do compromisso, com as possï¿œveis falhas.                                             
3206                        if($errorInfo) {
3207                                $tmpbody = "<font color='red'>".lang("The following commitment had problems for DELIVERING the NOTIFICATION messages.").".</font><br>";
3208                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3209                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";                         
3210                                $tmpbody.= "<br><u>".lang("Failed to delivery")."</u><br>";
3211                                $failed = false;                               
3212                                if(strstr($errorInfo['participants'],"recipients_failed")){
3213                                        $failed = explode("recipients_failed",$errorInfo['participants']);
3214                                        $tmpbody.= lang("to").": ".$failed[1];
3215                                }
3216                                if(strstr($errorInfo['ex_participants'],"recipients_failed")){
3217                                        $failed = explode("recipients_failed",$errorInfo['ex_participants']);
3218                                        $tmpbody.= lang("to").": ".$failed[1];
3219                                }                       
3220                                if(!$failed) {
3221                                        $tmpbody.= lang("Description").":<br>";
3222                                        $tmpbody.= $errorInfo['participants'];
3223                                        $tmpbody.= "<br>".$errorInfo['ex_participants'];
3224                                }
3225                                $tmpbody.= "<br>".lang("Subject").": ".$subject;
3226                                // Reinicializa o objeto, devido ao erro anterior na entrega.
3227                               
3228                                $mail = new PHPMailer();
3229                                $mail->IsSMTP();
3230                                $mail->Host = $emailadmin['smtpServer'];
3231                                $mail->Port = $emailadmin['smtpPort'];
3232                                $mail->From = $sender;
3233                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3234                                $mail->Sender = $mail->From;
3235                                $mail->SenderName = $mail->FromName;
3236                                $mail->IsHTML(True);
3237                                $mail->Subject = lang("calendar event")." - ".lang("email notification");                                                       
3238                                $mail->Body = $tmpbody;                                 
3239                                $mail->AddAddress($sender);
3240                                if(!$mail->Send())                     
3241                                        $returncode = false;
3242                                else
3243                                        $returncode =  true;
3244                        }
3245                        return $returncode;
3246                }
3247               
3248                function send_alarm($alarm)
3249                {
3250                        //echo "<p>bocalendar::send_alarm("; print_r($alarm); echo ")</p>\n";
3251                       
3252                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->owner = $alarm['owner'];
3253
3254                        if (!$alarm['enabled'] || !$alarm['owner'] || !$alarm['cal_id'] || !($event = $this->so->read_entry($alarm['cal_id'])))
3255                        {
3256                                return False;   // event not found
3257                        }
3258                        if ($alarm['all'])
3259                        {
3260                                $to_notify = $event['participants'];
3261                        }
3262                        elseif ($this->check_perms(PHPGW_ACL_READ,$event))      // checks agains $this->owner set to $alarm[owner]
3263                        {
3264                                $to_notify[$alarm['owner']] = 'A';
3265                        }
3266                        else
3267                        {
3268                                return False;   // no rights
3269                        }
3270                        return $this->send_update(MSG_ALARM,$to_notify,$event,False,$alarm['owner']);
3271                }
3272
3273                function get_alarms($event_id)
3274                {
3275                        return $this->so->get_alarm($event_id);
3276                }
3277
3278                function alarm_today($event,$today,$starttime)
3279                {
3280                        $found = False;
3281                        @reset($event['alarm']);
3282                        $starttime_hi = $GLOBALS['phpgw']->common->show_date($starttime,'Hi');
3283                        $t_appt['month'] =$GLOBALS['phpgw']->common->show_date($today,'m');
3284                        $t_appt['mday'] = $GLOBALS['phpgw']->common->show_date($today,'d');
3285                        $t_appt['year'] = $GLOBALS['phpgw']->common->show_date($today,'Y');
3286                        $t_appt['hour'] = $GLOBALS['phpgw']->common->show_date($starttime,'H');
3287                        $t_appt['min']  = $GLOBALS['phpgw']->common->show_date($starttime,'i');
3288                        $t_appt['sec']  = 0;
3289                        $t_time = $this->maketime($t_appt) - $GLOBALS['phpgw']->datetime->tz_offset;
3290                        $y_time = $t_time - 86400;
3291                        $tt_time = $t_time + 86399;
3292                        print_debug('T_TIME',$t_time.' : '.$GLOBALS['phpgw']->common->show_date($t_time));
3293                        print_debug('Y_TIME',$y_time.' : '.$GLOBALS['phpgw']->common->show_date($y_time));
3294                        print_debug('TT_TIME',$tt_time.' : '.$GLOBALS['phpgw']->common->show_date($tt_time));
3295                        while(list($key,$alarm) = each($event['alarm']))
3296                        {
3297                                if($alarm['enabled'])
3298                                {
3299                                        print_debug('TIME',$alarm['time'].' : '.$GLOBALS['phpgw']->common->show_date($alarm['time']).' ('.$event['id'].')');
3300                                        if($event['recur_type'] != MCAL_RECUR_NONE)   /* Recurring Event */
3301                                        {
3302                                                print_debug('Recurring Event');
3303                                                if($alarm['time'] > $y_time && $GLOBALS['phpgw']->common->show_date($alarm['time'],'Hi') < $starttime_hi && $alarm['time'] < $t_time)
3304                                                {
3305                                                        $found = True;
3306                                                }
3307                                        }
3308                                        elseif($alarm['time'] > $y_time && $alarm['time'] < $t_time)
3309                                        {
3310                                                $found = True;
3311                                        }
3312                                }
3313                        }
3314                        print_debug('Found',$found);
3315                        return $found;
3316                }
3317
3318                function prepare_recipients(&$new_event,$old_event)
3319                {
3320                                               
3321                        // Find modified and deleted users.....
3322                        while(list($old_userid,$old_status) = each($old_event['participants']))
3323                        {
3324                                if(isset($new_event['participants'][$old_userid]))
3325                                {
3326                                        print_debug('Modifying event for user',$old_userid);
3327                                        $this->modified[(int)$old_userid] = $new_status;
3328                                }
3329                                else
3330                                {
3331                                        print_debug('Deleting user from the event',$old_userid);
3332                                        $this->deleted[(int)$old_userid] = $old_status;
3333                                }
3334                        }
3335                        // Find new users.....
3336                        while(list($new_userid,$new_status) = each($new_event['participants']))
3337                        {
3338                                if(!isset($old_event['participants'][$new_userid]))
3339                                {
3340                                        print_debug('Adding event for user',$new_userid);
3341                                        $this->added[$new_userid] = 'U';
3342                                        $new_event['participants'][$new_userid] = 'U';
3343                                }
3344                        }
3345                       
3346                        if(count($this->added) > 0 || count($this->modified) > 0 || count($this->deleted) > 0)
3347                        {
3348                                if(count($this->added) > 0)
3349                                {
3350                                        $this->ex_participants = '';
3351                                        $this->send_update(MSG_ADDED,$this->added,'',$new_event);
3352                                }
3353                                if(count($this->modified) > 0)
3354                                {
3355                                        $this->send_update(MSG_MODIFIED,$this->modified,$old_event,$new_event);
3356                                }
3357                                if(count($this->deleted) > 0)
3358                                {
3359                                        $this->ex_participants = '';
3360                                        $this->send_update(MSG_DELETED,$this->deleted,$old_event);
3361                                }
3362                        }
3363                }
3364
3365                function remove_doubles_in_cache($firstday,$lastday)
3366                {
3367                        $already_moved = Array();
3368                        for($v=$firstday;$v<=$lastday;$v++)
3369                        {
3370                                if (!$this->cached_events[$v])
3371                                {
3372                                        continue;
3373                                }
3374                                $cached = $this->cached_events[$v];
3375                                $this->cached_events[$v] = array();
3376                                while (list($g,$event) = each($cached))
3377                                {
3378                                        $end = date('Ymd',$this->maketime($event['end']));
3379                                        print_debug('EVENT',_debug_array($event,False));
3380                                        print_debug('start',$start);
3381                                        print_debug('v',$v);
3382
3383                                        if (!isset($already_moved[$event['id']]) || $event['recur_type'] && $v > $end)
3384                                        {
3385                                                $this->cached_events[$v][] = $event;
3386                                                $already_moved[$event['id']] = 1;
3387                                                print_debug('Event moved');
3388                                        }
3389                                }
3390                        }
3391                }
3392
3393                function get_dirty_entries($lastmod=-1)
3394                {
3395                        $events = false;
3396                        $event_ids = $this->so->cal->list_dirty_events($lastmod);
3397                        if(is_array($event_ids))
3398                        {
3399                                foreach($event_ids as $key => $id)
3400                                {
3401                                        $events[$id] = $this->so->cal->fetch_event($id);
3402                                }
3403                        }
3404                        unset($event_ids);
3405
3406                        $rep_event_ids = $this->so->cal->list_dirty_events($lastmod,$true);
3407                        if(is_array($rep_event_ids))
3408                        {
3409                                foreach($rep_event_ids as $key => $id)
3410                                {
3411                                        $events[$id] = $this->so->cal->fetch_event($id);
3412                                }
3413                        }
3414                        unset($rep_event_ids);
3415
3416                        return $events;
3417                }
3418
3419                function _debug_array($data)
3420                {
3421                        echo '<br>UI:';
3422                        _debug_array($data);
3423                }
3424
3425                /*!
3426                @function rejected_no_show
3427                @abstract checks if event is rejected from user and he's not the owner and dont want rejected
3428                @param $event to check
3429                @returns True if event should not be shown
3430                */
3431                function rejected_no_show($event)
3432                {
3433                        $ret = !$this->prefs['calendar']['show_rejected'] &&
3434                                $event['owner'] != $this->owner &&
3435                                $event['participants'][$this->owner] == 'R';
3436                        //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";
3437                        return $ret;
3438                }
3439
3440                /* This is called only by list_cals().  It was moved here to remove fatal error in php5 beta4 */
3441                function list_cals_add($id,&$users,&$groups)
3442                {
3443                        $name = $GLOBALS['phpgw']->common->grab_owner_name($id);
3444                        if (($type = $GLOBALS['phpgw']->accounts->get_type($id)) == 'g')
3445                        {
3446                                $arr = &$groups;
3447                        }
3448                        else
3449                        {
3450                                $arr = &$users;
3451                        }
3452                        $arr[$name] = Array(
3453                                'grantor' => $id,
3454                                'value'   => ($type == 'g' ? 'g_' : '') . $id,
3455                                'name'    => $name
3456                        );
3457                }
3458
3459                /*!
3460                @function list_cals
3461                @abstract generate list of user- / group-calendars for the selectbox in the header
3462                @returns alphabeticaly sorted array with groups first and then users
3463                */
3464                function list_cals()
3465                {
3466                        $users = $groups = array();
3467                        foreach($this->grants as $id => $rights)
3468                        {
3469                                $this->list_cals_add($id,$users,$groups);
3470                        }
3471                       
3472                        //by JakJr, melhora de performance na abertura da agenda
3473                        /*if ($memberships = $GLOBALS['phpgw']->accounts->membership($GLOBALS['phpgw_info']['user']['account_id']))
3474                        {
3475                                foreach($memberships as $group_info)
3476                                {
3477                                        $this->list_cals_add($group_info['account_id'],$users,$groups);
3478
3479                                        if ($account_perms = $GLOBALS['phpgw']->acl->get_ids_for_location($group_info['account_id'],PHPGW_ACL_READ,'calendar'))
3480                                        {
3481                                                foreach($account_perms as $id)
3482                                                {
3483                                                        $this->list_cals_add($id,$users,$groups);
3484                                                }
3485                                        }
3486                                }
3487                        }*/
3488                        uksort($users,'strnatcasecmp');
3489                        uksort($groups,'strnatcasecmp');
3490
3491                        return $users + $groups;        // users first and then groups, both alphabeticaly
3492                }
3493
3494          function translate($key,$vars=false, $not_found='*' )
3495          {
3496            if ($this->async)
3497              return $GLOBALS['phpgw']->translation->translate_async($key, $vars);
3498            return lang($key, $vars);
3499          }
3500
3501                /*!
3502                @function event2array
3503                @abstract create array with name, translated name and readable content of each attributes of an event
3504                @syntax event2array($event,$sep='<br>')
3505                @param $event event to use
3506                @returns array of attributes with fieldname as key and array with the 'field'=translated name \
3507                        'data' = readable content (for participants this is an array !)
3508                */
3509                function event2array($event)
3510                {
3511                       
3512                       
3513                  $var['title'] = Array(
3514                                'field'         => $this->translate('Title'),
3515                                'data'          => $event['title']
3516                        );
3517
3518                        // Some browser add a \n when its entered in the database. Not a big deal
3519                        // this will be printed even though its not needed.
3520                        $var['description'] = Array(
3521                                'field' => $this->translate('Description'),
3522                                'data'  => $event['description']
3523                        );
3524
3525                        $var['ex_participants'] = Array(
3526                                'field' => $this->translate('External Participants'),
3527                                'data'  => $event['ex_participants']
3528                        );
3529                       
3530                        $cats = Array();
3531                        $this->cat->categories($this->bo->owner,'calendar');
3532                        if(strpos($event['category'],','))
3533                        {
3534                                $cats = explode(',',$event['category']);
3535                        }
3536                        else
3537                        {
3538                                $cats[] = $event['category'];
3539                        }
3540                        foreach($cats as $cat_id)
3541                        {
3542                                list($cat) = $this->cat->return_single($cat_id);
3543                                $cat_string[] = $cat['name'];
3544                        }
3545                        $var['category'] = Array(
3546                                'field' => $this->translate('Category'),
3547                                'data'  => implode(', ',$cat_string)
3548                        );
3549
3550                        $var['location'] = Array(
3551                                'field' => $this->translate('Location'),
3552                                'data'  => $event['location']
3553                        );
3554
3555                        $var['startdate'] = Array(
3556                                'field' => $this->translate('Start Date/Time'),
3557                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset),
3558                        );
3559
3560                        $var['enddate'] = Array(
3561                                'field' => $this->translate('End Date/Time'),
3562                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset)
3563                        );
3564
3565                        $pri = Array(
3566                                1       => lang('Low'),
3567                                2       => lang('Normal'),
3568                                3       => lang('High')
3569                        );
3570                        $var['priority'] = Array(
3571                                'field' => lang('Priority'),
3572                                'data'  => $pri[$event['priority']]
3573                        );
3574
3575                        $var['owner'] = Array(
3576                                'field' => lang('Created By'),
3577                                'data'  => $GLOBALS['phpgw']->common->grab_owner_name($event['owner'])
3578                        );
3579
3580                        $var['updated'] = Array(
3581                                'field' => lang('Updated'),
3582                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['modtime']) - $GLOBALS['phpgw']->datetime->tz_offset)
3583                        );
3584
3585                        $var['access'] = Array(
3586                                'field' => lang('Access'),
3587                                'data'  => $event['public'] ? lang('Public') : lang('Private')
3588                        );
3589
3590                        if(@isset($event['groups'][0]))
3591                        {
3592                                $cal_grps = '';
3593                                for($i=0;$i<count($event['groups']);$i++)
3594                                {
3595                                        if($GLOBALS['phpgw']->accounts->exists($event['groups'][$i]))
3596                                        {
3597                                                $cal_grps .= ($i>0?'<br>':'').$GLOBALS['phpgw']->accounts->id2name($event['groups'][$i]);
3598                                        }
3599                                }
3600
3601                                $var['groups'] = Array(
3602                                        'field' => lang('Groups'),
3603                                        'data'  => $cal_grps
3604                                );
3605                        }
3606
3607                        $participants = array();
3608                        foreach($event['participants'] as $user => $short_status)
3609                        {
3610                                if($GLOBALS['phpgw']->accounts->exists($user))
3611                                {
3612                                        $participants[$user] = $GLOBALS['phpgw']->common->grab_owner_name($user).' ('.$this->get_long_status($short_status).')';
3613                                }
3614                        }
3615                        $var['participants'] = Array(
3616                                'field' => $this->translate('Participants'),
3617                                'data'  => $participants
3618                        );
3619
3620                        // Repeated Events
3621                        if($event['recur_type'] != MCAL_RECUR_NONE)
3622                        {
3623                                $str = lang($this->rpt_type[$event['recur_type']]);
3624
3625                                $str_extra = array();
3626                                if ($event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['month'] != 0 && $event['recur_enddate']['year'] != 0)
3627                                {
3628                                        $recur_end = $this->maketime($event['recur_enddate']);
3629                                        if($recur_end != 0)
3630                                        {
3631                                                $recur_end -= $GLOBALS['phpgw']->datetime->tz_offset;
3632                                                $str_extra[] = lang('ends').': '.lang($GLOBALS['phpgw']->common->show_date($recur_end,'l')).', '.$this->long_date($recur_end).' ';
3633                                        }
3634                                }
3635                                // only weekly uses the recur-data (days) !!!
3636                                if($event['recur_type'] == MCAL_RECUR_WEEKLY)
3637                                {
3638                                        $repeat_days = array();
3639                                        foreach ($this->rpt_day as $mcal_mask => $dayname)
3640                                        {
3641                                                if ($event['recur_data'] & $mcal_mask)
3642                                                {
3643                                                        $repeat_days[] = lang($dayname);
3644                                                }
3645                                        }
3646                                        if(count($repeat_days))
3647                                        {
3648                                                $str_extra[] = lang('days repeated').': '.implode(', ',$repeat_days);
3649                                        }
3650                                }
3651                                if($event['recur_interval'] != 0)
3652                                {
3653                                        $str_extra[] = lang('Interval').': '.$event['recur_interval'];
3654                                }
3655
3656                                if(count($str_extra))
3657                                {
3658                                        $str .= ' ('.implode(', ',$str_extra).')';
3659                                }
3660
3661                                $var['recure_type'] = Array(
3662                                        'field' => lang('Repetition'),
3663                                        'data'  => $str,
3664                                );
3665                        }
3666
3667                        if (!isset($this->fields))
3668                        {
3669                                $this->custom_fields = CreateObject('calendar.bocustom_fields');
3670                                $this->fields = &$this->custom_fields->fields;
3671                                $this->stock_fields = &$this->custom_fields->stock_fields;
3672                        }
3673                        foreach($this->fields as $field => $data)
3674                        {
3675                                if (!$data['disabled'])
3676                                {
3677                                        if (isset($var[$field]))
3678                                        {
3679                                                $sorted[$field] = $var[$field];
3680                                        }
3681                                        elseif (!isset($this->stock_fields[$field]) && strlen($event[$field]))  // Custom field
3682                                        {
3683                                                $lang = lang($name = substr($field,1));
3684                                                $sorted[$field] = array(
3685                                                        'field' => $lang == $name.'*' ? $name : $lang,
3686                                                        'data'  => $event[$field]
3687                                                );
3688                                        }
3689                                }
3690                                unset($var[$field]);
3691                        }
3692                        foreach($var as $name => $v)
3693                        {
3694                                $sorted[$name] = $v;
3695
3696                        }
3697                        return $sorted;
3698                }
3699
3700                /*!
3701                @function check_set_default_prefs
3702                @abstract sets the default prefs, if they are not already set (on a per pref. basis)
3703                @note It sets a flag in the app-session-data to be called only once per session
3704                */
3705                function check_set_default_prefs()
3706                {
3707                        if (($set = $GLOBALS['phpgw']->session->appsession('default_prefs_set','calendar')))
3708                        {
3709                                return;
3710                        }
3711                        $GLOBALS['phpgw']->session->appsession('default_prefs_set','calendar','set');
3712
3713                        //$default_prefs = $GLOBALS['phpgw']->preferences->default['calendar']; jakjr
3714
3715                        $subject = $this->translate('Calendar Event') . ' - $$action$$: $$startdate$$ $$title$$'."\n";
3716                        $defaults = array(
3717                                'defaultcalendar' => 'week',
3718                                'mainscreen_showevents' => '0',
3719                                'summary'         => 'no',
3720                                'receive_updates' => 'no',
3721                                'update_format'   => 'extended',        // leave it to extended for now, as iCal kills the message-body
3722                                'notifyAdded'     => $subject . $this->translate ('You have a meeting scheduled for %1',array('$$startdate$$')),
3723                                'notifyCanceled'  => $subject . $this->translate ('Your meeting scheduled for %1 has been canceled',array('$$startdate$$')),
3724                                'notifyModified'  => $subject . $this->translate ('Your meeting that had been scheduled for %1 has been rescheduled to %2',array('$$olddate$$','$$startdate$$')),
3725                                'notifyResponse'  => $subject . $this->translate ('On %1 %2 %3 your meeting request for %4', array('$$date$$','$$fullname$$','$$action$$','$$startdate$$')),
3726                                'notifyAlarm'     => $this->translate('Alarm for %1 at %2 in %3',array('$$title$$','$$startdate$$','$$location$$')) . "\n" . $this->translate('Here is your requested alarm.'),
3727                                'show_rejected'   => '0',
3728                                'hide_event_conflict'   => '0',
3729                                'display_status'  => '1',
3730                                'weekdaystarts'   => 'Monday',
3731                                'workdaystarts'   => '9',
3732                                'workdayends'     => '17',
3733                                'interval'        => '30',
3734                                'defaultlength'   => '60',
3735                                'planner_start_with_group' => $GLOBALS['phpgw']->accounts->name2id('Default'),
3736                                'planner_intervals_per_day'=> '4',
3737                                'defaultfilter'   => 'all',
3738                                'default_private' => '0',
3739                                'display_minicals'=> '1',
3740                                'print_black_white'=>'0'
3741                        );
3742                        foreach($defaults as $var => $default)
3743                        {
3744                                if (!isset($default_prefs[$var]) || $default_prefs[$var] == '')
3745                                {
3746                                        $GLOBALS['phpgw']->preferences->add('calendar',$var,$default,'default');
3747                                        $need_save = True;
3748                                }
3749                        }
3750                        if ($need_save)
3751                        {
3752                                $prefs = $GLOBALS['phpgw']->preferences->save_repository(False,'default');
3753                                $this->prefs['calendar'] = $prefs['calendar'];
3754                        }
3755                        if ($this->prefs['calendar']['send_updates'] && !isset($this->prefs['calendar']['receive_updates']))
3756                        {
3757                                $this->prefs['calendar']['receive_updates'] = $this->prefs['calendar']['send_updates'];
3758                                $GLOBALS['phpgw']->preferences->add('calendar','receive_updates',$this->prefs['calendar']['send_updates']);
3759                                $GLOBALS['phpgw']->preferences->delete('calendar','send_updates');
3760                                $prefs = $GLOBALS['phpgw']->preferences->save_repository();
3761                        }
3762                }
3763
3764                // return array with all infolog categories (for xmlrpc)
3765                function categories($complete = False)
3766                {
3767                        return $GLOBALS['server']->categories($complete);
3768                }
3769        }
3770?>
Note: See TracBrowser for help on using the repository browser.