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

Revision 1500, 118.5 KB checked in by eduardoalex, 15 years ago (diff)

Ticket #681 - Criada a função para delegar evento

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