source: branches/2.2/calendar/inc/class.bocalendar.inc.php @ 3419

Revision 3419, 122.2 KB checked in by brunocosta, 14 years ago (diff)

Ticket #1393 - Preferências padrão da agenda não são salvas.

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