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

Revision 313, 110.6 KB checked in by niltonneto, 16 years ago (diff)

Correção de bug, quando há repetição de compromisso, porém sem
o parametro frequencia. Gera muitos erros "division by zero"

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