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

Revision 766, 117.4 KB checked in by rafaelraymundo, 15 years ago (diff)

Adicionada implementacao de imprecao da revisao 596, com data inicial e quantidade de dias a partir dessa data.
Na comunidade ocorrencia http://www.expressolivre.org/dev/ticket/260

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