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

Revision 1576, 121.3 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #716 - Adicionado codigo de erro em common, alterado codigo de em bocalendar e adicionado lang da mensagem

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