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

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