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

Revision 583, 116.0 KB checked in by niltonneto, 15 years ago (diff)

Resolve #390.

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