source: branches/2.0/calendar/inc/class.bocalendar.inc.php @ 3195

Revision 3195, 116.7 KB checked in by wmerlotto, 14 years ago (diff)

Ticket #1179 - Compatibilização do agendamento para Outlook.

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