source: contrib/resources/inc/class.boresources.inc.php @ 3524

Revision 3524, 139.4 KB checked in by afernandes, 13 years ago (diff)

Ticket #1416 - Disponibilizado módulo de recursos para a comunidade

  • Property svn:executable set to *
Line 
1<?php
2  /**************************************************************************\
3  * eGroupWare - resources                                                    *
4  * http://www.eGroupWare.org                                                *
5  * Maintained and further developed by RalfBecker@outdoor-training.de       *
6  * Based on Webresources 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 boresources
18        {
19
20var $db;
21        /**
22         * resourcess config data
23         *
24         * @var array
25         */
26        var $config = array();
27
28
29        /**
30         * resourcess config data
31         *
32         * @var array
33         */
34        var $config_data = array();
35        /**
36         * Should we show a quantity sum, makes only sense if we sum up identical units (can be used to sum up negative (over-)time)
37         *
38         * @var boolean
39         */
40        var $quantity_sum=false;
41        /**
42         * Timestaps that need to be adjusted to user-time on reading or saving
43         *
44         * @var array
45         */
46        var $timestamps = array(
47                'ts_start','ts_modified'
48        );
49        /**
50         * Offset in secconds between user and server-time,     it need to be add to a server-time to get the user-time
51         * or substracted from a user-time to get the server-time
52         *
53         * @var int
54         */
55        var $tz_offset_s;
56        /**
57         * Current time as timestamp in user-time
58         *
59         * @var int
60         */
61        var $now;
62        /**
63         * Start of today in user-time
64         *
65         * @var int
66         */
67        var $today;
68        /**
69         * Filter for search limiting the date-range
70         *
71         * @var array
72         */
73        var $date_filters = array(      // Start: year,month,day,week, End: year,month,day,week
74                'Today'       => array(0,0,0,0,  0,0,1,0),
75                'Yesterday'   => array(0,0,-1,0, 0,0,0,0),
76                'This week'   => array(0,0,0,0,  0,0,0,1),
77                'Last week'   => array(0,0,0,-1, 0,0,0,0),
78                'This month'  => array(0,0,0,0,  0,1,0,0),
79                'Last month'  => array(0,-1,0,0, 0,0,0,0),
80                '2 month ago' => array(0,-2,0,0, 0,-1,0,0),
81                'This year'   => array(0,0,0,0,  1,0,0,0),
82                'Last year'   => array(-1,0,0,0, 0,0,0,0),
83                '2 years ago' => array(-2,0,0,0, -1,0,0,0),
84                '3 years ago' => array(-3,0,0,0, -2,0,0,0),
85        );
86        /**
87         * Reference to the (bo)link class instanciated at $GLOBALS['phpgw']->link
88         *
89         * @var bolink
90         */
91        var $link;
92        /**
93         * Grants: $GLOBALS['phpgw']->acl->get_grants(resources_APP);
94         *
95         * @var array
96         */     
97        var $grants;
98        /**
99         * Sums of the last search in keys duration and price
100         *
101         * @var array
102         */
103        var $summary;
104        /**
105         * Array with boolean values in keys 'day', 'week' or 'month', for the sums to return in the search
106         *
107         * @var array
108         */
109        var $show_sums;
110
111        var $customfields=array();
112
113                function boresources($session=0)
114                {
115
116                        if(!is_object($GLOBALS['phpgw']->datetime))
117                        {
118                                $GLOBALS['phpgw']->datetime = createobject('phpgwapi.date_time');
119                        }
120
121                        $this->cat = CreateObject('phpgwapi.categories');
122
123$this->resources = CreateObject('phpgwapi.resources');
124
125$this->tarea = CreateObject('phpgwapi.project');
126
127$this->project = CreateObject('phpgwapi.project');
128
129
130
131
132$this->config_data =& $this->config->config_data;
133               
134
135
136if (isset($this->config_data['customfields']) && is_array($this->config_data['customfields']))
137                {
138                        $this->customfields = $this->config_data['customfields'];
139                }
140
141                if (!is_object($GLOBALS['phpgw']->datetime))
142                {
143                        $GLOBALS['phpgw']->datetime =& CreateObject('phpgwapi.datetime');
144                }
145                $this->tz_offset_s = $GLOBALS['phpgw']->datetime->tz_offset;
146                $this->now = time() + $this->tz_offset_s;       // time() is server-time and we need a user-time
147                $this->today = mktime(0,0,0,date('m',$this->now),date('d',$this->now),date('Y',$this->now));
148
149       
150
151
152                        $this->grants = $GLOBALS['phpgw']->acl->get_grants('resources');
153                        @reset($this->grants);
154                        if(DEBUG_APP)
155                        {
156                                if(floor(phpversion()) >= 4)
157                                {
158                                        $this->debug_string = '';
159                                        ob_start();
160                                }
161
162                                foreach($this->grants as $grantor => $rights)
163                                {
164                                        print_debug('Grantor',$grantor);
165                                        print_debug('Rights',$rights);
166                                }
167                        }
168
169                        print_debug('Read use_session',$session);
170
171                        if($session)
172                        {
173                                $this->read_sessiondata();
174                                $this->use_session = True;
175                        }
176                        print_debug('BO Filter',$this->filter);
177                        print_debug('Owner',$this->owner);
178
179                        if ($GLOBALS['argv']) {
180                          $this->async = true;
181                          $this->load_lang();
182                        }
183
184                        $this->prefs['resources']    = $GLOBALS['phpgw_info']['user']['preferences']['resources'];
185                        $this->check_set_default_prefs();
186
187                        $owner = get_var('owner',array('GET','POST'),$GLOBALS['owner']);
188
189                        ereg('menuaction=([a-zA-Z.]+)',$_SERVER['HTTP_REFERER'],$regs);
190                        $from = $regs[1];
191                        if ((substr($_SERVER['PHP_SELF'],-8) == 'home.php' && substr($this->prefs['resources']['defaultresources'],0,7) == 'planner'
192                                || $_GET['menuaction'] == 'resources.uiresources.planner' &&
193                                $from  != 'resources.uiresources.planner' && !$this->save_owner)
194                                && (int)$this->prefs['resources']['planner_start_with_group'] > 0)
195                        {
196                                // entering planner for the first time ==> saving owner in save_owner, setting owner to default
197                                //
198                                $this->save_owner = $this->owner;
199                                $owner = 'g_'.$this->prefs['resources']['planner_start_with_group'];
200                        }
201                        elseif ($_GET['menuaction'] != 'resources.uiresources.planner' &&
202                                $this->save_owner)
203                        {
204                                // leaving planner with an unchanged user/owner ==> setting owner back to save_owner
205                                //
206                                $owner = (int)(isset($_GET['owner']) ? $_GET['owner'] : $this->save_owner);
207                                unset($this->save_owner);
208                        }
209                        elseif (!empty($owner) && $owner != $this->owner && $from == 'resources.uiresources.planner')
210                        {
211                                // user/owner changed within planner ==> forgetting save_owner
212                                //
213                                unset($this->save_owner);
214                        }
215
216                        if(isset($owner) && $owner!='' && substr($owner,0,2) == 'g_')
217                        {
218                                $this->set_owner_to_group(substr($owner,2));
219                        }
220                        elseif(isset($owner) && $owner!='')
221                        {
222                                $this->owner = (int)$owner;
223                        }
224                        elseif(!@isset($this->owner) || !@$this->owner)
225                        {
226                                $this->owner = (int)$GLOBALS['phpgw_info']['user']['account_id'];
227                        }
228                        elseif(isset($this->owner) && $GLOBALS['phpgw']->accounts->get_type($this->owner) == 'g')
229                        {
230                                $this->set_owner_to_group((int)$this->owner);
231                        }
232
233                        $this->prefs['common']    = $GLOBALS['phpgw_info']['user']['preferences']['common'];
234
235                        if ($this->prefs['common']['timeformat'] == '12')
236                        {
237                                $this->users_timeformat = 'h:ia';
238                        }
239                        else
240                        {
241                                $this->users_timeformat = 'H:i';
242                        }
243                        $this->holiday_color = (substr($GLOBALS['phpgw_info']['theme']['bg07'],0,1)=='#'?'':'#').$GLOBALS['phpgw_info']['theme']['bg07'];
244
245                        $friendly = (isset($_GET['friendly'])?$_GET['friendly']:'');
246                        $friendly = ($friendly=='' && isset($_POST['friendly'])?$_POST['friendly']:$friendly);
247
248                        $this->printer_friendly = ((int)$friendly == 1?True:False);
249
250                        if(isset($_POST['filter'])) { $this->filter = $_POST['filter']; }
251                        if(isset($_POST['sortby'])) { $this->sortby = $_POST['sortby']; }
252                        if(isset($_POST['cat_id'])) { $this->cat_id = $_POST['cat_id']; }
253
254                        if(!isset($this->filter))
255                        {
256                                $this->filter = ' '.$this->prefs['resources']['defaultfilter'].' ';
257                        }
258
259                        if(!isset($this->sortby))
260                        {
261                                $this->sortby = $this->prefs['resources']['defaultresources'] == 'planner_user' ? 'user' : 'category';
262                        }
263
264                        if($GLOBALS['phpgw']->accounts->get_type($this->owner)=='g')
265                        {
266                                $this->filter = ' all ';
267                        }
268
269                        /*$this->so = CreateObject('resources.soresources',
270                                Array(
271                                        'owner'         => $this->owner,
272                                        'filter'        => $this->filter,
273                                        'category'      => $this->cat_id,
274                                        'g_owner'       => $this->g_owner
275                                )
276                        );*/
277                        $this->rpt_day = array( // need to be after creation of soresources
278                                MCAL_M_SUNDAY    => 'Sunday',
279                                MCAL_M_MONDAY    => 'Monday',
280                                MCAL_M_TUESDAY   => 'Tuesday',
281                                MCAL_M_WEDNESDAY => 'Wednesday',
282                                MCAL_M_THURSDAY  => 'Thursday',
283                                MCAL_M_FRIDAY    => 'Friday',
284                                MCAL_M_SATURDAY  => 'Saturday'
285                        );
286                        if($this->bo->prefs['resources']['weekdaystarts'] != 'Sunday')
287                        {
288                                $mcals = array_keys($this->rpt_day);
289                                $days  = array_values($this->rpt_day);
290                                $this->rpt_day = array();
291                                list($n) = $found = array_keys($days,$this->prefs['resources']['weekdaystarts']);
292                                for ($i = 0; $i < 7; ++$i,++$n)
293                                {
294                                        $this->rpt_day[$mcals[$n % 7]] = $days[$n % 7];
295                                }
296                        }
297                        $this->rpt_type = Array(
298                                MCAL_RECUR_NONE         => 'None',
299                                MCAL_RECUR_DAILY        => 'Daily',
300                                MCAL_RECUR_WEEKLY       => 'Weekly',
301                                MCAL_RECUR_MONTHLY_WDAY => 'Monthly (by day)',
302                                MCAL_RECUR_MONTHLY_MDAY => 'Monthly (by date)',
303                                MCAL_RECUR_YEARLY       => 'Yearly'
304                        );
305
306                        $localtime = $GLOBALS['phpgw']->datetime->users_localtime;
307
308                        $date = (isset($GLOBALS['date'])?$GLOBALS['date']:'');
309                        $date = (isset($_GET['date'])?$_GET['date']:$date);
310                        $date = ($date=='' && isset($_POST['date'])?$_POST['date']:$date);
311
312                        $year = (isset($_GET['year'])?$_GET['year']:'');
313                        $year = ($year=='' && isset($_POST['year'])?$_POST['year']:$year);
314
315                        $month = (isset($_GET['month'])?$_GET['month']:'');
316                        $month = ($month=='' && isset($_POST['month'])?$_POST['month']:$month);
317
318                        $day = (isset($_GET['day'])?$_GET['day']:'');
319                        $day = ($day=='' && isset($_POST['day'])?$_POST['day']:'');
320
321                        $num_months = (isset($_GET['num_months'])?$_GET['num_months']:'');
322                        $num_months = ($num_months=='' && isset($_POST['num_months'])?$_POST['num_months']:$num_months);
323
324                        if(isset($date) && $date!='')
325                        {
326                                $this->year  = (int)(substr($date,0,4));
327                                $this->month = (int)(substr($date,4,2));
328                                $this->day   = (int)(substr($date,6,2));
329                        }
330                        else
331                        {
332                                if(isset($year) && $year!='')
333                                {
334                                        $this->year = $year;
335                                }
336                                else
337                                {
338                                        $this->year = date('Y',$localtime);
339                                }
340                                if(isset($month) && $month!='')
341                                {
342                                        $this->month = $month;
343                                }
344                                else
345                                {
346                                        $this->month = date('m',$localtime);
347                                }
348                                if(isset($day) && $day!='')
349                                {
350                                        $this->day = $day;
351                                }
352                                else
353                                {
354                                        $this->day = date('d',$localtime);
355                                }
356                        }
357
358                        if(isset($num_months) && $num_months!='')
359                        {
360                                $this->num_months = $num_months;
361                        }
362                        elseif($this->num_months == 0)
363                        {
364                                $this->num_months = 1;
365                        }
366
367                        $this->today = date('Ymd',$GLOBALS['phpgw']->datetime->users_localtime);
368
369                        if(DEBUG_APP)
370                        {
371                                print_debug('BO Filter','('.$this->filter.')');
372                                print_debug('Owner',$this->owner);
373                                print_debug('Today',$this->today);
374                                if(floor(phpversion()) >= 4)
375                                {
376                                        $this->debug_string .= ob_get_contents();
377                                        ob_end_clean();
378                                }
379                        }
380
381$evento=$this->restore_from_appsession();
382                        $this->xmlrpc = is_object($GLOBALS['server']) && $GLOBALS['server']->last_method;
383                }
384
385          function load_lang() {
386            if(!$_SESSION['phpgw_info']['resources']['langAlarm'])
387              {
388                $array_keys = array();
389                $fn = '../../resources/setup/phpgw_alarm_'.$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'].'.lang';                     
390                echo $fn;
391                if (file_exists($fn)){
392                  $fp = fopen($fn,'r');
393                  while ($data = fgets($fp,16000))      {
394                    list($message_id,$app_name,$null,$content) = explode("\t",substr($data,0,-1));                     
395                    $_SESSION['phpgw_info']['resources']['langAlarm'][$message_id] =  $content;
396                  }
397                  fclose($fp);
398                }
399              }
400          }
401                function list_methods($_type='xmlrpc')
402                {
403                        /*
404                          This handles introspection or discovery by the logged in client,
405                          in which case the input might be an array.  The server always calls
406                          this function to fill the server dispatch map using a string.
407                        */
408                        if (is_array($_type))
409                        {
410                                $_type = $_type['type'];
411                        }
412                        switch($_type)
413                        {
414                                case 'xmlrpc':
415                                        $xml_functions = array(
416                                                'list_methods' => array(
417                                                        'function'  => 'list_methods',
418                                                        'signature' => array(array(xmlrpcStruct,xmlrpcString)),
419                                                        'docstring' => lang('Read this list of methods.')
420                                                ),
421                                                'read' => array(
422                                                        'function'  => 'read_entry',
423                                                        'signature' => array(array(xmlrpcStruct,xmlrpcInt)),
424                                                        'docstring' => lang('Read a single entry by passing the id and fieldlist.')
425                                                ),
426                                                'read_entry' => array(  // deprecated, use read
427                                                        'function'  => 'read_entry',
428                                                        'signature' => array(array(xmlrpcStruct,xmlrpcInt)),
429                                                        'docstring' => lang('Read a single entry by passing the id and fieldlist.')
430                                                ),
431                                                'write' => array(
432                                                        'function'  => 'update',
433                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
434                                                        'docstring' => lang('Add or update a single entry by passing the fields.')
435                                                ),
436                                                'add_entry' => array(   // deprecated, use write
437                                                        'function'  => 'update',
438                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
439                                                        'docstring' => lang('Add a single entry by passing the fields.')
440                                                ),
441                                                'update_entry' => array(        // deprecated, use write
442                                                        'function'  => 'update',
443                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
444                                                        'docstring' => lang('Update a single entry by passing the fields.')
445                                                ),
446                                                'delete' => array(
447                                                        'function'  => 'delete_entry',
448                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
449                                                        'docstring' => lang('Delete a single entry by passing the id.')
450                                                ),
451                                                'delete_entry' => array(        // deprecated, use delete
452                                                        'function'  => 'delete_entry',
453                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
454                                                        'docstring' => lang('Delete a single entry by passing the id.')
455                                                ),
456                                                'delete_resources' => array(
457                                                        'function'  => 'delete_resources',
458                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
459                                                        'docstring' => lang('Delete an entire users resources.')
460                                                ),
461                                                'change_owner' => array(
462                                                        'function'  => 'change_owner',
463                                                        'signature' => array(array(xmlrpcInt,xmlrpcStruct)),
464                                                        'docstring' => lang('Change all events for $params[\'old_owner\'] to $params[\'new_owner\'].')
465                                                ),
466                                                'search' => array(
467                                                        'function'  => 'store_to_cache',
468                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
469                                                        'docstring' => lang('Read a list of entries.')
470                                                ),
471                                                'store_to_cache' => array(      // deprecated, use search
472                                                        'function'  => 'store_to_cache',
473                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
474                                                        'docstring' => lang('Read a list of entries.')
475                                                ),
476                                                'export_event' => array(
477                                                        'function'  => 'export_event',
478                                                        'signature' => array(array(xmlrpcString,xmlrpcStruct)),
479                                                        'docstring' => lang('Export a list of entries in iCal format.')
480                                                ),
481                                                'categories' => array(
482                                                        'function'  => 'categories',
483                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
484                                                        'docstring' => lang('List all categories.')
485                                                ),
486                                        );
487                                        return $xml_functions;
488                                        break;
489                                case 'soap':
490                                        return $this->soap_functions;
491                                        break;
492                                default:
493                                        return array();
494                                        break;
495                        }
496                }
497
498                function set_owner_to_group($owner)
499                {
500                        print_debug('resources::boresources::set_owner_to_group:owner',$owner);
501                        $this->owner = (int)$owner;
502                        $this->is_group = True;
503                        $this->g_owner = Array();
504                        $members = $GLOBALS['phpgw']->accounts->member($owner);
505                        if (is_array($members))
506                        {
507                                foreach($members as $user)
508                                {
509                                        // use only members which gave the user a read-grant
510                                        if ($this->check_perms(PHPGW_ACL_READ,0,$user['account_id']))
511                                        {
512                                                $this->g_owner[] = $user['account_id'];
513                                        }
514                                }
515                        }
516                        //echo "<p>".function_backtrace().": set_owner_to_group($owner) = ".print_r($this->g_owner,True)."</p>\n";
517                }
518
519                function member_of_group($owner=0)
520                {
521                        $owner = ($owner==0?$GLOBALS['phpgw_info']['user']['account_id']:$owner);
522                        $group_owners = $GLOBALS['phpgw']->accounts->membership();
523                        while($group_owners && list($index,$group_info) = each($group_owners))
524                        {
525                                if($this->owner == $group_info['account_id'])
526                                {
527                                        return True;
528                                }
529                        }
530                        return False;
531                }
532
533                function save_sessiondata($data='')
534                {
535                        if ($this->use_session)
536                        {
537                                if (!is_array($data))
538                                {
539                                        $data = array(
540                                                'filter'     => $this->filter,
541                                                'cat_id'     => $this->cat_id,
542                                                'owner'      => $this->owner,
543                                                'save_owner' => $this->save_owner,
544                                                'year'       => $this->year,
545                                                'month'      => $this->month,
546                                                'day'        => $this->day,
547                                                'date'       => $this->date,
548                                                'sortby'     => $this->sortby,
549                                                'num_months' => $this->num_months,
550                                                'return_to'  => $this->return_to
551                                        );
552                                }
553                                if($this->debug)
554                                {
555                                        if(floor(phpversion()) >= 4)
556                                        {
557                                                ob_start();
558                                        }
559                                        echo '<!-- '."\n".'Save:'."\n"._debug_array($data,False)."\n".' -->'."\n";
560                                        if(floor(phpversion()) >= 4)
561                                        {
562                                                $this->debug_string .= ob_get_contents();
563                                                ob_end_clean();
564                                        }
565                                }
566                                $GLOBALS['phpgw']->session->appsession('session_data','resources',$data);
567                        }
568                }
569
570                function read_sessiondata()
571                {
572                        $data = $GLOBALS['phpgw']->session->appsession('session_data','resources');
573                        print_debug('Read',_debug_array($data,False));
574
575                        $this->filter = $data['filter'];
576                        $this->cat_id = $data['cat_id'];
577                        $this->sortby = $data['sortby'];
578                        $this->owner  = (int)$data['owner'];
579                        $this->save_owner = (int)$data['save_owner'];
580                        $this->year   = (int)$data['year'];
581                        $this->month  = (int)$data['month'];
582                        $this->day    = (int)$data['day'];
583                        $this->num_months = (int)$data['num_months'];
584                        $this->return_to = $data['return_to'];
585                }
586
587                function read_entry()
588                {
589
590                        $event = $this->so->read_entry($id);
591                                echo $event;
592                       
593                       
594                        return False;
595                }
596
597                function delete_single($param)
598                {
599                        if($this->check_perms(PHPGW_ACL_DELETE,(int)$param['id']))
600                        {
601                                $temp_event = $this->get_cached_event();
602                                $event = $this->read_entry((int)$param['id']);
603//                              if($this->owner == $event['owner'])
604//                              {
605                                $exception_time = mktime($event['start']['hour'],$event['start']['min'],0,$param['month'],$param['day'],$param['year']) - $GLOBALS['phpgw']->datetime->tz_offset;
606                                $event['recur_exception'][] = (int)$exception_time;
607                                $this->so->cal->event = $event;
608//                              print_debug('exception time',$event['recur_exception'][count($event['recur_exception']) -1]);
609//                              print_debug('count event exceptions',count($event['recur_exception']));
610                                $this->so->add_entry($event);
611                                $cd = 16;
612
613                                $this->so->cal->event = $temp_event;
614                                unset($temp_event);
615                        }
616                        else
617                        {
618                                $cd = 60;
619                        }
620//                      }
621                        return $cd;
622                }
623
624                function delete_entry($id)
625                {
626                        if (is_array($id) && count($id) == 1)
627                        {
628                                list(,$id) = each($id);
629                        }
630                        if($this->check_perms(PHPGW_ACL_DELETE,$id))
631                        {
632                                $this->so->delete_entry($id);
633
634                                if ($this->xmlrpc)
635                                {
636                                        $this->so->expunge($id);
637                                }
638                                return $this->xmlrpc ? True : 16;
639                        }
640                        if ($this->xmlrpc)
641                        {
642                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
643                        }
644                        return 60;
645                }
646
647                function reinstate($params='')
648                {
649                        if($this->check_perms(PHPGW_ACL_EDIT,$params['cal_id']) && isset($params['reinstate_index']))
650                        {
651                                $event = $this->so->read_entry($params['cal_id']);
652                                @reset($params['reinstate_index']);
653                                print_debug('Count of reinstate_index',count($params['reinstate_index']));
654                                if(count($params['reinstate_index']) > 1)
655                                {
656                                        while(list($key,$value) = each($params['reinstate_index']))
657                                        {
658                                                print_debug('reinstate_index ['.$key.']',(int)$value);
659                                                print_debug('exception time',$event['recur_exception'][(int)$value]);
660                                                unset($event['recur_exception'][(int)$value]);
661                                                print_debug('count event exceptions',count($event['recur_exception']));
662                                        }
663                                }
664                                else
665                                {
666                                        print_debug('reinstate_index[0]',(int)$params['reinstate_index'][0]);
667                                        print_debug('exception time',$event['recur_exception'][(int)$params['reinstate_index'][0]]);
668                                        unset($event['recur_exception'][(int)$params['reinstate_index'][0]]);
669                                        print_debug('count event exceptions',count($event['recur_exception']));
670                                }
671                                $this->so->cal->event = $event;
672                                $this->so->add_entry($event);
673                                return 42;
674                        }
675                        else
676                        {
677                                return 43;
678                        }
679                }
680
681                function delete_resources($owner)
682                {
683                        if($GLOBALS['phpgw_info']['user']['apps']['admin'])
684                        {
685                                $this->so->delete_resources($owner);
686                        }
687                }
688
689                function change_owner($params='')
690                {
691                        if($GLOBALS['phpgw_info']['server']['resources_type'] == 'sql')
692                        {
693                                if(is_array($params))
694                                {
695                                        $this->so->change_owner($params['old_owner'],$params['new_owner']);
696                                }
697                        }
698                }
699
700                function expunge()
701                {
702                        reset($this->so->cal->deleted_events);
703                        while(list($i,$event_id) = each($this->so->cal->deleted_events))
704                        {
705                                $event = $this->so->read_entry($event_id);
706                                if(!$this->ex_participants)
707                                        $this->ex_participants = html_entity_decode($event['ex_participants']);                 
708                                if($this->check_perms(PHPGW_ACL_DELETE,$event))
709                                {
710                                        $this->send_update(MSG_DELETED,$event['participants'],$event);
711                                }
712                                else
713                                {
714                                        unset($this->so->cal->deleted_events[$i]);
715                                }
716                        }
717                        $this->so->expunge();
718                }
719
720                function search_keywords($keywords)
721                {
722                        $type = $GLOBALS['phpgw']->accounts->get_type($this->owner);
723
724                        if($type == 'g')
725                        {
726                                $members = $GLOBALS['phpgw']->acl->get_ids_for_location($this->owner, 1, 'phpgw_group');
727                        }
728                        else
729                        {
730                                $members = array_keys($this->grants);
731
732                                if (!in_array($this->owner,$members))
733                                {
734                                        $members[] = $this->owner;
735                                }
736                        }
737                        foreach($members as $n => $uid)
738                        {
739                                if (!($this->grants[$uid] & PHPGW_ACL_READ))
740                                {
741                                        unset($members[$n]);
742                                }
743                        }
744
745
746                        return $this->so->list_events_keyword($keywords,$members);
747                }
748
749                function update($params='')
750                {
751
752                        if($params['from_mobile']) {
753                                $ui_return = "mobile.ui_mobileresources.edit";
754                                $ui_index = "mobile.ui_mobileresources.index";
755                                $ui_overlap = "mobile.ui_mobileresources.overlap";
756                        }
757                        else {
758                                $ui_return = "resources.uiresources.edit";
759                                $ui_index = "resources.uiresources.index";             
760                                $ui_overlap = "resources.uiresources.overlap";
761                        }
762
763                        if(!is_object($GLOBALS['phpgw']->datetime))
764                        {
765                                $GLOBALS['phpgw']->datetime = createobject('phpgwapi.date_time');
766                        }
767                        $l_cal = (@isset($params['info_type']) && $params['info_type']?$params['info_type']:$_POST['info_type']);
768                        $l_participants = (@$params['participants']?$params['participants']:$_POST['participants']);
769                        $this->ex_participants = (@$params['ex_participants']?$params['ex_participants']:$_POST['ex_participants']);
770                        $l_categories = (@$params['categories']?$params['categories']:$_POST['categories']);
771                        $l_start = (@isset($params['start']) && $params['start']?$params['start']:$_POST['start']);
772                        $l_end = (@isset($params['end']) && $params['end']?$params['end']:$_POST['end']);
773                        $l_recur_enddate = (@isset($params['recur_enddate']) && $params['recur_enddate']?$params['recur_enddate']:$_POST['recur_enddate']);
774
775                       
776                        $send_to_ui = True;
777                        //if ((!is_array($l_start) || !is_array($l_end)) && !isset($_GET['readsess']))  // xmlrpc call
778                        if ($this->xmlrpc)      // xmlrpc call
779                        {
780
781                                $send_to_ui = False;
782
783                                $l_cal = $params;       // no extra array
784
785                                foreach(array('start','end','recur_enddate') as $name)
786                                {
787                                        $var = 'l_'.$name;
788                                        $$var = $GLOBALS['server']->iso86012date($params[$name]);
789                                        unset($l_cal[$name]);
790                                }
791
792                                if (!is_array($l_participants) || !count($l_participants))
793                                {
794                                        $l_participants = array($GLOBALS['phpgw_info']['user']['account_id'].'A');
795                                }
796                                else
797                                {
798                                        $l_participants = array();
799                                        foreach($params['participants'] as $user => $data)
800                                        {
801                                                $l_participants[] = $user.$data['status'];
802                                        }
803                                }
804
805                                unset($l_cal['participants']);
806
807                                if (!is_object($GLOBALS['phpgw']->categories))
808                                {
809                                        $GLOBALS['phpgw']->categories = CreateObject('phpgwapi.categories');
810                                }
811
812                                $l_categories = $GLOBALS['server']->xmlrpc2cats($params['category']);
813                                unset($l_cal['category']);
814
815                                // using access={public|private} in all modules via xmlrpc
816                                $l_cal['public'] = $params['access'] != 'private';
817                                unset($l_cal['access']);
818/*
819                                $fp = fopen('/tmp/xmlrpc.log','a+');
820                                ob_start();
821                                echo "\nboresources::update("; print_r($params); echo ")\n";
822                                //echo "\nl_start="; print_r($l_start);
823                                //echo "\nl_end="; print_r($l_end);
824                                fwrite($fp,ob_get_contents());
825                                ob_end_clean();
826                                fclose($fp);
827*/
828                        }
829
830                        print_debug('ID',$l_cal['id']);
831
832                        // don't wrap to the next day for no time
833                        if ($l_end['hour'] == 24 && $l_end['min'] == 0)
834                        {
835                                $l_end['hour'] = 23;
836                                $l_end['min'] = 59;
837                        }
838
839                        if(isset($_GET['readsess']))
840                        {
841
842                                $event = $this->restore_from_appsession();
843                                $event['title'] = stripslashes($event['title']);
844                                $event['description'] = stripslashes($event['description']);
845$event['description1'] = stripslashes($event['description1']);
846$event['participants1'] = stripslashes($event['participants1']);
847                                $event['ex_participants'] = stripslashes($event['ex_participants']);
848                                $datetime_check = $this->validate_update($event);
849                                if($datetime_check)
850                                {
851                                        ExecMethod($ui_return,
852                                                Array(
853                                                        'cd'            => $datetime_check,
854                                                        'readsess'      => 1
855                                                )
856                                        );
857                                        if(!$params['from_mobile'])
858                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
859                                        else
860                                                return;
861                                }
862                                $overlapping_events = False;
863                        }
864                        else
865                        {
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
871                                        if ($this->xmlrpc)
872                                        {
873                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
874                                        }
875                                        if (!$send_to_ui)
876                                        {
877                                                return array(($l_cal['id']?1:2) => 'permission denied');
878                                        }
879
880                                        ExecMethod($ui_index);
881
882
883                                        if(!$params['from_mobile'])
884                                                $GLOBALS['phpgw']->common->phpgw_exit();
885                                        else
886                                                return;
887                                }
888
889                                print_debug('Prior to fix_update_time()');
890
891                                $this->fix_update_time($l_start);
892
893                                $this->fix_update_time($l_end);
894
895                                if(!isset($l_cal['ex_participants']))
896                                {
897                                        $l_cal['ex_participants'] = $this->ex_participants;
898                                }
899
900                                if(!isset($l_categories))
901                                {
902                                        $l_categories = 0;
903                                }
904
905                                $is_public = ($l_cal['type'] != 'private' && $l_cal['type'] != 'privateHiddenFields');
906
907                                //$this->so->event_init();
908
909                        $this->add_attribute('uid',$l_cal['uid']);
910
911                                $this->add_attribute('type',$l_cal['type']);
912
913                                if($l_cal['ex_participants']) {
914                                        $this->add_attribute('ex_participants',$l_cal['ex_participants']);
915                                }
916                                /*if(count($l_categories) >= 2)
917                                {
918                                        $this->so->set_category(implode(',',$l_categories));
919                                }
920                                else
921                                {
922                                        $this->so->set_category(strval($l_categories[0]));
923                                }
924                                $this->so->set_title($l_cal['title']);
925                                $this->so->set_description($l_cal['description']);
926$this->so->set_description1($l_cal['description1']);
927$this->so->set_participants1($l_cal['participants1']);
928                                $this->so->set_ex_participants($l_cal['ex_participants']);
929                                $this->so->set_start($l_start['year'],$l_start['month'],$l_start['mday'],$l_start['hour'],$l_start['min'],0);
930                                $this->so->set_end($l_end['year'],$l_end['month'],$l_end['mday'],$l_end['hour'],$l_end['min'],0);
931                                $this->so->set_class($is_public);
932                                $this->so->add_attribute('reference',(@isset($l_cal['reference']) && $l_cal['reference']?$l_cal['reference']:0));
933                                $this->so->add_attribute('location',(@isset($l_cal['location']) && $l_cal['location']?$l_cal['location']:''));*/
934                                if($l_cal['id'])
935                                {
936                                        //$this->so->add_attribute('id',$l_cal['id']);
937                                }
938
939                                if($l_cal['rpt_use_end'] != 'y')
940                                {
941                                        $l_recur_enddate['year'] = 0;
942                                        $l_recur_enddate['month'] = 0;
943                                        $l_recur_enddate['mday'] = 0;
944                                }
945                                elseif (isset($l_recur_enddate['str']))
946                                {
947                                        $l_recur_enddate = $this->jscal->input2date($l_recur_enddate['str'],False,'mday');
948                                }
949
950                                switch((int)$l_cal['recur_type'])
951                                {
952
953
954                                        case MCAL_RECUR_NONE:
955                                                //$this->so->set_recur_none();
956
957                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
958
959                                                break;
960                                        case MCAL_RECUR_DAILY:
961                                                //$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']);
962
963                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
964
965                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
966                                                $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;
967
968                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
969                                                {
970
971                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
972                                                        $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;
973
974                                                }else { // se nao existe data final da repeticao (agendamento infinito):
975
976                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
977                                                }
978                                                break;
979                                        case MCAL_RECUR_WEEKLY:
980
981                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
982
983                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
984                                                $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;
985
986                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
987                                                {
988
989                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
990                                                        $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;
991
992                                                }else { // se nao existe data final da repeticao (agendamento infinito):
993
994                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
995                                                }
996
997                                                foreach(array('rpt_sun','rpt_mon','rpt_tue','rpt_wed','rpt_thu','rpt_fri','rpt_sat') as $rpt_day)
998                                                {
999                                                        $l_cal['recur_data'] += (int)$l_cal[$rpt_day];
1000                                                }
1001                                                if (is_array($l_cal['rpt_day']))
1002                                                {
1003                                                        foreach ($l_cal['rpt_day'] as $mask)
1004                                                        {
1005                                                                $l_cal['recur_data'] |= (int)$mask;
1006                                                                $rpt_wdays = $l_cal['recur_data']; // recebe os dias da semana (somatorio) para repetir o alarme;
1007                                                        }
1008                                                }
1009                                                //$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']);
1010                                                break;
1011                                        case MCAL_RECUR_MONTHLY_MDAY:
1012                                                //$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']);
1013
1014                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1015
1016                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
1017                                                $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;
1018
1019                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
1020                                                {
1021
1022                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
1023                                                        $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;
1024
1025                                                }else { // se nao existe data final da repeticao (agendamento infinito):
1026
1027                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1028                                                }
1029                                                break;
1030                                        case MCAL_RECUR_MONTHLY_WDAY:
1031                                                //$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']);
1032                                                break;
1033                                        case MCAL_RECUR_YEARLY:
1034                                                //$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']);
1035
1036                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1037
1038                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
1039                                                $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;
1040
1041                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
1042                                                {
1043
1044                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
1045                                                        $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;
1046
1047                                                }else { // se nao existe data final da repeticao (agendamento infinito):
1048
1049                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1050                                                }
1051                                                break;
1052                                }
1053
1054                                if($l_participants)
1055                                {
1056                                        $parts = $l_participants;
1057                                        $minparts = min($l_participants);
1058                                        $part = Array();
1059                                        for($i=0;$i<count($parts);$i++)
1060                                        {
1061                                                if (($accept_type = substr($parts[$i],-1,1)) == '0' || (int)$accept_type > 0)
1062                                                {
1063                                                        $accept_type = 'U';
1064                                                }
1065                                                $acct_type = $GLOBALS['phpgw']->accounts->get_type((int)$parts[$i]);
1066                                                if($acct_type == 'u')
1067                                                {
1068                                                        $part[(int)$parts[$i]] = $accept_type;
1069                                                }
1070                                                elseif($acct_type == 'g')
1071                                                {
1072                                                        $part[(int)$parts[$i]] = $accept_type;
1073                                                        $groups[] = $parts[$i];
1074                                                        /* This pulls ALL users of a group and makes them as participants to the event */
1075                                                        /* I would like to turn this back into a group thing. */
1076                                                        $acct = CreateObject('phpgwapi.accounts',(int)$parts[$i]);
1077                                                        $members = $acct->member((int)$parts[$i]);
1078                                                        unset($acct);
1079                                                        if($members == False)
1080                                                        {
1081                                                                continue;
1082                                                        }
1083                                                        while($member = each($members))
1084                                                        {
1085                                                                $part[$member[1]['account_id']] = $accept_type;
1086                                                        }
1087                                                }
1088                                        }
1089                                }
1090                                else
1091                                {
1092                                        $part = False;
1093                                }
1094
1095                                if($part)
1096                                {
1097                                        @reset($part);
1098                                        while(list($key,$accept_type) = each($part))
1099                                        {
1100echo "";
1101                                                //$this->so->add_attribute('participants',$accept_type,(int)$key);
1102                                        }
1103                                }
1104
1105                                if($groups)
1106                                {
1107                                        @reset($groups);
1108                                        //$this->so->add_attribute('groups',(int)$group_id);
1109                                }
1110
1111                                $event = $this->get_cached_event();
1112                                if(!is_int($minparts))
1113                                {
1114                                        $minparts = $this->owner;
1115                                }
1116                                if(!@isset($event['participants'][$l_cal['owner']]))
1117                                {
1118                                        //$this->so->add_attribute('owner',$minparts);
1119                                }
1120                                else
1121                                {
1122                                        //$this->so->add_attribute('owner',$l_cal['owner']);
1123                                }
1124                                //$this->so->add_attribute('priority',$l_cal['priority']);
1125
1126                                foreach($l_cal as $name => $value)
1127                                {
1128                                        if ($name[0] == '#')    // Custom field
1129                                        {
1130                                                //$this->so->add_attribute($name,stripslashes($value));
1131                                        }
1132                                }
1133                                if (isset($_POST['preserved']) && is_array($preserved = unserialize(stripslashes($_POST['preserved']))))
1134                                {
1135                                        foreach($preserved as $name => $value)
1136                                        {
1137                                                switch($name)
1138                                                {
1139                                                        case 'owner':
1140                                                                //$this->so->add_attribute('participants',$value,$l_cal['owner']);
1141                                                                break;
1142                                                        default:
1143echo "";
1144                                                                //$this->so->add_attribute($name,str_replace(array('&amp;','&quot;','&lt;','&gt;'),array('&','"','<','>'),$value));
1145                                                }
1146                                        }
1147                                }
1148                                $event = $this->get_cached_event();
1149
1150                                if ($l_cal['alarmdays'] > 0 || $l_cal['alarmhours'] > 0 ||
1151                                                $l_cal['alarmminutes'] > 0)
1152                                {
1153                                        $offset = ($l_cal['alarmdays'] * 24 * 3600) +
1154                                                ($l_cal['alarmhours'] * 3600) + ($l_cal['alarmminutes'] * 60);
1155
1156                                        $time = $this->maketime($event['start']) - $offset;
1157
1158                                        $event['alarm'][] = Array(
1159                                                'time'    => $time,
1160                                                'offset'  => $offset,
1161                                                'owner'   => $this->owner,
1162                                                'enabled' => 1,
1163                                                'repeat'  => $repetido, // para repetir alarme;
1164                                                'init_rept' => $init_rept, // inicio repeticao;
1165                                                'end_rept' => $end_rept, // fim repeticao;
1166                                                'rpt_wdays' => $rpt_wdays // dias repeticao da semana;
1167                                        );
1168                                }
1169
1170                                $this->store_to_appsession($event);
1171                                $datetime_check = $this->validate_update($event);
1172                                print_debug('bo->validated_update() returnval',$datetime_check);
1173
1174                                /*if($datetime_check)
1175                                {
1176
1177
1178                                        if (!$send_to_ui)
1179                                        {
1180                                                return array($datetime_check => 'invalid input data');
1181                                        }
1182
1183
1184                                        ExecMethod($ui_return,
1185                                                Array(
1186                                                        'cd'            => $datetime_check,
1187                                                        'readsess'      => 1
1188                                                )
1189                                        );
1190
1191                                        if(!$params['from_mobile'])
1192                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
1193                                        else
1194                                                return;
1195
1196                                }/*/
1197                                if($event['id'])
1198                                {
1199                                        $event_ids[] = $event['id'];
1200                                }
1201                                if($event['reference'])
1202                                {
1203                                        $event_ids[] = $event['reference'];
1204                                }
1205
1206                                $overlapping_events = $this->overlap(
1207                                        $this->maketime($event['start']),
1208                                        $this->maketime($event['end']),
1209                                        $event['participants'],
1210                                        $event['owner'],
1211                                        $event_ids
1212                                );
1213                        }
1214                        if(!$this->ex_participants)
1215                                $this->ex_participants = $event['ex_participants'];                     
1216                        if($overlapping_events)
1217                        {
1218
1219
1220                                if($send_to_ui)
1221                                {
1222                                        $event['ex_participants'] = $this->ex_participants;
1223                                        unset($GLOBALS['phpgw_info']['flags']['noheader']);
1224                                        unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
1225                                        ExecMethod($ui_overlap,
1226                                                Array(
1227                                                        'o_events'      => $overlapping_events,
1228                                                        'this_event'    => $event
1229                                                )
1230                                        );
1231                                        if(!$params['from_mobile'])
1232                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
1233                                        else
1234                                                return;
1235                                }
1236                                else
1237                                {
1238                                        return $overlapping_events;
1239                                }
1240                        }
1241                        else
1242                        {
1243
1244
1245
1246                                if(!$event['id'])
1247                                {
1248
1249
1250
1251                                        //$this->so->add_entry($event);
1252                                        $this->send_update(MSG_ADDED,$event['participants'],'',$this->get_cached_event());
1253                                        print_debug('New Event ID',$event['id']);
1254                                }
1255                                else
1256                                {
1257
1258                                        print_debug('Updating Event ID',$event['id']);
1259                                        $new_event = $event;
1260                                        $old_event = $this->read_entry($event['id']);
1261                                        // if old event has alarm and the start-time changed => update them
1262                                        //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";
1263                                        if ($old_event['alarm'] &&
1264                                                $this->maketime($old_event['start']) != $this->maketime($event['start']))
1265                                        {
1266                                                //$this->so->delete_alarms($old_event['id']);
1267                                                foreach($old_event['alarm'] as $id => $alarm)
1268                                                {
1269                                                        $alarm['time'] = $this->maketime($event['start']) - $alarm['offset'];
1270                                                        $event['alarm'][] = $alarm;
1271                                                }
1272                                                //echo "updated alarms<pre>".print_r($event['alarm'],True)."</pre>\n";
1273                                        }
1274                                        //$this->so->cal->event = $event;
1275                                        //$this->so->add_entry($event);
1276                                        $this->prepare_recipients($new_event,$old_event);
1277                                }
1278
1279                                $date = sprintf("%04d%02d%02d",$event['start']['year'],$event['start']['month'],$event['start']['mday']);
1280                                if($send_to_ui)
1281                                {
1282                                        $this->read_sessiondata();
1283                                        if ($this->return_to)
1284                                        {
1285                                                $GLOBALS['phpgw']->redirect_link('/index.php','menuaction='.$this->return_to);
1286                                                $GLOBALS['phpgw']->common->phpgw_exit();
1287                                        }
1288                                        Execmethod($ui_index);
1289                                }
1290                                else
1291                                {
1292                                        return (int)$event['id'];
1293                                }
1294                        }
1295                        return True;
1296                }
1297
1298                /* Private functions */
1299                function read_holidays($year=0)
1300                {
1301                        if(!$year)
1302                        {
1303                                $year = $this->year;
1304                        }
1305                        $holiday = CreateObject('resources.boholiday');
1306                        $holiday->prepare_read_holidays($year,$this->owner);
1307                        $this->cached_holidays = $holiday->read_holiday();
1308                        unset($holiday);
1309                }
1310
1311                function user_is_a_member($event,$user)
1312                {
1313                        @reset($event['participants']);
1314                        $uim = False;
1315                        $security_equals = $GLOBALS['phpgw']->accounts->membership($user);
1316                        while(!$uim && $event['participants'] && $security_equals && list($participant,$status) = each($event['participants']))
1317                        {
1318                                if($GLOBALS['phpgw']->accounts->get_type($participant) == 'g')
1319                                {
1320                                        @reset($security_equals);
1321                                        while(list($key,$group_info) = each($security_equals))
1322                                        {
1323                                                if($group_info['account_id'] == $participant)
1324                                                {
1325                                                        return True;
1326                                                        $uim = True;
1327                                                }
1328                                        }
1329                                }
1330                        }
1331                        return $uim;
1332                }
1333
1334                function maketime($time)
1335                {
1336//echo "tttt".$time['month']."  ".$time['mday']."  ".$time['year']."<br>";
1337                        return mktime(intval($time['hour']),intval($time['min']),intval($time['sec']),intval($time['month']),intval($time['mday']),intval($time['year']));
1338                }
1339
1340function maketime2($hora,$min,$seg,$dia,$mes,$ano,$ampm)
1341                {
1342if($ampm == 'pm' || $ampm == 'PM')  $hora = $hora+12;
1343
1344
1345                        return mktime(intval($hora),intval($min),intval($seg),intval($mes),intval($dia),intval($ano));
1346                }
1347                /*!
1348                @function time2array
1349                @abstract returns a date-array suitable for the start- or endtime of an event from a timestamp
1350                @syntax time2array($time,$alarm=0)
1351                @param $time the timestamp for the values of the array
1352                @param $alarm (optional) alarm field of the array, defaults to 0
1353                @author ralfbecker
1354                */
1355                function time2array($time,$alarm = 0)
1356                {
1357                        return array(
1358                                'year'  => (int)(date('Y',$time)),
1359                                'month' => (int)(date('m',$time)),
1360                                'mday'  => (int)(date('d',$time)),
1361                                'hour'  => (int)(date('g',$time)),
1362                                'min'   => (int)(date('i',$time)),
1363                                'sec'   => (int)(date('s',$time)),
1364                                'ampm'=> (int)(date('a',$time)),
1365                                'hourcompleta' => (int)(date('H',$time)),
1366                                'alarm' => (int)($alarm)
1367                        );
1368                }
1369
1370
1371                /*!
1372                @function set_recur_date
1373                @abstract set the start- and enddates of a recuring event for a recur-date
1374                @syntax set_recur_date(&$event,$date)
1375                @param $event the event which fields to set (has to be the original event for start-/end-times)
1376                @param $date  the recuring date in form 'Ymd', eg. 20030226
1377                @author ralfbecker
1378                */
1379                function set_recur_date(&$event,$date)
1380                {
1381                        $org_start = $this->maketime($event['start']);
1382                        $org_end   = $this->maketime($event['end']);
1383                        $start = mktime($event['start']['hour'],$event['start']['min'],0,substr($date,4,2),substr($date,6,2),substr($date,0,4));
1384                        $end   = $org_end + $start - $org_start;
1385                        $event['start'] = $this->time2array($start);
1386                        $event['end']   = $this->time2array($end);
1387                }
1388
1389                function fix_update_time(&$time_param)
1390                {
1391                        if (isset($time_param['str']))
1392                        {
1393                                if (!is_object($this->jscal))
1394                                {
1395                                        $this->jscal = CreateObject('phpgwapi.jscalendar');
1396                                }
1397                                $time_param += $this->jscal->input2date($time_param['str'],False,'mday');
1398                                unset($time_param['str']);
1399                        }
1400                        if ($this->prefs['common']['timeformat'] == '12')
1401                        {
1402                                if ($time_param['ampm'] == 'pm')
1403                                {
1404                                        if ($time_param['hour'] <> 12)
1405                                        {
1406                                                $time_param['hour'] += 12;
1407                                        }
1408                                }
1409                                elseif ($time_param['ampm'] == 'am')
1410                                {
1411                                        if ($time_param['hour'] == 12)
1412                                        {
1413                                                $time_param['hour'] -= 12;
1414                                        }
1415                                }
1416
1417                                if($time_param['hour'] > 24)
1418                                {
1419                                        $time_param['hour'] -= 12;
1420                                }
1421                        }
1422                }
1423
1424                function validate_update($event)
1425                {
1426                        $error = 0;
1427                        // do a little form verifying
1428                        if (!count($event['participants']))
1429                        {
1430                                $error = 43;
1431                        }
1432                        elseif ($event['title'] == '')
1433                        {
1434                                $error = 40;
1435                        }
1436                        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))
1437                        {
1438                                $error = 41;
1439                        }
1440                        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))
1441                        {
1442                                $error = 42;
1443                        }
1444                        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)
1445                        {
1446                                if ($GLOBALS['phpgw']->datetime->time_compare($event['start']['hour'],$event['start']['min'],0,$event['end']['hour'],$event['end']['min'],0) == 1)
1447                                {
1448                                        $error = 42;
1449                                }
1450                        }
1451                        return $error;
1452                }
1453
1454                /*!
1455                @function participants_not_rejected($participants,$event)
1456                @abstract checks if any of the $particpants participates in $event and has not rejected it
1457                */
1458                function participants_not_rejected($participants,$event)
1459                {
1460                        //echo "participants_not_rejected()<br>participants =<pre>"; print_r($participants); echo "</pre><br>event[participants]=<pre>"; print_r($event['participants']); echo "</pre>\n";
1461                        foreach($participants as $uid => $status)
1462                        {
1463                                //echo "testing event[participants][uid=$uid] = '".$event['participants'][$uid]."'<br>\n";
1464                                if (isset($event['participants'][$uid]) && $event['participants'][$uid] != 'R' &&
1465                                        $status != 'R')
1466                                {
1467                                        return True;    // found not rejected participant in event
1468                                }
1469                        }
1470                        return False;
1471                }
1472
1473                function overlap($starttime,$endtime,$participants,$owner=0,$id=0,$restore_cache=False)
1474                {
1475//                      $retval = Array();
1476//                      $ok = False;
1477
1478/* This needs some attention.. by commenting this chunk of code it will fix bug #444265 */
1479
1480                        if($restore_cache)
1481                        {
1482                                $temp_cache_events = $this->cached_events;
1483                        }
1484
1485//                      $temp_start = (int)$GLOBALS['phpgw']->common->show_date($starttime,'Ymd');
1486//                      $temp_start_time = (int)($GLOBALS['phpgw']->common->show_date($starttime,'Hi');
1487//                      $temp_end = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Ymd');
1488//                      $temp_end_time = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Hi');
1489                        $temp_start = (int)(date('Ymd',$starttime));
1490                        $temp_start_time = (int)(date('Hi',$starttime));
1491                        $temp_end = (int)(date('Ymd',$endtime));
1492                        $temp_end_time = (int)(date('Hi',$endtime));
1493                        if($this->debug)
1494                        {
1495                                echo '<!-- Temp_Start: '.$temp_start.' -->'."\n";
1496                                echo '<!-- Temp_End: '.$temp_end.' -->'."\n";
1497                        }
1498
1499                        $users = Array();
1500                        if(count($participants))
1501                        {
1502                                while(list($user,$status) = each($participants))
1503                                {
1504                                        $users[] = $user;
1505                                }
1506                        }
1507                        else
1508                        {
1509                                $users[] = $this->owner;
1510                        }
1511
1512                        $possible_conflicts = $this->store_to_cache(
1513                                Array(
1514                                        'smonth'        => substr(strval($temp_start),4,2),
1515                                        'sday'  => substr(strval($temp_start),6,2),
1516                                        'syear' => substr(strval($temp_start),0,4),
1517                                        'emonth'        => substr(strval($temp_end),4,2),
1518                                        'eday'  => substr(strval($temp_end),6,2),
1519                                        'eyear' => substr(strval($temp_end),0,4),
1520                                        'owner' => $users
1521                                )
1522                        );
1523
1524                        if($this->debug)
1525                        {
1526                                echo '<!-- Possible Conflicts ('.($temp_start - 1).'): '.count($possible_conflicts[$temp_start - 1]).' -->'."\n";
1527                                echo '<!-- Possible Conflicts ('.$temp_start.'): '.count($possible_conflicts[$temp_start]).' '.count($id).' -->'."\n";
1528                        }
1529
1530                        if($possible_conflicts[$temp_start] || $possible_conflicts[$temp_end])
1531                        {
1532                                if($temp_start == $temp_end)
1533                                {
1534                                        if($this->debug)
1535                                        {
1536                                                echo '<!-- Temp_Start == Temp_End -->'."\n";
1537                                        }
1538                                        @reset($possible_conflicts[$temp_start]);
1539                                        while(list($key,$event) = each($possible_conflicts[$temp_start]))
1540                                        {
1541                                                $found = False;
1542                                                if($id)
1543                                                {
1544                                                        @reset($id);
1545                                                        while(list($key,$event_id) = each($id))
1546                                                        {
1547                                                                if($this->debug)
1548                                                                {
1549                                                                        echo '<!-- $id['.$key.'] = '.$id[$key].' = '.$event_id.' -->'."\n";
1550                                                                        echo '<!-- '.$event['id'].' == '.$event_id.' -->'."\n";
1551                                                                }
1552                                                                if($event['id'] == $event_id)
1553                                                                {
1554                                                                        $found = True;
1555                                                                }
1556                                                        }
1557                                                }
1558                                                if($this->debug)
1559                                                {
1560                                                        echo '<!-- Item found: '.$found.' -->'."<br>\n";
1561                                                }
1562                                                if(!$found)
1563                                                {
1564                                                        if($this->debug)
1565                                                        {
1566                                                                echo '<!-- Checking event id #'.$event['id'];
1567                                                        }
1568                                                        $temp_event_start = sprintf("%d%02d",$event['start']['hour'],$event['start']['min']);
1569                                                        $temp_event_end = sprintf("%d%02d",$event['end']['hour'],$event['end']['min']);
1570//                                                      if((($temp_start_time <= $temp_event_start) && ($temp_end_time >= $temp_event_start) && ($temp_end_time <= $temp_event_end)) ||
1571                                                        if(($temp_start_time <= $temp_event_start &&
1572                                                                $temp_end_time > $temp_event_start &&
1573                                                                $temp_end_time <= $temp_event_end ||
1574                                                                $temp_start_time >= $temp_event_start &&
1575                                                                $temp_start_time < $temp_event_end &&
1576                                                                $temp_end_time >= $temp_event_end ||
1577                                                                $temp_start_time <= $temp_event_start &&
1578                                                                $temp_end_time >= $temp_event_end ||
1579                                                                $temp_start_time >= $temp_event_start &&
1580                                                                $temp_end_time <= $temp_event_end) &&
1581                                                                $this->participants_not_rejected($participants,$event))
1582                                                        {
1583                                                                if($this->debug)
1584                                                                {
1585                                                                        echo ' Conflicts';
1586                                                                }
1587                                                                $retval[] = $event['id'];
1588                                                        }
1589                                                        if($this->debug)
1590                                                        {
1591                                                                echo ' -->'."\n";
1592                                                        }
1593                                                }
1594                                        }
1595                                }
1596                        }
1597                        else
1598                        {
1599                                $retval = False;
1600                        }
1601
1602                        if($restore_cache)
1603                        {
1604                                $this->cached_events = $temp_cache_events;
1605                        }
1606
1607                        return $retval;
1608                }
1609
1610                /*!
1611                @function check_perms( )
1612                @syntax check_perms($needed,$event=0,$other=0)
1613                @abstract Checks if the current user has the necessary ACL rights
1614                @author ralfbecker
1615                @discussion The check is performed on an event or general on the cal of an other user
1616                @param $needed necessary ACL right: PHPGW_ACL_{READ|EDIT|DELETE}
1617                @param $event event as array or the event-id or 0 for general check
1618                @param $other uid to check (if event==0) or 0 to check against $this->owner
1619                @note Participating in an event is considered as haveing read-access on that event, \
1620                        even if you have no general read-grant from that user.
1621                */
1622                function check_perms($needed,$event=0,$other=0)
1623                {
1624                        $event_in = $event;
1625                       
1626                        if (is_int($event) && $event == 0)
1627                        {
1628                                $owner = $other > 0 ? $other : $this->owner;
1629                        }
1630                        else
1631                        {
1632                                if (!is_array($event))
1633                                {
1634                                        $event = "";//$this->so->read_entry((int) $event);
1635                                }
1636                                if (!is_array($event))
1637                                {
1638                                        if ($this->xmlrpc)
1639                                        {
1640                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['not_exist'],$GLOBALS['xmlrpcstr']['not_exist']);
1641                                        }
1642                                        return False;
1643                                }
1644                                $owner = $event['owner'];
1645                                $private = $event['public'] == False || $event['public'] == 0;
1646                        }
1647                        $user = $GLOBALS['phpgw_info']['user']['account_id'];
1648                        $grants = $this->grants[$owner];
1649
1650                        if (is_array($event) && $needed == PHPGW_ACL_READ)
1651                        {
1652                                // Check if the $user is one of the participants or has a read-grant from one of them
1653                                //
1654if($event['participants']){
1655                                foreach($event['participants'] as $uid => $accept)
1656                                {
1657                                        if ($this->grants[$uid] & PHPGW_ACL_READ || $uid == $user)
1658                                        {
1659                                                $grants |= PHPGW_ACL_READ;
1660                                                // if the $user is one of the participants read-grant private (restricted) too.
1661                                                if($uid == $user || ($this->grants[$uid] & PHPGW_ACL_PRIVATE)) {
1662                                                        $grants |= PHPGW_ACL_PRIVATE;
1663                                                }
1664                                                //break;
1665                                        }
1666                                }
1667}
1668                        }
1669
1670                        if ($GLOBALS['phpgw']->accounts->get_type($owner) == 'g' && $needed == PHPGW_ACL_ADD)
1671                        {
1672                                $access = False;        // a group can't be the owner of an event
1673                        }
1674                        else
1675                        {
1676                                $access = $user == $owner || $grants & $needed && (!$private || $grants & PHPGW_ACL_PRIVATE);
1677                        }
1678                        //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";
1679
1680                        return $access;
1681                }
1682
1683
1684                function display_status($user_status)
1685                {
1686                        if(@$this->prefs['resources']['display_status'] && $user_status)
1687                        {
1688                                $user_status = substr($this->get_long_status($user_status),0,1);
1689
1690                                return ' ('.$user_status.')';
1691                        }
1692                        else
1693                        {
1694                                return '';
1695                        }
1696                }
1697
1698                function get_long_status($status_short)
1699                {
1700                        switch ($status_short)
1701                        {
1702                                case 'A':
1703                                        $status = lang('Accepted');
1704                                        break;
1705                                case 'R':
1706                                        $status = lang('Rejected');
1707                                        break;
1708                                case 'T':
1709                                        $status = lang('Tentative');
1710                                        break;
1711                                case 'U':
1712                                        $status = lang('No Response');
1713                                        break;
1714                        }
1715                        return $status;
1716                }
1717
1718                function is_private($event,$owner)
1719                {
1720                        if($owner == 0)
1721                        {
1722                                $owner = $this->owner;
1723                        }
1724                        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'])
1725                        {
1726                                return False;
1727                        }
1728                        elseif($event['public'] == 0)
1729                        {
1730                                return True;
1731                        }
1732                        elseif($event['public'] == 2)
1733                        {
1734                                $is_private = True;
1735                                $groups = $GLOBALS['phpgw']->accounts->membership($owner);
1736                                while (list($key,$group) = each($groups))
1737                                {
1738                                        if (strpos(' '.implode(',',$event['groups']).' ',$group['account_id']))
1739                                        {
1740                                                return False;
1741                                        }
1742                                }
1743                        }
1744                        else
1745                        {
1746                                return False;
1747                        }
1748
1749                        return $is_private;
1750                }
1751
1752                function get_short_field($event,$is_private=True,$field='')
1753                {
1754
1755
1756                        if($is_private)
1757                        {
1758                                return lang('private');
1759                        }
1760
1761// cut off too long titles
1762                        elseif(strlen($event[$field]) > 19 && !$this->printer_friendly && $field=="title")
1763//                      elseif(strlen($event[$field]) > 19 && $this->printer_friendly)
1764                        {
1765// we dont use currently 160304
1766//                              return substr($event[$field], 0 , 19) . '&nbsp;...';
1767                                return $event[$field];
1768                        }
1769                        else
1770                        {
1771                                return $event[$field];
1772                        }
1773                }
1774
1775                function long_date($first,$last=0)
1776                {
1777                        if (!is_array($first))
1778                        {
1779                                $first = $this->time2array($raw = $first);
1780                                $first['raw'] = $raw;
1781                                $first['day'] = $first['mday'];
1782                        }
1783                        if ($last && !is_array($last))
1784                        {
1785                                $last = $this->time2array($raw = $last);
1786                                $last['raw'] = $raw;
1787                                $last['day'] = $last['mday'];
1788                        }
1789                        $datefmt = $this->prefs['common']['dateformat'];
1790
1791                        $month_before_day = strtolower($datefmt[0]) == 'm' ||
1792                                strtolower($datefmt[2]) == 'm' && $datefmt[4] == 'd';
1793
1794                        for ($i = 0; $i < 5; $i += 2)
1795                        {
1796                                switch($datefmt[$i])
1797                                {
1798                                        case 'd':
1799                                                $range .= $first['day'] . ($datefmt[1] == '.' ? '.' : '');
1800                                                if ($first['month'] != $last['month'] || $first['year'] != $last['year'])
1801                                                {
1802                                                        if (!$month_before_day)
1803                                                        {
1804                                                                $range .= ' '.lang(strftime('%B',$first['raw']));
1805                                                        }
1806                                                        if ($first['year'] != $last['year'] && $datefmt[0] != 'Y')
1807                                                        {
1808                                                                $range .= ($datefmt[0] != 'd' ? ', ' : ' ') . $first['year'];
1809                                                        }
1810                                                        if (!$last)
1811                                                        {
1812                                                                return $range;
1813                                                        }
1814                                                        $range .= ' - ';
1815
1816                                                        if ($first['year'] != $last['year'] && $datefmt[0] == 'Y')
1817                                                        {
1818                                                                $range .= $last['year'] . ', ';
1819                                                        }
1820
1821                                                        if ($month_before_day)
1822                                                        {
1823                                                                $range .= lang(strftime('%B',$last['raw']));
1824                                                        }
1825                                                }
1826                                                else
1827                                                {
1828                                                        $range .= ' - ';
1829                                                }
1830                                                $range .= ' ' . $last['day'] . ($datefmt[1] == '.' ? '.' : '');
1831                                                break;
1832                                        case 'm':
1833                                        case 'M':
1834                                                $range .= ' '.lang(strftime('%B',$month_before_day ? $first['raw'] : $last['raw'])) . ' ';
1835                                                break;
1836                                        case 'Y':
1837                                                $range .= ($datefmt[0] == 'm' ? ', ' : ' ') . ($datefmt[0] == 'Y' ? $first['year'].($datefmt[2] == 'd' ? ', ' : ' ') : $last['year'].' ');
1838                                                break;
1839                                }
1840                        }
1841                        return $range;
1842                }
1843
1844                function get_week_label()
1845                {
1846                        $first = $GLOBALS['phpgw']->datetime->gmtdate($GLOBALS['phpgw']->datetime->get_weekday_start($this->year, $this->month, $this->day));
1847                        $last = $GLOBALS['phpgw']->datetime->gmtdate($first['raw'] + 518400);
1848
1849                        return ($this->long_date($first,$last));
1850                }
1851
1852                function normalizeminutes(&$minutes)
1853                {
1854                        $hour = 0;
1855                        $min = (int)$minutes;
1856                        if($min >= 60)
1857                        {
1858                                $hour += $min / 60;
1859                                $min %= 60;
1860                        }
1861                        settype($minutes,'integer');
1862                        $minutes = $min;
1863                        return $hour;
1864                }
1865
1866                function splittime($time,$follow_24_rule=True)
1867                {
1868                        $temp = array('hour','minute','second','ampm');
1869                        $time = strrev($time);
1870                        $second = (int)(strrev(substr($time,0,2)));
1871                        $minute = (int)(strrev(substr($time,2,2)));
1872                        $hour   = (int)(strrev(substr($time,4)));
1873                        $hour += $this->normalizeminutes($minute);
1874                        $temp['second'] = $second;
1875                        $temp['minute'] = $minute;
1876                        $temp['hour']   = $hour;
1877                        $temp['ampm']   = '  ';
1878                        if($follow_24_rule == True)
1879                        {
1880                                if ($this->prefs['common']['timeformat'] == '24')
1881                                {
1882                                        return $temp;
1883                                }
1884
1885                                $temp['ampm'] = 'am';
1886
1887                                if ((int)$temp['hour'] > 12)
1888                                {
1889                                        $temp['hour'] = (int)((int)$temp['hour'] - 12);
1890                                        $temp['ampm'] = 'pm';
1891                                }
1892                                elseif ((int)$temp['hour'] == 12)
1893                                {
1894                                        $temp['ampm'] = 'pm';
1895                                }
1896                        }
1897                        return $temp;
1898                }
1899
1900                function get_exception_array($exception_str='')
1901                {
1902                        $exception = Array();
1903                        if(strpos(' '.$exception_str,','))
1904                        {
1905                                $exceptions = explode(',',$exception_str);
1906                                for($exception_count=0;$exception_count<count($exceptions);$exception_count++)
1907                                {
1908                                        $exception[] = (int)$exceptions[$exception_count];
1909                                }
1910                        }
1911                        elseif($exception_str != '')
1912                        {
1913                                $exception[] = (int)$exception_str;
1914                        }
1915                        return $exception;
1916                }
1917
1918                function build_time_for_display($fixed_time)
1919                {
1920                        $time = $this->splittime($fixed_time);
1921                        $str = $time['hour'].':'.((int)$time['minute']<=9?'0':'').$time['minute'];
1922
1923                        if ($this->prefs['common']['timeformat'] == '12')
1924                        {
1925                                $str .= ' ' . $time['ampm'];
1926                        }
1927
1928                        return $str;
1929                }
1930
1931                function sort_event($event,$date)
1932                {
1933                        $inserted = False;
1934                        if(isset($event['recur_exception']))
1935                        {
1936                                $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;
1937                                while($inserted == False && list($key,$exception_time) = each($event['recur_exception']))
1938                                {
1939                                        if($this->debug)
1940                                        {
1941                                                echo '<!-- checking exception datetime '.$exception_time.' to event datetime '.$event_time.' -->'."\n";
1942                                        }
1943                                        if($exception_time == $event_time)
1944                                        {
1945                                                $inserted = True;
1946                                        }
1947                                }
1948                        }
1949                        if($this->cached_events[$date] && $inserted == False)
1950                        {
1951
1952                                if($this->debug)
1953                                {
1954                                        echo '<!-- Cached Events found for '.$date.' -->'."\n";
1955                                }
1956                                $year = substr($date,0,4);
1957                                $month = substr($date,4,2);
1958                                $day = substr($date,6,2);
1959
1960                                if($this->debug)
1961                                {
1962                                        echo '<!-- Date : '.$date.' Count : '.count($this->cached_events[$date]).' -->'."\n";
1963                                }
1964
1965                                for($i=0;$i<count($this->cached_events[$date]);$i++)
1966                                {
1967                                        if($this->cached_events[$date][$i]['id'] == $event['id'] || $this->cached_events[$date][$i]['reference'] == $event['id'])
1968                                        {
1969                                                if($this->debug)
1970                                                {
1971                                                        echo '<!-- Item already inserted! -->'."\n";
1972                                                }
1973                                                $inserted = True;
1974                                                break;
1975                                        }
1976                                        /* This puts all spanning events across multiple days up at the top. */
1977                                        if($this->cached_events[$date][$i]['recur_type'] == MCAL_RECUR_NONE)
1978                                        {
1979                                                if($this->cached_events[$date][$i]['start']['mday'] != $day && $this->cached_events[$date][$i]['end']['mday'] >= $day)
1980                                                {
1981                                                        continue;
1982                                                }
1983                                        }
1984                                        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)))
1985                                        {
1986                                                for($j=count($this->cached_events[$date]);$j>=$i;$j--)
1987                                                {
1988                                                        $this->cached_events[$date][$j] = $this->cached_events[$date][$j-1];
1989                                                }
1990                                                if($this->debug)
1991                                                {
1992                                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
1993                                                }
1994                                                $inserted = True;
1995                                                $this->cached_events[$date][$i] = $event;
1996                                                break;
1997                                        }
1998                                }
1999                        }
2000                        if(!$inserted)
2001                        {
2002                                if($this->debug)
2003                                {
2004                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
2005                                }
2006                                $this->cached_events[$date][] = $event;
2007                        }
2008                }
2009
2010                function check_repeating_events($datetime)
2011                {
2012                        @reset($this->repeating_events);
2013                        $search_date_full = date('Ymd',$datetime);
2014                        $search_date_year = date('Y',$datetime);
2015                        $search_date_month = date('m',$datetime);
2016                        $search_date_day = date('d',$datetime);
2017                        $search_date_dow = date('w',$datetime);
2018                        $search_beg_day = mktime(0,0,0,$search_date_month,$search_date_day,$search_date_year);
2019                        if($this->debug)
2020                        {
2021                                echo '<!-- Search Date Full = '.$search_date_full.' -->'."\n";
2022                        }
2023                        $repeated = $this->repeating_events;
2024                        $r_events = count($repeated);
2025                        for ($i=0;$i<$r_events;$i++)
2026                        {
2027                                $rep_events = $this->repeating_events[$i];
2028                                $id = $rep_events['id'];
2029                                $event_beg_day = mktime(0,0,0,$rep_events['start']['month'],$rep_events['start']['mday'],$rep_events['start']['year']);
2030                                if($rep_events['recur_enddate']['month'] != 0 && $rep_events['recur_enddate']['mday'] != 0 && $rep_events['recur_enddate']['year'] != 0)
2031                                {
2032                                        $event_recur_time = $this->maketime($rep_events['recur_enddate']);
2033                                }
2034                                else
2035                                {
2036                                        $event_recur_time = mktime(0,0,0,1,1,2030);
2037                                }
2038                                $end_recur_date = date('Ymd',$event_recur_time);
2039                                $full_event_date = date('Ymd',$event_beg_day);
2040
2041                                if($this->debug)
2042                                {
2043                                        echo '<!-- check_repeating_events - Processing ID - '.$id.' -->'."\n";
2044                                        echo '<!-- check_repeating_events - Recurring End Date - '.$end_recur_date.' -->'."\n";
2045                                }
2046
2047                                // only repeat after the beginning, and if there is an rpt_end before the end date
2048                                if (($search_date_full > $end_recur_date) || ($search_date_full < $full_event_date))
2049                                {
2050                                        continue;
2051                                }
2052
2053                                if ($search_date_full == $full_event_date)
2054                                {
2055                                        $this->sort_event($rep_events,$search_date_full);
2056                                        continue;
2057                                }
2058                                else
2059                                {
2060                                        $freq = $rep_events['recur_interval'];
2061                                        $freq = $freq ? $freq : 1;
2062                                        $type = $rep_events['recur_type'];
2063                                        switch($type)
2064                                        {
2065                                                case MCAL_RECUR_DAILY:
2066                                                        if($this->debug)
2067                                                        {
2068                                                                echo '<!-- check_repeating_events - MCAL_RECUR_DAILY - '.$id.' -->'."\n";
2069                                                        }
2070                                                       
2071                                                        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)
2072                                                        {
2073                                                                $this->sort_event($rep_events,$search_date_full);
2074                                                        }
2075                                                        elseif (floor(($search_beg_day - $event_beg_day)/86400) % ($freq ? $freq : 1))
2076                                                        {
2077                                                                continue;
2078                                                        }
2079                                                        else
2080                                                        {
2081                                                                $this->sort_event($rep_events,$search_date_full);
2082                                                        }
2083                                                        break;
2084                                                case MCAL_RECUR_WEEKLY:
2085                                                        if (floor(($search_beg_day - $event_beg_day)/604800)  % ($freq ? $freq : 1))
2086                                                        {
2087                                                                continue;
2088                                                        }
2089                                                        $check = 0;
2090                                                        switch($search_date_dow)
2091                                                        {
2092                                                                case 0:
2093                                                                        $check = MCAL_M_SUNDAY;
2094                                                                        break;
2095                                                                case 1:
2096                                                                        $check = MCAL_M_MONDAY;
2097                                                                        break;
2098                                                                case 2:
2099                                                                        $check = MCAL_M_TUESDAY;
2100                                                                        break;
2101                                                                case 3:
2102                                                                        $check = MCAL_M_WEDNESDAY;
2103                                                                        break;
2104                                                                case 4:
2105                                                                        $check = MCAL_M_THURSDAY;
2106                                                                        break;
2107                                                                case 5:
2108                                                                        $check = MCAL_M_FRIDAY;
2109                                                                        break;
2110                                                                case 6:
2111                                                                        $check = MCAL_M_SATURDAY;
2112                                                                        break;
2113                                                        }
2114                                                        if ($rep_events['recur_data'] & $check)
2115                                                        {
2116                                                                $this->sort_event($rep_events,$search_date_full);
2117                                                        }
2118                                                        break;
2119                                                case MCAL_RECUR_MONTHLY_WDAY:
2120                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month']) % $freq)
2121                                                        {
2122                                                                continue;
2123                                                        }
2124
2125                                                        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)) &&
2126                                                                (ceil($rep_events['start']['mday']/7) == ceil($search_date_day/7)))
2127                                                        {
2128                                                                $this->sort_event($rep_events,$search_date_full);
2129                                                        }
2130                                                        break;
2131                                                case MCAL_RECUR_MONTHLY_MDAY:
2132                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month'])  % ($freq ? $freq : 1))
2133                                                        {
2134                                                                continue;
2135                                                        }
2136                                                        if ($search_date_day == $rep_events['start']['mday'])
2137                                                        {
2138                                                                $this->sort_event($rep_events,$search_date_full);
2139                                                        }
2140                                                        break;
2141                                                case MCAL_RECUR_YEARLY:
2142                                                        if (($search_date_year - $rep_events['start']['year']) % ($freq ? $freq : 1))
2143                                                        {
2144                                                                continue;
2145                                                        }
2146                                                        if (date('dm',$datetime) == date('dm',$event_beg_day))
2147                                                        {
2148                                                                $this->sort_event($rep_events,$search_date_full);
2149                                                        }
2150                                                        break;
2151                                        }
2152                                }
2153                        }       // end for loop
2154                }       // end function
2155
2156                function store_to_cache($params)
2157                {
2158                        if(!is_array($params))
2159                        {
2160                                return False;
2161                        }
2162                        if (isset($params['start']) && ($datearr = $GLOBALS['server']->iso86012date($params['start'])))
2163                        {
2164                                $syear = $datearr['year'];
2165                                $smonth = $datearr['month'];
2166                                $sday = $datearr['mday'];
2167                                $this->xmlrpc = True;
2168                        }
2169                        else
2170                        {
2171                                $syear = $params['syear'];
2172                                $smonth = $params['smonth'];
2173                                $sday = $params['sday'];
2174                        }
2175                        if (isset($params['end']) && ($datearr = $GLOBALS['server']->iso86012date($params['end'])))
2176                        {
2177                                $eyear = $datearr['year'];
2178                                $emonth = $datearr['month'];
2179                                $eday = $datearr['mday'];
2180                                $this->xmlrpc = True;
2181                        }
2182                        else
2183                        {
2184                                $eyear = (isset($params['eyear'])?$params['eyear']:0);
2185                                $emonth = (isset($params['emonth'])?$params['emonth']:0);
2186                                $eday = (isset($params['eday'])?$params['eday']:0);
2187                        }
2188                        if (!isset($params['owner']) && @$this->xmlrpc)
2189                        {
2190                                $owner_id = $GLOBALS['phpgw_info']['user']['user_id'];
2191                        }
2192                        else
2193                        {
2194                                $owner_id = (isset($params['owner'])?$params['owner']:0);
2195                                if($owner_id==0 && $this->is_group)
2196                                {
2197                                        unset($owner_id);
2198                                        $owner_id = $this->g_owner;
2199                                        if($this->debug)
2200                                        {
2201                                                echo '<!-- owner_id in ('.implode(',',$owner_id).') -->'."\n";
2202                                        }
2203                                }
2204                        }
2205                        if(!$eyear && !$emonth && !$eday)
2206                        {
2207                                $edate = mktime(23,59,59,$smonth + 1,$sday + 1,$syear);
2208                                $eyear = date('Y',$edate);
2209                                $emonth = date('m',$edate);
2210                                $eday = date('d',$edate);
2211                        }
2212                        else
2213                        {
2214                                if(!$eyear)
2215                                {
2216                                        $eyear = $syear;
2217                                }
2218                                //Tratamento do valor final (mes) da pesquisa de eventos feita em $this->so->list_events.
2219                                //Se $emonth nao tem valor, recebe o valor de $smonth (que recebe $params['smonth']) e soma 1.
2220                                //O valor $params['emonth'] indica o mes final para a pesquisa de eventos, e passou a ser
2221                                //informado na a impressao de eventos mensais. Mudancas feitas em class.uiresources.inc.php,
2222                                //function display_month_print();
2223                                if(!$emonth)
2224                                {
2225                                        $emonth = $smonth + 1;
2226                                        if($emonth > 12)
2227                                        {
2228                                                $emonth = 1;
2229                                                $eyear++;
2230                                        }
2231                                }
2232                                if(!$eday)
2233                                {
2234                                        $eday = $sday + 1;
2235                                }
2236                                $edate = mktime(23,59,59,$emonth,$eday,$eyear);
2237                        }
2238                        //echo "<p>boresources::store_to_cache(".print_r($params,True).") syear=$syear, smonth=$smonth, sday=$sday, eyear=$eyear, emonth=$emonth, eday=$eday, xmlrpc='$param[xmlrpc]'</p>\n";
2239                        if($this->debug)
2240                        {
2241                                echo '<!-- Start Date : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2242                                echo '<!-- End   Date : '.sprintf("%04d%02d%02d",$eyear,$emonth,$eday).' -->'."\n";
2243                        }
2244                        //A variavel $month_print recebe o parametro 'saux' com o mes de inicio da pesquisa de eventos por
2245                        //$this->so->list_events. O valor do mes final da pesquisa e tratado no codigo acima;
2246                        //$month_ini = $params['saux'];
2247
2248                        if($owner_id)
2249                        {
2250                                $cached_event_ids = "";//$this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2251                                $cached_event_ids_repeating = "";//$this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2252                        }
2253                        else
2254                        {
2255                                $cached_event_ids = "";//$this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2256                                $cached_event_ids_repeating = "";//$this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2257                        }
2258
2259                        $c_cached_ids = count($cached_event_ids);
2260                        $c_cached_ids_repeating = count($cached_event_ids_repeating);
2261
2262                        if($this->debug)
2263                        {
2264                                echo '<!-- events cached : '.$c_cached_ids.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2265                                echo '<!-- repeating events cached : '.$c_cached_ids_repeating.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2266                        }
2267
2268                        $this->cached_events = Array();
2269
2270                        if($c_cached_ids == 0 && $c_cached_ids_repeating == 0)
2271                        {
2272                                return;
2273                        }
2274
2275                        $cache_start = (int)(sprintf("%04d%02d%02d",$syear,$smonth,$sday));
2276                        $cached_event=$this->get_cached_event();
2277                        if($c_cached_ids)
2278                        {
2279                                for($i=0;$i<$c_cached_ids;$i++)
2280                                {
2281                                        $event = "";//$this->so->read_entry($cached_event_ids[$i]);
2282                                        if ($event['recur_type'])
2283                                        {
2284                                                continue;       // fetch recuring events only in 2. loop
2285                                        }
2286                                        $startdate = (int)(date('Ymd',$this->maketime($event['start'])));
2287                                        $enddate = (int)(date('Ymd',$this->maketime($event['end'])));
2288                                        $this->cached_events[$startdate][] = $event;
2289                                        if($startdate != $enddate)
2290                                        {
2291                                                $start['year'] = (int)(substr($startdate,0,4));
2292                                                $start['month'] = (int)(substr($startdate,4,2));
2293                                                $start['mday'] = (int)(substr($startdate,6,2));
2294                                                for($j=$startdate,$k=0;$j<=$enddate;$k++,$j=(int)(date('Ymd',mktime(0,0,0,$start['month'],$start['mday'] + $k,$start['year']))))
2295                                                {
2296                                                        $c_evt_day = count($this->cached_events[$j]) - 1;
2297                                                        if($c_evt_day < 0)
2298                                                        {
2299                                                                $c_evt_day = 0;
2300                                                        }
2301                                                        if($this->debug)
2302                                                        {
2303                                                                echo '<!-- Date: '.$j.' Count : '.$c_evt_day.' -->'."\n";
2304                                                        }
2305                                                        if($this->cached_events[$j][$c_evt_day]['id'] != $event['id'])
2306                                                        {
2307                                                                if($this->debug)
2308                                                                {
2309                                                                        echo '<!-- Adding Event for Date: '.$j.' -->'."\n";
2310                                                                }
2311                                                                $this->cached_events[$j][] = $event;
2312                                                        }
2313                                                        if ($j >= $cache_start && (@$params['no_doubles'] || @$this->xmlrpc))
2314                                                        {
2315                                                                break;  // add event only once on it's startdate
2316                                                        }
2317                                                }
2318                                        }
2319                                }
2320                        }
2321
2322                        $this->repeating_events = Array();
2323                        if($c_cached_ids_repeating)
2324                        {
2325                                for($i=0;$i<$c_cached_ids_repeating;$i++)
2326                                {
2327                                        $this->repeating_events[$i] = "";//$this->so->read_entry($cached_event_ids_repeating[$i]);
2328                                        if($this->debug)
2329                                        {
2330                                                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";
2331                                        }
2332                                }
2333                                for($date=mktime(0,0,0,$smonth,$sday,$syear);$date<=$edate;$date += 86400)
2334                                {
2335                                        if($this->debug)
2336                                        {
2337                                                $search_date = date('Ymd',$date);
2338                                                echo '<!-- Calling check_repeating_events('.$search_date.') -->'."\n";
2339                                        }
2340                                        $this->check_repeating_events($date);
2341                                        if($this->debug)
2342                                        {
2343                                                echo '<!-- Total events found matching '.$search_date.' = '.count($this->cached_events[$search_date]).' -->'."\n";
2344                                                for($i=0;$i<count($this->cached_events[$search_date]);$i++)
2345                                                {
2346                                                        echo '<!-- Date: '.$search_date.' ['.$i.'] = '.$this->cached_events[$search_date][$i]['id'].' -->'."\n";
2347                                                }
2348                                        }
2349                                }
2350                        }
2351                        $retval = Array();
2352                        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)))
2353                        {
2354                                if(is_array($this->cached_events[$j]))
2355                                {
2356                                        if ($this->xmlrpc)
2357                                        {
2358                                                foreach($this->cached_events[$j] as $event)
2359                                                {
2360                                                        $retval[] = $this->xmlrpc_prepare($event);
2361                                                }
2362                                        }
2363                                        else
2364                                        {
2365                                                $retval[$j] = $this->cached_events[$j];
2366                                        }
2367                                }
2368                        }
2369                        //echo "store_to_cache(".print_r($params,True).")=<pre>".print_r($retval,True)."</pre>\n";
2370                        //$this->so->cal->event = $cached_event;
2371                        return $retval;
2372                }
2373
2374                function xmlrpc_prepare(&$event)
2375                {
2376                        $event['rights'] = $this->grants[$event['owner']];
2377
2378                        foreach(array('start','end','modtime','recur_enddate') as $name)
2379                        {
2380                                if (isset($event[$name]))
2381                                {
2382                                        $event[$name] = $GLOBALS['server']->date2iso8601($event[$name]);
2383                                }
2384                        }
2385                        if (is_array($event['recur_exception']))
2386                        {
2387                                foreach($event['recur_exception'] as $key => $timestamp)
2388                                {
2389                                        $event['recur_exception'][$key] = $GLOBALS['server']->date2iso8601($timestamp);
2390                                }
2391                        }
2392                        static $user_cache = array();
2393
2394                        if (!is_object($GLOBALS['phpgw']->perferences))
2395                        {
2396                                $GLOBALS['phpgw']->perferences = CreateObject('phpgwapi.preferences');
2397                        }
2398                        foreach($event['participants'] as $user_id => $status)
2399                        {
2400                                if (!isset($user_cache[$user_id]))
2401                                {
2402                                        $user_cache[$user_id] = array(
2403                                                'name'   => $GLOBALS['phpgw']->common->grab_owner_name($user_id),
2404                                                'email'  => $GLOBALS['phpgw']->perferences->email_address($user_id)
2405                                        );
2406                                }
2407                                $event['participants'][$user_id] = $user_cache[$user_id] + array(
2408                                        'status' => $status,
2409                                );
2410                        }
2411                        if (is_array($event['alarm']))
2412                        {
2413                                foreach($event['alarm'] as $id => $alarm)
2414                                {
2415                                        $event['alarm'][$id]['time'] = $GLOBALS['server']->date2iso8601($alarm['time']);
2416                                        if ($alarm['owner'] != $GLOBALS['phpgw_info']['user']['account_id'])
2417                                        {
2418                                                unset($event['alarm'][$id]);
2419                                        }
2420                                }
2421                        }
2422                        $event['category'] = $GLOBALS['server']->cats2xmlrpc(explode(',',$event['category']));
2423
2424                        // using access={public|privat} in all modules via xmlrpc
2425                        $event['access'] = $event['public'] ? 'public' : 'privat';
2426                        unset($event['public']);
2427
2428                        return $event;
2429                }
2430
2431                /* Begin Appsession Data */
2432                function store_to_appsession($event)
2433                {
2434                        $GLOBALS['phpgw']->session->appsession('entry','resources',$event);
2435                }
2436
2437                function restore_from_appsession()
2438                {
2439//echo "quees";
2440                        $this->event_init();
2441                        $event = $GLOBALS['phpgw']->session->appsession('entry','resources');
2442//echo "quees".$event;
2443                        //$this->so->cal->event = $event;
2444                        return $event;
2445                }
2446                /* End Appsession Data */
2447
2448                /* Begin of SO functions */
2449                function get_cached_event()
2450                {
2451                        return "";//$this->so->get_cached_event();
2452                }
2453
2454                function add_attribute($var,$value,$index='**(**')
2455                {
2456                        //$this->so->add_attribute($var,$value,$index);
2457                }
2458
2459                function event_init()
2460                {
2461                        //$this->so->event_init();
2462                }
2463
2464                function set_start($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2465                {
2466                        //$this->so->set_start($year,$month,$day,$hour,$min,$sec);
2467                }
2468
2469                function set_end($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2470                {
2471                        //$this->so->set_end($year,$month,$day,$hour,$min,$sec);
2472                }
2473
2474                function set_title($title='')
2475                {
2476                        //$this->so->set_title($title);
2477                }
2478
2479                function set_description($description='')
2480                {
2481                        //$this->so->set_description($description);
2482                }
2483
2484                function set_description1($description1='')
2485                {
2486                        //$this->so->set_description1($description1);
2487                }
2488function set_participants1($participants1='')
2489                {
2490                        //$this->so->set_participants1($participants1);
2491                }
2492                function set_ex_participants($ex_participants='')
2493                {
2494                        //$this->so->set_ex_participants($ex_participants);
2495                }
2496
2497                function set_class($class)
2498                {
2499                        //$this->so->set_class($class);
2500                }
2501
2502                function set_category($category='')
2503                {
2504                        //$this->so->set_category($category);
2505                }
2506
2507                function set_alarm($alarm)
2508                {
2509                        //$this->so->set_alarm($alarm);
2510                }
2511
2512                function set_recur_none()
2513                {
2514                        //$this->so->set_recur_none();
2515                }
2516
2517                function set_recur_daily($year,$month,$day,$interval)
2518                {
2519                        //$this->so->set_recur_daily($year,$month,$day,$interval);
2520                }
2521
2522                function set_recur_weekly($year,$month,$day,$interval,$weekdays)
2523                {
2524                        //$this->so->set_recur_weekly($year,$month,$day,$interval,$weekdays);
2525                }
2526
2527                function set_recur_monthly_mday($year,$month,$day,$interval)
2528                {
2529                        //$this->so->set_recur_monthly_mday($year,$month,$day,$interval);
2530                }
2531
2532                function set_recur_monthly_wday($year,$month,$day,$interval)
2533                {
2534                        //$this->so->set_recur_monthly_wday($year,$month,$day,$interval);
2535                }
2536
2537                function set_recur_yearly($year,$month,$day,$interval)
2538                {
2539                        //$this->so->set_recur_yearly($year,$month,$day,$interval);
2540                }
2541                /* End of SO functions */
2542
2543                function prepare_matrix($interval,$increment,$part,$fulldate)
2544                {
2545                        for($h=0;$h<24;$h++)
2546                        {
2547                                for($m=0;$m<$interval;$m++)
2548                                {
2549                                        $index = (($h * 10000) + (($m * $increment) * 100));
2550                                        $time_slice[$index]['marker'] = '&nbsp';
2551                                        $time_slice[$index]['description'] = '';
2552$time_slice[$index]['description1'] = '';
2553                                }
2554                        }
2555                        foreach($this->cached_events[$fulldate] as $event)
2556                        {
2557                                if ($event['participants'][$part] == 'R')
2558                                {
2559                                        continue;       // dont show rejected invitations, as they are free time
2560                                }
2561                                $eventstart = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset);
2562                                $eventend = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset);
2563                                $start = ($eventstart['hour'] * 10000) + ($eventstart['minute'] * 100);
2564                                $starttemp = $this->splittime("$start",False);
2565                                $subminute = 0;
2566                                for($m=0;$m<$interval;$m++)
2567                                {
2568                                        $minutes = $increment * $m;
2569                                        if((int)$starttemp['minute'] > $minutes && (int)$starttemp['minute'] < ($minutes + $increment))
2570                                        {
2571                                                $subminute = ($starttemp['minute'] - $minutes) * 100;
2572                                        }
2573                                }
2574                                $start -= $subminute;
2575                                $end =  ($eventend['hour'] * 10000) + ($eventend['minute'] * 100);
2576                                $endtemp = $this->splittime("$end",False);
2577                                $addminute = 0;
2578                                for($m=0;$m<$interval;$m++)
2579                                {
2580                                        $minutes = ($increment * $m);
2581                                        if($endtemp['minute'] < ($minutes + $increment) && $endtemp['minute'] > $minutes)
2582                                        {
2583                                                $addminute = ($minutes + $increment - $endtemp['minute']) * 100;
2584                                        }
2585                                }
2586                                $end += $addminute;
2587                                $starttemp = $this->splittime("$start",False);
2588                                $endtemp = $this->splittime("$end",False);
2589
2590                                for($h=$starttemp['hour'];$h<=$endtemp['hour'];$h++)
2591                                {
2592                                        $startminute = 0;
2593                                        $endminute = $interval;
2594                                        $hour = $h * 10000;
2595                                        if($h == (int)$starttemp['hour'])
2596                                        {
2597                                                $startminute = ($starttemp['minute'] / $increment);
2598                                        }
2599                                        if($h == (int)$endtemp['hour'])
2600                                        {
2601                                                $endminute = ($endtemp['minute'] / $increment);
2602                                        }
2603                                        $private = $this->is_private($event,$part);
2604                                        $time_display = $GLOBALS['phpgw']->common->show_date($eventstart['raw'],$this->users_timeformat).'-'.$GLOBALS['phpgw']->common->show_date($eventend['raw'],$this->users_timeformat);
2605                                        $time_description = '('.$time_display.') '.$this->get_short_field($event,$private,'title').$this->display_status($event['participants'][$part]);
2606                                        for($m=$startminute;$m<$endminute;$m++)
2607                                        {
2608                                                $index = ($hour + (($m * $increment) * 100));
2609                                                $time_slice[$index]['marker'] = '-';
2610                                                $time_slice[$index]['description'] = $time_description;
2611                                                $time_slice[$index]['id'] = $event['id'];
2612                                        }
2613                                }
2614                        }
2615                        return $time_slice;
2616                }
2617
2618                /*!
2619                @function set_status
2620                @abstract set the participant response $status for event $cal_id and notifies the owner of the event
2621                */
2622                function set_status($cal_id,$status)
2623                {
2624                        $status2msg = array(
2625                                REJECTED  => MSG_REJECTED,
2626                                TENTATIVE => MSG_TENTATIVE,
2627                                ACCEPTED  => MSG_ACCEPTED
2628                        );
2629                        if (!isset($status2msg[$status]))
2630                        {
2631                                return False;
2632                        }
2633                        $event = "";//$this->so->read_entry($cal_id);
2634                        $account_id = $GLOBALS['phpgw_info']['user']['account_id'];
2635                        if(($status2msg[$status] == "5" && $event['participants'][$account_id] == "A") ||
2636                         ($status2msg[$status] == "3" && $event['participants'][$account_id] == "R")) {
2637                                return True;
2638                        }
2639                        //$this->so->set_status($cal_id,$status);
2640                        $event = "";//$this->so->read_entry($cal_id);
2641                        $this->send_update($status2msg[$status],$event['participants'],$event);
2642
2643                }
2644
2645                /*!
2646                @function update_requested
2647                @abstract checks if $userid has requested (in $part_prefs) updates for $msg_type
2648                @syntax update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2649                @param $userid numerical user-id
2650                @param $part_prefs preferces of the user $userid
2651                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2652                @param $old_event Event before the change
2653                @param $new_event Event after the change
2654                @returns 0 = no update requested, > 0 update requested
2655                */
2656                function update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2657                {
2658                        if ($msg_type == MSG_ALARM)
2659                        {
2660                                return True;    // always True for now
2661                        }
2662                        $want_update = 0;
2663
2664                        // the following switch fall-through all cases, as each included the following too
2665                        //
2666                        $msg_is_response = $msg_type == MSG_REJECTED || $msg_type == MSG_ACCEPTED || $msg_type == MSG_TENTATIVE;
2667
2668                        switch($ru = $part_prefs['resources']['receive_updates'])
2669                        {
2670                                case 'responses':
2671                                        if ($msg_is_response)
2672                                        {
2673                                                ++$want_update;
2674                                        }
2675                                case 'modifications':
2676                                        if ($msg_type == MSG_MODIFIED)
2677                                        {
2678                                                ++$want_update;
2679                                        }
2680                                case 'time_change_4h':
2681                                case 'time_change':
2682                                        $diff = max(abs($this->maketime($old_event['start'])-$this->maketime($new_event['start'])),
2683                                                abs($this->maketime($old_event['end'])-$this->maketime($new_event['end'])));
2684                                        $check = $ru == 'time_change_4h' ? 4 * 60 * 60 - 1 : 0;
2685                                        if ($msg_type == MSG_MODIFIED && $diff > $check)
2686                                        {
2687                                                ++$want_update;
2688                                        }
2689                                case 'add_cancel':
2690                                        if ($old_event['owner'] == $userid && $msg_is_response ||
2691                                                $msg_type == MSG_DELETED || $msg_type == MSG_ADDED)
2692                                        {
2693                                                ++$want_update;
2694                                        }
2695                                        break;
2696                                case 'no':
2697                                        break;
2698                        }
2699                        //echo "<p>boresources::update_requested(user=$userid,pref=".$part_prefs['resources']['receive_updates'] .",msg_type=$msg_type,".($old_event?$old_event['title']:'False').",".($old_event?$old_event['title']:'False').") = $want_update</p>\n";
2700                        return $want_update > 0;
2701                }
2702
2703        function create_vcard($event_array)
2704        {
2705        if(!is_array($event_array))
2706                return null;
2707        $tmpattach="BEGIN:Vresources\n"
2708        ."PRODID:-//Expresso Livre//resources//EN\n"
2709        ."VERSION:1.0\n";
2710                foreach ($event_array as $event)
2711                {
2712                        // It translates int to string
2713                        if (!is_object($event) && !is_array($event) || !array_key_exists  ('end', $event))
2714                                $event = $event_array;
2715                        if ( $event['end']['month'] < 10 )
2716                                $end_event_month="0".$event['end']['month'];
2717                        else
2718                                $end_event_month=$event['end']['month'];
2719                        if ( $event['start']['month'] < 10 )
2720                                $start_event_month="0".$event['start']['month'];
2721                        else
2722                                $start_event_month=$event['start']['month'];
2723                        if ( $event['end']['mday'] < 10 )
2724                                $end_event_day="0".$event['end']['mday'];
2725                        else
2726                                $end_event_day=$event['end']['mday'];
2727                        if ( $event['start']['mday'] < 10 )
2728                                $start_event_day="0".$event['start']['mday'];
2729                        else
2730                                $start_event_day=$event['start']['mday'];
2731                        if ( $event['start']['hour'] < 10)
2732                                $start_event_hour="0".$event['start']['hour'];
2733                        else
2734                                $start_event_hour=$event['start']['hour'];
2735                        if ( $event['end']['hour'] < 10)
2736                                $end_event_hour="0".$event['end']['hour'];
2737                        else
2738                                $end_event_hour=$event['end']['hour'];
2739                               
2740                        if ( $event['start']['min'] < 10)
2741                                $start_event_min="0".$event['start']['min'];
2742                        else
2743                                $start_event_min=$event['start']['min'];
2744                        if ( $event['end']['min'] < 10)
2745                                $end_event_min="0".$event['end']['min'];
2746                        else
2747                                $end_event_min=$event['end']['min'];   
2748               
2749
2750                        $tmpattach.="BEGIN:VEVENT\n"
2751                        ."DTSTART:".$event['start'][year].$start_event_month.$start_event_day."T".$start_event_hour.$start_event_min."00Z\n"
2752                        ."DTEND:".$event[end][year].$end_event_month.$end_event_day."T".$end_event_hour.$end_event_min."00Z\n"
2753                        ."UID:Expresso-".$event[id].$event[uid]."\n"
2754                        ."LAST-MODIFIED:".time()."\n"
2755                        ."DESCRIPTION:".$event[description]."\n"
2756."DESCRIPTION1:".$event[description1]."\n"
2757."PARTICIPANTS1:".$event[participants1]."\n"
2758                        ."SUMMARY:".$event[title]."\n"
2759                        ."LOCATION:".$event[location]."\n"
2760                        ."END:VEVENT"."\n";
2761                }
2762                        $tmpattach.="END:Vresources\n";
2763                        return $tmpattach;
2764}
2765
2766                /*!
2767                @function send_update
2768                @abstract sends update-messages to certain participants of an event
2769                @syntax send_update($msg_type,$to_notify,$old_event,$new_event=False)
2770                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2771                @param $to_notify array with numerical user-ids as keys (!) (value is not used)
2772                @param $old_event Event before the change
2773                @param $new_event Event after the change
2774                */
2775                function send_update($msg_type,$to_notify,$old_event,$new_event=False,$user=False)
2776                {
2777                       
2778                        //echo "<p>boresources::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";
2779                        if (!is_array($to_notify))
2780                        {
2781                                $to_notify = array();
2782                        }
2783                        $owner = $old_event ? $old_event['owner'] : $new_event['owner'];
2784                        if ($owner && !isset($to_notify[$owner]) && $msg_type != MSG_ALARM)
2785                        {
2786                                $to_notify[$owner] = 'owner';   // always include the event-owner
2787                        }
2788                        $version = $GLOBALS['phpgw_info']['apps']['resources']['version'];
2789
2790                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences();
2791                        $sender = $GLOBALS['phpgw_info']['user']['email'];
2792
2793                        $temp_tz_offset = $this->prefs['common']['tz_offset'];
2794                        $temp_timeformat = $this->prefs['common']['timeformat'];
2795                        $temp_dateformat = $this->prefs['common']['dateformat'];
2796
2797                        $tz_offset = ((60 * 60) * (int)$temp_tz_offset);
2798
2799                        if($old_event != False)
2800                        {
2801                                $t_old_start_time = $this->maketime($old_event['start']);
2802                                if($t_old_start_time < (time() - 86400))
2803                                {
2804                                        return False;
2805                                }
2806                        }
2807
2808                        $temp_user = $GLOBALS['phpgw_info']['user'];
2809
2810                        if (!$user)
2811                        {
2812                                $user = $this->owner;
2813                        }
2814                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences($user);
2815
2816                        $event = $msg_type == MSG_ADDED || $msg_type == MSG_MODIFIED ? $new_event : $old_event;
2817                        if($old_event != False)
2818                        {
2819                                $old_starttime = $t_old_start_time - $GLOBALS['phpgw']->datetime->tz_offset;
2820                        }
2821                        $starttime = $this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
2822                        $endtime   = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
2823
2824                        switch($msg_type)
2825                        {
2826                                case MSG_DELETED:
2827                                        $action = lang('Canceled');
2828                                        $msg = 'Canceled';
2829                                        $msgtype = '"resources";';
2830                                        $method = 'cancel';
2831                                        $typesend = 1;
2832                                        break;
2833                                case MSG_MODIFIED:
2834                                        $action = lang('Modified');
2835                                        $msg = 'Modified';
2836                                        $msgtype = '"resources"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2837                                        $method = 'request';
2838                                        $typesend = 2;
2839                                        break;
2840                                case MSG_ADDED:
2841                                        $action = lang('Added');
2842                                        $msg = 'Added';
2843                                        $msgtype = '"resources"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2844                                        $method = 'request';
2845                                        $typesend = 3;
2846                                        break;
2847                                case MSG_REJECTED:
2848                                        $action = lang('Rejected');
2849                                        $msg = 'Response';
2850                                        $msgtype = '"resources";';
2851                                        $method = 'reply';
2852                                        $typesend = 4;
2853                                        break;
2854                                case MSG_TENTATIVE:
2855                                        $action = lang('Tentative');
2856                                        $msg = 'Response';
2857                                        $msgtype = '"resources";';
2858                                        $method = 'reply';
2859                                        $typesend = 5;
2860                                        break;
2861                                case MSG_ACCEPTED:
2862                                        $action = lang('Accepted');
2863                                        $msg = 'Response';
2864                                        $msgtype = '"resources";';
2865                                        $method = 'reply';
2866                                        $typesend = 6;
2867                                        break;
2868                                case MSG_ALARM:
2869                                        $action = lang('Alarm');
2870                                        $msg = 'Alarm';
2871                                        $msgtype = '"resources";';
2872                                        $method = 'publish';    // duno if thats right
2873                                        $typesend = 7;
2874                                        break;
2875                                default:
2876                                        $method = 'publish';
2877                                        $typesend = 8;
2878                        }
2879                        $notify_msg = $this->prefs['resources']['notify'.$msg];
2880                        if (empty($notify_msg))
2881                        {
2882                                $notify_msg = $this->prefs['resources']['notifyAdded']; // use a default
2883                        }
2884                        $details = array(                       // event-details for the notify-msg
2885                                'id'          => $msg_type == MSG_ADDED ? $new_event['id'] : $old_event['id'],
2886                                'action'      => $action,
2887                        );
2888                        $event_arr = $this->event2array($event);
2889                        foreach($event_arr as $key => $val)
2890                        {
2891                                $details[$key] = $val['data'];
2892                        }
2893                       
2894                        $details['participants'] = implode("\n",$details['participants']);
2895
2896                        $details['link'] = $GLOBALS['phpgw_info']['server']['webserver_url'].'/index.php?menuaction=resources.uiresources.view&cal_id='.$event['id'];
2897                        // if url is only a path, try guessing the rest ;-)
2898                        if ($GLOBALS['phpgw_info']['server']['webserver_url'][0] == '/')
2899                        {
2900                                $details['link'] = ($GLOBALS['phpgw_info']['server']['enforce_ssl'] ? 'https://' : 'http://').
2901                                        ($GLOBALS['phpgw_info']['server']['hostname'] ? $GLOBALS['phpgw_info']['server']['hostname'] : 'localhost').
2902                                        $details['link'];
2903                        }
2904                       
2905                        //Seta o email usando phpmailer
2906                        define('PHPGW_INCLUDE_ROOT','../');     
2907                        define('PHPGW_API_INC','../phpgwapi/inc');     
2908                        include_once(PHPGW_API_INC.'/class.phpmailer.inc.php');
2909                        $mail = new PHPMailer();
2910                        $mail->IsSMTP();
2911                        $boemailadmin = CreateObject('emailadmin.bo');
2912                        $emailadmin_profile = $boemailadmin->getProfileList();
2913                        $emailadmin = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
2914               
2915                        $mail->Host = $emailadmin['smtpServer'];
2916                        $mail->Port = $emailadmin['smtpPort'];
2917                        $mail->From = $GLOBALS['phpgw']->preferences->values['email'];
2918                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
2919                        $mail->IsHTML(true);
2920
2921                        // Aqui ï¿œ enviado o email
2922                        foreach($to_notify as $userid => $statusid)
2923                        {
2924                                $mail->ClearAttachments();
2925                               
2926                                $userid = (int)$userid;
2927
2928                                if ($statusid == 'R' || $GLOBALS['phpgw']->accounts->get_type($userid) == 'g')
2929                                {
2930                                        continue;       // dont notify rejected participants
2931                                }
2932                                if($userid != $GLOBALS['phpgw_info']['user']['account_id'] ||  $msg_type == MSG_ALARM)
2933                                {
2934                                        print_debug('Msg Type',$msg_type);
2935                                        print_debug('UserID',$userid);
2936
2937                                        $preferences = CreateObject('phpgwapi.preferences',$userid);
2938                                        $part_prefs = $preferences->read_repository();
2939
2940                                        if (!$this->update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event))
2941                                        {
2942                                                continue;
2943                                        }
2944                                        $GLOBALS['phpgw']->accounts->get_account_name($userid,$lid,$details['to-firstname'],$details['to-lastname']);
2945                                        $details['to-fullname'] = $GLOBALS['phpgw']->common->display_fullname('',$details['to-firstname'],$details['to-lastname']);
2946
2947                                        $to = $preferences->email_address($userid);
2948                                       
2949                                        if (empty($to) || $to[0] == '@' || $to[0] == '$')       // we have no valid email-address
2950                                        {
2951                                                //echo "<p>boresources::send_update: Empty email adress for user '".$details['to-fullname']."' ==> ignored !!!</p>\n";
2952                                                continue;
2953                                        }
2954                                        print_debug('Email being sent to',$to);
2955
2956                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $part_prefs['common']['tz_offset'];
2957                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $part_prefs['common']['timeformat'];
2958                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $part_prefs['common']['dateformat'];
2959
2960                                        $GLOBALS['phpgw']->datetime->tz_offset = ((60 * 60) * (int)$GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset']);
2961
2962                                        if($old_starttime)
2963                                        {
2964                                                $details['olddate'] = $GLOBALS['phpgw']->common->show_date($old_starttime);
2965                                        }
2966                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
2967                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
2968                                       
2969                                       
2970                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
2971                                       
2972                                        switch($part_prefs['resources']['update_format'])
2973                                        {
2974                                                case  'extended':
2975                                                        //$body .= "\n\n".lang('Event Details follow').":\n";
2976                                                        $body = '';
2977                                                        $body .= "<br>".lang('Event Details follow')." :: ";
2978                                                        foreach($event_arr as $key => $val)
2979                                                        {
2980                                                                // titulo
2981                                                                if($key =='title')
2982                                                                {
2983                                                                        $var1 = $val['field'];
2984                                                                        $vardata1 = $details[$key];
2985                                                                }
2986                                                                //descricao
2987                                                                if($key =='description')
2988                                                                {
2989                                                                        $var2 = $val['field'];
2990                                                                        $vardata2 = $details[$key];
2991                                                                }
2992if($key =='description1')
2993                                                                {
2994                                                                        $var2 = $val['field'];
2995                                                                        $vardata2 = $details[$key];
2996                                                                }
2997
2998if($key =='participants1')
2999                                                                {
3000                                                                        $var2 = $val['field'];
3001                                                                        $vardata2 = $details[$key];
3002                                                                }
3003
3004                                                                //dt inicio
3005                                                                if($key =='startdate')
3006                                                                {
3007                                                                        switch(trim($part_prefs['common']['dateformat']))
3008                                                                        {
3009                                                                               
3010                                                                                case ($part_prefs['common']['dateformat'] === "m/d/Y" || $part_prefs['common']['dateformat'] === "m-d-Y" || $part_prefs['common']['dateformat'] === "m.d.Y"):
3011                                                                                        $var3 = $val['field'];
3012                                                                                        $vardata3 = $details[$key];
3013                                                                                        $newmounth3 = substr($vardata3,0,2);
3014                                                                                        $newday3 = substr($vardata3,3,2);
3015                                                                                        $newyear3 = substr($vardata3,6,4);
3016                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3017                                                                                        break;
3018                                                                                       
3019                                                                                case    ($part_prefs['common']['dateformat'] === "Y/d/m" || $part_prefs['common']['dateformat'] === "Y-d-m" || $part_prefs['common']['dateformat'] === "Y.d.m"):
3020
3021                                                                                        $var3 = $val['field'];
3022                                                                                        $vardata3 = $details[$key];
3023                                                                                        $newyear3 = substr($vardata3,0,4);
3024                                                                                        $newday3 = substr($vardata3,5,2);
3025                                                                                        $newmounth3 = substr($vardata3,8,2);
3026                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3027                                                                                        break;
3028
3029                                                                                case ($part_prefs['common']['dateformat'] === "Y/m/d" || $part_prefs['common']['dateformat'] === "Y-m-d" || $part_prefs['common']['dateformat'] === "Y.m.d"):
3030
3031                                                                                        $var3 = $val['field'];
3032                                                                                        $vardata3 = $details[$key];
3033                                                                                        $newyear3 = substr($vardata3,0,4);
3034                                                                                        $newmounth3 = substr($vardata3,5,2);
3035                                                                                        $newday3 = substr($vardata3,8,2);
3036                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3037                                                                                        break;
3038
3039                                                                                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"):
3040                                                                               
3041                                                                                        $var3 = $val['field'];
3042                                                                                        $vardata3 = $details[$key];
3043                                                                                        $newday3 = substr($vardata3,0,2);
3044                                                                                        $newmounth3 = substr($vardata3,3,2);
3045                                                                                        $newyear3 = substr($vardata3,6,4);
3046                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3047                                                                                        break;
3048                                                                       
3049                                                                        }
3050                                                                       
3051                                                                }
3052                                                                //dt final
3053                                                                if($key =='enddate')
3054                                                                {
3055                                                                        $var4 = $val['field'];
3056                                                                        $vardata4 = $details[$key];
3057                                                                }
3058                                                                //localizacao
3059                                                                if($key =='location')
3060                                                                {
3061                                                                        $var8 = $val['field'];
3062                                                                        $vardata8 = $details[$key];
3063                                                                }
3064                                                                //participantes
3065                                                                if($key =='participants')
3066                                                                {
3067                                                                        $var5 = $val['field'];
3068                                                                        foreach($val['data'] as $NewKey => $NewVal)
3069                                                                        {
3070                                                                                //Research inside of ldap ( Pesquisa dentro do ldap )
3071                                                                                $newvalue = "";//$this->so->search_uidNumber($to);
3072                                                                                foreach($newvalue as $tmp)
3073                                                                                {
3074                                                                                        $tmpmail = $tmp['mail'][0];
3075                                                                                        $tmpuid = $tmp['uidnumber'][0];
3076                                                                                        if( trim($tmpmail) == trim($to) & trim($tmpuid) == trim($NewKey))
3077                                                                                        {
3078                                                                                                        if($typesend == 3)
3079                                                                                                        {
3080
3081                                                                                                                $lang1 = lang("To See Commitment");
3082                                                                                                                $varbuttom = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=resources.uiresources.view&cal_id=$event[id]&date=$newall3' method='POST'>
3083                                                                                                                                                                  <input type='submit' value='$lang1'>
3084                                                                                                                                                                   </form>";
3085                                                                                                                $lang2 = lang("To accept");
3086                                                                                                                $varbuttom1 ="<input type='submit' value='$lang2' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=resources.uiresources.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\")'>";
3087
3088                                                                                                                $lang3 = lang("To reject");
3089                                                                                                                $varbuttom2 ="<input type='submit' value='$lang3' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=resources.uiresources.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\")'>";
3090                                                                                                               
3091                                                                                                                $lang4 = lang("Alarm");
3092                                                                                                                $varbuttom3 = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=resources.uialarm.manager method='POST'>
3093                                                                                                                                                                  <input type='submit' value='$lang4'>
3094                                                                                                                                                                  <input type='hidden' name='cal_id' value=$event[id]>
3095                                                                                                                                                                   </form>";
3096                                                                                                        }
3097                                                                                                        else
3098                                                                                                        {
3099                                                                                                                        $varbuttom  = "";
3100                                                                                                                        $varbuttom1 = "";
3101                                                                                                                        $varbuttom2 = "";
3102                                                                                                                        $varbuttom3 = "";
3103                                                                                                        }
3104                                                                                        }
3105                                                                                        // It only mounts variavel with the name of the participants of the list ( Monta a variavel somente com o nome dos participantes da lista)
3106                                                                                        if($typesend == 3)
3107                                                                                        {
3108                                                                                                list($tmpvardata5,$tmp2vardata5) = explode("(",$NewVal);
3109                                                                                                $vardata5 = $tmpvardata5."<br>";
3110                                                                                        }
3111                                                                                        else
3112                                                                                        {
3113                                                                                                $vardata5 = $NewVal."<br>";
3114                                                                                        }
3115                                                                               
3116                                                                                }
3117                                                                                $vardata6 .= $vardata5;
3118                                                                                unset($vardata5);
3119                                                                        }
3120                                                                }               
3121                                                        }
3122                                                        //To mount the message as text/html (Para montar a mensagem como text/html - /phpgwapi/inc/class.send.inc.php )
3123                                                        $content_type = "text/html";
3124                                                        //It mounts the body of the message (Monta o corpo da mensagem)
3125                                                       
3126                                                        // A constante PHPGW_APP_TPL nao existe para envio de alarmes (cront, asyncservice).
3127                                                        define ("PHPGW_APP_TPL",PHPGW_API_INC . "/../../resources/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."");
3128                                                       
3129                                                        $body = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
3130                                                        $body->set_file(Array('resources' => 'body_email.tpl'));
3131                                                        $body->set_block('resources','list');
3132                                                        $var = Array(
3133                                                                'script'                        => $script,
3134                                                                'subject'                       => $body1,
3135                                                                'var1'                          => $var1,
3136                                                                'vardata1'                      => $vardata1,
3137                                                                'var2'                          => $var2,
3138                                                                'vardata2'                      => $vardata2,
3139                                                                'var3'                          => $var3,
3140                                                                'vardata3'                      => $vardata3,
3141                                                                'var4'                          => $var4,
3142                                                                'vardata4'                      => $vardata4,
3143                                                                'var5'                          => $var5,
3144                                                                'vardata6'                      => $vardata6,
3145                                                                'var8'                          => $var8,
3146                                                                'vardata8'                      => $vardata8,                                                   
3147                                                                'varbuttom'                     => $varbuttom,
3148                                                                'varbuttom1'            => $varbuttom1,
3149                                                                'varbuttom2'            => $varbuttom2,
3150                                                                'varbuttom3'            => $varbuttom3
3151                                                               
3152                                                        );
3153                                                        $body->set_var($var);
3154                                                        $tmpbody = $body->fp('out','list');
3155                                                                                                               
3156                                                        break;
3157
3158                                                case 'ical':
3159                                                        $content_type = "resources; method=$method; name=resources.ics";
3160/*                                                      if ($body != '')
3161                                                        {
3162                                                                $boundary = '----Message-Boundary';
3163                                                                $body .= "\n\n\n$boundary\nContent-type: text/$content_type\n".
3164                                                                        "Content-Disposition: inline\nContent-transfer-encoding: 7BIT\n\n";
3165                                                                $content_type = '';
3166                                                        }
3167*/
3168                                                        $body = ExecMethod('resources.boiresources.export',array(
3169                                                                'l_event_id'  => $event['id'],
3170                                                                'method'      => $method,
3171                                                                'chunk_split' => False
3172                                                        ));
3173                                                        break;
3174                                        }
3175                                        $mail->AddAddress($to);
3176                                        $mail->Body = $tmpbody;
3177                                        $mail->From = $sender;
3178                                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3179                                        $mail->Sender = $mail->From;
3180                                        $mail->SenderName = $mail->FromName;
3181                                        $mail->Subject = $subject;
3182                                        unset($vardata5);
3183                                        unset($vardata6);
3184                                }
3185                        }
3186
3187                        //Inicializa variï¿œvel de retorno.
3188                        $returncode=true;                       
3189                        if(count($mail->to)) {                         
3190                                // Envia aviso a todos os participantes.
3191                                if(!$mail->Send()) {                           
3192                                        $returncode = false;
3193                                        $errorInfo['participants'] = $mail->ErrorInfo;
3194                                }
3195                                else
3196                                        $returncode =  true;
3197                        }
3198                       
3199                        if(count($to_notify) && $this->ex_participants){
3200                                $mail->ClearAllRecipients();
3201                                $var = explode(",",trim($this->ex_participants));
3202                                $to = array();
3203                                if(!$subject) {
3204                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
3205                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
3206                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
3207                                }
3208                               
3209                                foreach($var as $index => $ex_participant){
3210                                        $ex_participant = trim($ex_participant);
3211                                        $ex_participant = preg_replace('#"(.*)" <(.*)\@(.*)\.(.*)>#','\\2@\\3.\\4',$ex_participant);
3212                                                if($ex_participant)
3213                                                        $to[] = $ex_participant;
3214                                }               
3215                               
3216                                foreach($to as $i => $to_array)
3217                                        $mail->AddAddress($to_array);
3218                               
3219                                $_body = explode("<hr size='1' width='100%'>",$tmpbody);
3220                                $tmpbody = $_body[0] ? $_body[0] : $subject ;
3221                                $tmpbody.= "<br><b>".lang("external participants").":: </b> ".htmlentities($this->ex_participants);
3222                                $tmpbody.= "<br>".lang("Summary").": "."";//$this->so->cal->event[title]."<br>";
3223                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";
3224                                $tmpbody.= "<br><br><hr size='1' width='100%'><font color='red'>"
3225                                .lang("This message was sent by server. You must send a message to sender to confirm this event")."<br>"
3226                                .lang("This is an external event. Even if it added to your expresso its can be changed any time at all")."</font><br>";
3227                               
3228                                if ($GLOBALS['boresources']->so->cal->event[start][month] > 10)
3229                                        $event_month=$GLOBALS['boresources']->so->cal->event[start][month];
3230                                else
3231                                        $event_month="0".$GLOBALS['boresources']->so->cal->event[start][month];
3232                                //attach extern vcard                   
3233                                // define('context','$GLOBALS.boresources.so.cal.event');
3234                                $tmpattach = $this->create_vcard($GLOBALS['boresources']->so->cal->event);
3235                                if($tmpattach){                                 
3236                                        $tmpbody .="<a href='../index.php?menuaction=resources.uiresources.add&date="
3237                                        .$GLOBALS['boresources']->so->cal->event[start][year]
3238                                .$event_month
3239                                .$GLOBALS['boresources']->so->cal->event[start][mday]
3240                                        ."&hour=".$GLOBALS['boresources']->so->cal->event[start][hour]
3241                                        ."&minute=".$GLOBALS['boresources']->so->cal->event[start][min]
3242                                        ."&title=".$GLOBALS['boresources']->so->cal->event['title']
3243                                        ."&description=".$GLOBALS['boresources']->so->cal->event['description']
3244."&description1=".$GLOBALS['boresources']->so->cal->event['description1']
3245."&participants1=".$GLOBALS['boresources']->so->cal->event['participants1']
3246                                        ."&location=".$GLOBALS['boresources']->so->cal->event['location']."'>"
3247                                        ."<h2>".lang("Add to my expresso")."</h2>";
3248                                        $tempdir = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
3249                                        srand((double)microtime()*1000000);
3250                                        $random_number = rand(100000000,999999999);
3251                                        $newfilename = md5(time() . getenv("REMOTE_ADDR") . $random_number );
3252                                        $filename = $tempdir . $newfilename;
3253                                        $attach_fd = fopen($filename,"w+");
3254                                        fwrite($attach_fd,$tmpattach);
3255                                        $mail->AddAttachment($filename, "extern.vcard", "base64", "text/plain"); // "application/octet-stream"
3256                                        fclose($attach_fd);
3257                                }
3258                                $mail->From = $sender;
3259                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3260                                $mail->Sender = $mail->From;
3261                                $mail->SenderName = $mail->FromName;
3262                                $mail->Subject = lang("External event from Expresso");
3263                                $mail->Body = $tmpbody;
3264                                                                                                                                               
3265                                if(!$mail->Send())
3266                                {
3267                                        $returncode=false;
3268                                        $errorInfo['ex_participants'] = $mail->ErrorInfo;
3269                                }
3270                                else
3271                                {
3272                                        $returncode=true;
3273                                }
3274                        }
3275
3276
3277                        if((is_int($this->user) && $this->user != $temp_user['account_id']) ||
3278                                (is_string($this->user) && $this->user != $temp_user['account_lid']))
3279                        {
3280                                $GLOBALS['phpgw_info']['user'] = $temp_user;
3281                        }       
3282
3283                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $temp_tz_offset;
3284                        $GLBOALS['phpgw']->datetime->tz_offset = ((60 * 60) * $temp_tz_offset);
3285                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $temp_timeformat;
3286                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $temp_dateformat;
3287                       
3288                        // Notifica por email o criador do compromisso, com as possï¿œveis falhas.                                             
3289                        if($errorInfo) {
3290                                $tmpbody = "<font color='red'>".lang("The following commitment had problems for DELIVERING the NOTIFICATION messages.").".</font><br>";
3291                                $tmpbody.= "<br>".lang("Summary").": "."";//$this->so->cal->event[title]."<br>";
3292                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";                         
3293                                $tmpbody.= "<br><u>".lang("Failed to delivery")."</u><br>";
3294                                $failed = false;                               
3295                                if(strstr($errorInfo['participants'],"recipients_failed")){
3296                                        $failed = explode("recipients_failed",$errorInfo['participants']);
3297                                        $tmpbody.= lang("to").": ".$failed[1];
3298                                }
3299                                if(strstr($errorInfo['ex_participants'],"recipients_failed")){
3300                                        $failed = explode("recipients_failed",$errorInfo['ex_participants']);
3301                                        $tmpbody.= lang("to").": ".$failed[1];
3302                                }                       
3303                                if(!$failed) {
3304                                        $tmpbody.= lang("Description").":<br>";
3305$tmpbody.= lang("Description1").":<br>";
3306$tmpbody.= lang("participants1").":<br>";
3307                                        $tmpbody.= $errorInfo['participants'];
3308                                        $tmpbody.= "<br>".$errorInfo['ex_participants'];
3309                                }
3310                                $tmpbody.= "<br>".lang("Subject").": ".$subject;
3311                                // Reinicializa o objeto, devido ao erro anterior na entrega.
3312                               
3313                                $mail = new PHPMailer();
3314                                $mail->IsSMTP();
3315                                $mail->Host = $emailadmin['smtpServer'];
3316                                $mail->Port = $emailadmin['smtpPort'];
3317                                $mail->From = $sender;
3318                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3319                                $mail->Sender = $mail->From;
3320                                $mail->SenderName = $mail->FromName;
3321                                $mail->IsHTML(True);
3322                                $mail->Subject = lang("resources event")." - ".lang("email notification");                                                     
3323                                $mail->Body = $tmpbody;                                 
3324                                $mail->AddAddress($sender);
3325                                if(!$mail->Send())                     
3326                                        $returncode = false;
3327                                else
3328                                        $returncode =  true;
3329                        }
3330                        return $returncode;
3331                }
3332               
3333                function send_alarm($alarm)
3334                {
3335                        //echo "<p>boresources::send_alarm("; print_r($alarm); echo ")</p>\n";
3336                       
3337                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->owner = $alarm['owner'];
3338
3339                        if (!$alarm['enabled'] || !$alarm['owner'] || !$alarm['cal_id'] )
3340                        {
3341                                return False;   // event not found
3342                        }
3343                        if ($alarm['all'])
3344                        {
3345                                $to_notify = $event['participants'];
3346                        }
3347                        elseif ($this->check_perms(PHPGW_ACL_READ,$event))      // checks agains $this->owner set to $alarm[owner]
3348                        {
3349                                $to_notify[$alarm['owner']] = 'A';
3350                        }
3351                        else
3352                        {
3353                                return False;   // no rights
3354                        }
3355                        return $this->send_update(MSG_ALARM,$to_notify,$event,False,$alarm['owner']);
3356                }
3357
3358                function get_alarms($event_id)
3359                {
3360                        return "";//$this->so->get_alarm($event_id);
3361                }
3362
3363                function alarm_today($event,$today,$starttime)
3364                {
3365                        $found = False;
3366                        @reset($event['alarm']);
3367                        $starttime_hi = $GLOBALS['phpgw']->common->show_date($starttime,'Hi');
3368                        $t_appt['month'] =$GLOBALS['phpgw']->common->show_date($today,'m');
3369                        $t_appt['mday'] = $GLOBALS['phpgw']->common->show_date($today,'d');
3370                        $t_appt['year'] = $GLOBALS['phpgw']->common->show_date($today,'Y');
3371                        $t_appt['hour'] = $GLOBALS['phpgw']->common->show_date($starttime,'H');
3372                        $t_appt['min']  = $GLOBALS['phpgw']->common->show_date($starttime,'i');
3373                        $t_appt['sec']  = 0;
3374                        $t_time = $this->maketime($t_appt) - $GLOBALS['phpgw']->datetime->tz_offset;
3375                        $y_time = $t_time - 86400;
3376                        $tt_time = $t_time + 86399;
3377                        print_debug('T_TIME',$t_time.' : '.$GLOBALS['phpgw']->common->show_date($t_time));
3378                        print_debug('Y_TIME',$y_time.' : '.$GLOBALS['phpgw']->common->show_date($y_time));
3379                        print_debug('TT_TIME',$tt_time.' : '.$GLOBALS['phpgw']->common->show_date($tt_time));
3380                        while(list($key,$alarm) = each($event['alarm']))
3381                        {
3382                                if($alarm['enabled'])
3383                                {
3384                                        print_debug('TIME',$alarm['time'].' : '.$GLOBALS['phpgw']->common->show_date($alarm['time']).' ('.$event['id'].')');
3385                                        if($event['recur_type'] != MCAL_RECUR_NONE)   /* Recurring Event */
3386                                        {
3387                                                print_debug('Recurring Event');
3388                                                if($alarm['time'] > $y_time && $GLOBALS['phpgw']->common->show_date($alarm['time'],'Hi') < $starttime_hi && $alarm['time'] < $t_time)
3389                                                {
3390                                                        $found = True;
3391                                                }
3392                                        }
3393                                        elseif($alarm['time'] > $y_time && $alarm['time'] < $t_time)
3394                                        {
3395                                                $found = True;
3396                                        }
3397                                }
3398                        }
3399                        print_debug('Found',$found);
3400                        return $found;
3401                }
3402
3403                function prepare_recipients(&$new_event,$old_event)
3404                {
3405                                               
3406                        // Find modified and deleted users.....
3407                        while(list($old_userid,$old_status) = each($old_event['participants']))
3408                        {
3409                                if(isset($new_event['participants'][$old_userid]))
3410                                {
3411                                        print_debug('Modifying event for user',$old_userid);
3412                                        $this->modified[(int)$old_userid] = $new_status;
3413                                }
3414                                else
3415                                {
3416                                        print_debug('Deleting user from the event',$old_userid);
3417                                        $this->deleted[(int)$old_userid] = $old_status;
3418                                }
3419                        }
3420                        // Find new users.....
3421                        while(list($new_userid,$new_status) = each($new_event['participants']))
3422                        {
3423                                if(!isset($old_event['participants'][$new_userid]))
3424                                {
3425                                        print_debug('Adding event for user',$new_userid);
3426                                        $this->added[$new_userid] = 'U';
3427                                        $new_event['participants'][$new_userid] = 'U';
3428                                }
3429                        }
3430                       
3431                        if(count($this->added) > 0 || count($this->modified) > 0 || count($this->deleted) > 0)
3432                        {
3433                                if(count($this->added) > 0)
3434                                {
3435                                        $this->ex_participants = '';
3436                                        $this->send_update(MSG_ADDED,$this->added,'',$new_event);
3437                                }
3438                                if(count($this->modified) > 0)
3439                                {
3440                                        $this->send_update(MSG_MODIFIED,$this->modified,$old_event,$new_event);
3441                                }
3442                                if(count($this->deleted) > 0)
3443                                {
3444                                        $this->ex_participants = '';
3445                                        $this->send_update(MSG_DELETED,$this->deleted,$old_event);
3446                                }
3447                        }
3448                }
3449
3450                function remove_doubles_in_cache($firstday,$lastday)
3451                {
3452                        $already_moved = Array();
3453                        for($v=$firstday;$v<=$lastday;$v++)
3454                        {
3455                                if (!$this->cached_events[$v])
3456                                {
3457                                        continue;
3458                                }
3459                                $cached = $this->cached_events[$v];
3460                                $this->cached_events[$v] = array();
3461                                while (list($g,$event) = each($cached))
3462                                {
3463                                        $end = date('Ymd',$this->maketime($event['end']));
3464                                        print_debug('EVENT',_debug_array($event,False));
3465                                        print_debug('start',$start);
3466                                        print_debug('v',$v);
3467
3468                                        if (!isset($already_moved[$event['id']]) || $event['recur_type'] && $v > $end)
3469                                        {
3470                                                $this->cached_events[$v][] = $event;
3471                                                $already_moved[$event['id']] = 1;
3472                                                print_debug('Event moved');
3473                                        }
3474                                }
3475                        }
3476                }
3477
3478                function get_dirty_entries($lastmod=-1)
3479                {
3480                        $events = false;
3481                        $event_ids = "";//$this->so->cal->list_dirty_events($lastmod);
3482                        if(is_array($event_ids))
3483                        {
3484                                foreach($event_ids as $key => $id)
3485                                {
3486                                        $events[$id] = "";//$this->so->cal->fetch_event($id);
3487                                }
3488                        }
3489                        unset($event_ids);
3490
3491                        $rep_event_ids = "";//$this->so->cal->list_dirty_events($lastmod,$true);
3492                        if(is_array($rep_event_ids))
3493                        {
3494                                foreach($rep_event_ids as $key => $id)
3495                                {
3496                                        $events[$id] = "";//$this->so->cal->fetch_event($id);
3497                                }
3498                        }
3499                        unset($rep_event_ids);
3500
3501                        return $events;
3502                }
3503
3504                function _debug_array($data)
3505                {
3506                        echo '<br>UI:';
3507                        _debug_array($data);
3508                }
3509
3510                /*!
3511                @function rejected_no_show
3512                @abstract checks if event is rejected from user and he's not the owner and dont want rejected
3513                @param $event to check
3514                @returns True if event should not be shown
3515                */
3516                function rejected_no_show($event)
3517                {
3518                        $ret = !$this->prefs['resources']['show_rejected'] &&
3519                                $event['owner'] != $this->owner &&
3520                                $event['participants'][$this->owner] == 'R';
3521                        //echo "<p>rejected_no_show($event[title])='$ret': user=$this->owner, event-owner=$event[owner], status='".$event['participants'][$this->owner]."', show_rejected='".$this->prefs['resources']['show_rejected']."'</p>\n";
3522                        return $ret;
3523                }
3524
3525                /* This is called only by list_cals().  It was moved here to remove fatal error in php5 beta4 */
3526                function list_cals_add($id,&$users,&$groups)
3527                {
3528                        $name = $GLOBALS['phpgw']->common->grab_owner_name($id);
3529                        if (($type = $GLOBALS['phpgw']->accounts->get_type($id)) == 'g')
3530                        {
3531                                $arr = &$groups;
3532                        }
3533                        else
3534                        {
3535                                $arr = &$users;
3536                        }
3537                        $arr[$name] = Array(
3538                                'grantor' => $id,
3539                                'value'   => ($type == 'g' ? 'g_' : '') . $id,
3540                                'name'    => $name
3541                        );
3542                }
3543
3544                /*!
3545                @function list_cals
3546                @abstract generate list of user- / group-resourcess for the selectbox in the header
3547                @returns alphabeticaly sorted array with groups first and then users
3548                */
3549                function list_cals()
3550                {
3551                        $users = $groups = array();
3552                        foreach($this->grants as $id => $rights)
3553                        {
3554                                $this->list_cals_add($id,$users,$groups);
3555                        }
3556                       
3557                        //by JakJr, melhora de performance na abertura da agenda
3558                        /*if ($memberships = $GLOBALS['phpgw']->accounts->membership($GLOBALS['phpgw_info']['user']['account_id']))
3559                        {
3560                                foreach($memberships as $group_info)
3561                                {
3562                                        $this->list_cals_add($group_info['account_id'],$users,$groups);
3563
3564                                        if ($account_perms = $GLOBALS['phpgw']->acl->get_ids_for_location($group_info['account_id'],PHPGW_ACL_READ,'resources'))
3565                                        {
3566                                                foreach($account_perms as $id)
3567                                                {
3568                                                        $this->list_cals_add($id,$users,$groups);
3569                                                }
3570                                        }
3571                                }
3572                        }*/
3573                        uksort($users,'strnatcasecmp');
3574                        uksort($groups,'strnatcasecmp');
3575
3576                        return $users + $groups;        // users first and then groups, both alphabeticaly
3577                }
3578
3579          function translate($key,$vars=false, $not_found='*' )
3580          {
3581            if ($this->async)
3582              return $GLOBALS['phpgw']->translation->translate_async($key, $vars);
3583            return lang($key, $vars);
3584          }
3585
3586                /*!
3587                @function event2array
3588                @abstract create array with name, translated name and readable content of each attributes of an event
3589                @syntax event2array($event,$sep='<br>')
3590                @param $event event to use
3591                @returns array of attributes with fieldname as key and array with the 'field'=translated name \
3592                        'data' = readable content (for participants this is an array !)
3593                */
3594                function event2array($event)
3595                {
3596                       
3597                       
3598                  $var['title'] = Array(
3599                                'field'         => $this->translate('Title'),
3600                                'data'          => $event['title']
3601                        );
3602
3603                        // Some browser add a \n when its entered in the database. Not a big deal
3604                        // this will be printed even though its not needed.
3605                        $var['description'] = Array(
3606                                'field' => $this->translate('Description'),
3607                                'data'  => $event['description']
3608                        );
3609$var['description1'] = Array(
3610                                'field' => $this->translate('Description1'),
3611                                'data'  => $event['description1']
3612                        );
3613
3614
3615$var['participants1'] = Array(
3616                                'field' => $this->translate('participants1'),
3617                                'data'  => $event['participants1']
3618                        );
3619
3620                        $var['ex_participants'] = Array(
3621                                'field' => $this->translate('External Participants'),
3622                                'data'  => $event['ex_participants']
3623                        );
3624                       
3625                        $cats = Array();
3626                        $this->cat->categories($this->bo->owner,'resources');
3627                        if(strpos($event['category'],','))
3628                        {
3629                                $cats = explode(',',$event['category']);
3630                        }
3631                        else
3632                        {
3633                                $cats[] = $event['category'];
3634                        }
3635                        foreach($cats as $cat_id)
3636                        {
3637                                list($cat) = $this->cat->return_single($cat_id);
3638                                $cat_string[] = $cat['name'];
3639                        }
3640                        $var['category'] = Array(
3641                                'field' => $this->translate('Category'),
3642                                'data'  => implode(', ',$cat_string)
3643                        );
3644
3645                        $var['location'] = Array(
3646                                'field' => $this->translate('Location'),
3647                                'data'  => $event['location']
3648                        );
3649
3650                        $var['startdate'] = Array(
3651                                'field' => $this->translate('Start Date/Time'),
3652                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset),
3653                        );
3654
3655                        $var['enddate'] = Array(
3656                                'field' => $this->translate('End Date/Time'),
3657                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset)
3658                        );
3659
3660                        $pri = Array(
3661                                1       => lang('Low'),
3662                                2       => lang('Normal'),
3663                                3       => lang('High')
3664                        );
3665                        $var['priority'] = Array(
3666                                'field' => lang('Priority'),
3667                                'data'  => $pri[$event['priority']]
3668                        );
3669
3670                        $var['owner'] = Array(
3671                                'field' => lang('Created By'),
3672                                'data'  => $GLOBALS['phpgw']->common->grab_owner_name($event['owner'])
3673                        );
3674
3675                        $var['updated'] = Array(
3676                                'field' => lang('Updated'),
3677                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['modtime']) - $GLOBALS['phpgw']->datetime->tz_offset)
3678                        );
3679
3680                        $var['access'] = Array(
3681                                'field' => lang('Access'),
3682                                'data'  => $event['public'] ? lang('Public') : lang('Private')
3683                        );
3684
3685                        if(@isset($event['groups'][0]))
3686                        {
3687                                $cal_grps = '';
3688                                for($i=0;$i<count($event['groups']);$i++)
3689                                {
3690                                        if($GLOBALS['phpgw']->accounts->exists($event['groups'][$i]))
3691                                        {
3692                                                $cal_grps .= ($i>0?'<br>':'').$GLOBALS['phpgw']->accounts->id2name($event['groups'][$i]);
3693                                        }
3694                                }
3695
3696                                $var['groups'] = Array(
3697                                        'field' => lang('Groups'),
3698                                        'data'  => $cal_grps
3699                                );
3700                        }
3701
3702                        $participants = array();
3703                        foreach($event['participants'] as $user => $short_status)
3704                        {
3705                                if($GLOBALS['phpgw']->accounts->exists($user))
3706                                {
3707                                        $participants[$user] = $GLOBALS['phpgw']->common->grab_owner_name($user).' ('.$this->get_long_status($short_status).')';
3708                                }
3709                        }
3710                        $var['participants'] = Array(
3711                                'field' => $this->translate('Participants'),
3712                                'data'  => $participants
3713                        );
3714
3715                        // Repeated Events
3716                        if($event['recur_type'] != MCAL_RECUR_NONE)
3717                        {
3718                                $str = lang($this->rpt_type[$event['recur_type']]);
3719
3720                                $str_extra = array();
3721                                if ($event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['month'] != 0 && $event['recur_enddate']['year'] != 0)
3722                                {
3723                                        $recur_end = $this->maketime($event['recur_enddate']);
3724                                        if($recur_end != 0)
3725                                        {
3726                                                $recur_end -= $GLOBALS['phpgw']->datetime->tz_offset;
3727                                                $str_extra[] = lang('ends').': '.lang($GLOBALS['phpgw']->common->show_date($recur_end,'l')).', '.$this->long_date($recur_end).' ';
3728                                        }
3729                                }
3730                                // only weekly uses the recur-data (days) !!!
3731                                if($event['recur_type'] == MCAL_RECUR_WEEKLY)
3732                                {
3733                                        $repeat_days = array();
3734                                        foreach ($this->rpt_day as $mcal_mask => $dayname)
3735                                        {
3736                                                if ($event['recur_data'] & $mcal_mask)
3737                                                {
3738                                                        $repeat_days[] = lang($dayname);
3739                                                }
3740                                        }
3741                                        if(count($repeat_days))
3742                                        {
3743                                                $str_extra[] = lang('days repeated').': '.implode(', ',$repeat_days);
3744                                        }
3745                                }
3746                                if($event['recur_interval'] != 0)
3747                                {
3748                                        $str_extra[] = lang('Interval').': '.$event['recur_interval'];
3749                                }
3750
3751                                if(count($str_extra))
3752                                {
3753                                        $str .= ' ('.implode(', ',$str_extra).')';
3754                                }
3755
3756                                $var['recure_type'] = Array(
3757                                        'field' => lang('Repetition'),
3758                                        'data'  => $str,
3759                                );
3760                        }
3761
3762                        if (!isset($this->fields))
3763                        {
3764                                $this->custom_fields = CreateObject('resources.bocustom_fields');
3765                                $this->fields = &$this->custom_fields->fields;
3766                                $this->stock_fields = &$this->custom_fields->stock_fields;
3767                        }
3768                        foreach($this->fields as $field => $data)
3769                        {
3770                                if (!$data['disabled'])
3771                                {
3772                                        if (isset($var[$field]))
3773                                        {
3774                                                $sorted[$field] = $var[$field];
3775                                        }
3776                                        elseif (!isset($this->stock_fields[$field]) && strlen($event[$field]))  // Custom field
3777                                        {
3778                                                $lang = lang($name = substr($field,1));
3779                                                $sorted[$field] = array(
3780                                                        'field' => $lang == $name.'*' ? $name : $lang,
3781                                                        'data'  => $event[$field]
3782                                                );
3783                                        }
3784                                }
3785                                unset($var[$field]);
3786                        }
3787                        foreach($var as $name => $v)
3788                        {
3789                                $sorted[$name] = $v;
3790
3791                        }
3792                        return $sorted;
3793                }
3794
3795                /*!
3796                @function check_set_default_prefs
3797                @abstract sets the default prefs, if they are not already set (on a per pref. basis)
3798                @note It sets a flag in the app-session-data to be called only once per session
3799                */
3800                function check_set_default_prefs()
3801                {
3802                        if (($set = $GLOBALS['phpgw']->session->appsession('default_prefs_set','resources')))
3803                        {
3804                                return;
3805                        }
3806                        $GLOBALS['phpgw']->session->appsession('default_prefs_set','resources','set');
3807
3808                        //$default_prefs = $GLOBALS['phpgw']->preferences->default['resources']; jakjr
3809
3810                        $subject = $this->translate('resources Event') . ' - $$action$$: $$startdate$$ $$title$$'."\n";
3811                        $defaults = array(
3812                                'defaultresources' => 'week',
3813                                'mainscreen_showevents' => '0',
3814                                'summary'         => 'no',
3815                                'receive_updates' => 'no',
3816                                'update_format'   => 'extended',        // leave it to extended for now, as iCal kills the message-body
3817                                'notifyAdded'     => $subject . $this->translate ('You have a meeting scheduled for %1',array('$$startdate$$')),
3818                                'notifyCanceled'  => $subject . $this->translate ('Your meeting scheduled for %1 has been canceled',array('$$startdate$$')),
3819                                'notifyModified'  => $subject . $this->translate ('Your meeting that had been scheduled for %1 has been rescheduled to %2',array('$$olddate$$','$$startdate$$')),
3820                                'notifyResponse'  => $subject . $this->translate ('On %1 %2 %3 your meeting request for %4', array('$$date$$','$$fullname$$','$$action$$','$$startdate$$')),
3821                                'notifyAlarm'     => $this->translate('Alarm for %1 at %2 in %3',array('$$title$$','$$startdate$$','$$location$$')) . "\n" . $this->translate('Here is your requested alarm.'),
3822                                'show_rejected'   => '0',
3823                                'hide_event_conflict'   => '0',
3824                                'display_status'  => '1',
3825                                'weekdaystarts'   => 'Monday',
3826                                'workdaystarts'   => '9',
3827                                'workdayends'     => '17',
3828                                'interval'        => '30',
3829                                'defaultlength'   => '60',
3830                                'planner_start_with_group' => $GLOBALS['phpgw']->accounts->name2id('Default'),
3831                                'planner_intervals_per_day'=> '4',
3832                                'defaultfilter'   => 'all',
3833                                'default_private' => '0',
3834                                'display_minicals'=> '1',
3835                                'print_black_white'=>'0'
3836                        );
3837                        foreach($defaults as $var => $default)
3838                        {
3839                                if (!isset($default_prefs[$var]) || $default_prefs[$var] == '')
3840                                {
3841                                        $GLOBALS['phpgw']->preferences->add('resources',$var,$default,'default');
3842                                        $need_save = True;
3843                                }
3844                        }
3845                        if ($need_save)
3846                        {
3847                                $prefs = $GLOBALS['phpgw']->preferences->save_repository(False,'default');
3848                                $this->prefs['resources'] = $prefs['resources'];
3849                        }
3850                        if ($this->prefs['resources']['send_updates'] && !isset($this->prefs['resources']['receive_updates']))
3851                        {
3852                                $this->prefs['resources']['receive_updates'] = $this->prefs['resources']['send_updates'];
3853                                $GLOBALS['phpgw']->preferences->add('resources','receive_updates',$this->prefs['resources']['send_updates']);
3854                                $GLOBALS['phpgw']->preferences->delete('resources','send_updates');
3855                                $prefs = $GLOBALS['phpgw']->preferences->save_repository();
3856                        }
3857                }
3858
3859                // return array with all resources categories (for xmlrpc)
3860                function categories($complete = False)
3861                {
3862                        return $GLOBALS['server']->categories($complete);
3863                }
3864/******************************************/
3865
3866function insert($params='')
3867                {
3868
3869                        if($params['from_mobile']) {
3870                                $ui_return = "mobile.ui_mobileresources.edit";
3871                                $ui_index = "mobile.ui_mobileresources.index";
3872                                $ui_overlap = "mobile.ui_mobileresources.overlap";
3873                        }
3874                        else {
3875                                $ui_return = "resources.uiresources.edit";
3876                                $ui_index = "resources.uiresources.index";             
3877                                $ui_overlap = "resources.uiresources.overlap";
3878                        }
3879
3880                        if(!is_object($GLOBALS['phpgw']->datetime))
3881                        {
3882                                $GLOBALS['phpgw']->datetime = createobject('phpgwapi.date_time');
3883                        }
3884                        //$l_cal = (@isset($params['info_type']) && $params['info_type']?$params['info_type']:$_POST['info_type']);
3885                        $l_participants = (@$params['participants']?$params['participants']:$_POST['participants']);
3886                        $this->ex_participants = (@$params['ex_participants']?$params['ex_participants']:$_POST['ex_participants']);
3887                        $l_categories = (@$params['categories']?$params['categories']:$_POST['categories']);
3888                        $l_start = (@isset($params['start']) && $params['start']?$params['start']:$_POST['start']);
3889                        $l_end = (@isset($params['end']) && $params['end']?$params['end']:$_POST['end']);
3890                        $l_recur_enddate = (@isset($params['recur_enddate']) && $params['recur_enddate']?$params['recur_enddate']:$_POST['recur_enddate']);
3891
3892                       
3893                        $send_to_ui = True;
3894                        //if ((!is_array($l_start) || !is_array($l_end)) && !isset($_GET['readsess']))  // xmlrpc call
3895                        if ($this->xmlrpc)      // xmlrpc call
3896                        {
3897
3898                                $send_to_ui = False;
3899
3900                                $l_cal = $params;       // no extra array
3901
3902                                foreach(array('start','end','recur_enddate') as $name)
3903                                {
3904                                        $var = 'l_'.$name;
3905                                        $$var = $GLOBALS['server']->iso86012date($params[$name]);
3906                                        unset($l_cal[$name]);
3907                                }
3908
3909                                if (!is_array($l_participants) || !count($l_participants))
3910                                {
3911                                        $l_participants = array($GLOBALS['phpgw_info']['user']['account_id'].'A');
3912                                }
3913                                else
3914                                {
3915                                        $l_participants = array();
3916                                        foreach($params['participants'] as $user => $data)
3917                                        {
3918                                                $l_participants[] = $user.$data['status'];
3919                                        }
3920                                }
3921
3922                                unset($l_cal['participants']);
3923
3924                                if (!is_object($GLOBALS['phpgw']->categories))
3925                                {
3926                                        $GLOBALS['phpgw']->categories = CreateObject('phpgwapi.categories');
3927                                }
3928
3929                                $l_categories = $GLOBALS['server']->xmlrpc2cats($params['category']);
3930                                unset($l_cal['category']);
3931
3932                                // using access={public|private} in all modules via xmlrpc
3933                                $l_cal['public'] = $params['access'] != 'private';
3934                                unset($l_cal['access']);
3935/*
3936                                $fp = fopen('/tmp/xmlrpc.log','a+');
3937                                ob_start();
3938                                echo "\nboresources::update("; print_r($params); echo ")\n";
3939                                //echo "\nl_start="; print_r($l_start);
3940                                //echo "\nl_end="; print_r($l_end);
3941                                fwrite($fp,ob_get_contents());
3942                                ob_end_clean();
3943                                fclose($fp);
3944*/
3945                        }
3946
3947                        print_debug('ID',$l_cal['id']);
3948
3949                        // don't wrap to the next day for no time
3950                        if ($l_end['hour'] == 24 && $l_end['min'] == 0)
3951                        {
3952                                $l_end['hour'] = 23;
3953                                $l_end['min'] = 59;
3954                        }
3955
3956                        if(isset($_GET['readsess']))
3957                        {
3958
3959                                $event = $this->restore_from_appsession();
3960                                $event['title'] = stripslashes($event['title']);
3961                                $event['description'] = stripslashes($event['description']);
3962$event['description1'] = stripslashes($event['description1']);
3963$event['participants1'] = stripslashes($event['participants1']);
3964                                $event['ex_participants'] = stripslashes($event['ex_participants']);
3965                                $datetime_check = $this->validate_update($event);
3966                                if($datetime_check)
3967                                {
3968                                        ExecMethod($ui_return,
3969                                                Array(
3970                                                        'cd'            => $datetime_check,
3971                                                        'readsess'      => 1
3972                                                )
3973                                        );
3974                                        if(!$params['from_mobile'])
3975                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
3976                                        else
3977                                                return;
3978                                }
3979                                $overlapping_events = False;
3980                        }
3981                        else
3982                        {
3983
3984                                if((!$l_cal['id'] && !$this->check_perms(PHPGW_ACL_ADD)) ||
3985                                   ($l_cal['id'] && !$this->check_perms(PHPGW_ACL_EDIT,$l_cal['id'])))
3986                                {
3987
3988                                        if ($this->xmlrpc)
3989                                        {
3990                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
3991                                        }
3992                                        if (!$send_to_ui)
3993                                        {
3994                                                return array(($l_cal['id']?1:2) => 'permission denied');
3995                                        }
3996
3997                                        ExecMethod($ui_index);
3998
3999
4000                                        if(!$params['from_mobile'])
4001                                                $GLOBALS['phpgw']->common->phpgw_exit();
4002                                        else
4003                                                return;
4004                                }
4005
4006                                print_debug('Prior to fix_update_time()');
4007
4008                                $this->fix_update_time($l_start);
4009
4010                                $this->fix_update_time($l_end);
4011
4012                                if(!isset($l_cal['ex_participants']))
4013                                {
4014                                        $l_cal['ex_participants'] = $this->ex_participants;
4015                                }
4016
4017                                if(!isset($l_categories))
4018                                {
4019                                        $l_categories = 0;
4020                                }
4021
4022                                $is_public = ($l_cal['type'] != 'private' && $l_cal['type'] != 'privateHiddenFields');
4023
4024                                //$this->so->event_init();
4025
4026                        $this->add_attribute('uid',$l_cal['uid']);
4027
4028                                $this->add_attribute('type',$l_cal['type']);
4029
4030                                if($l_cal['ex_participants']) {
4031                                        $this->add_attribute('ex_participants',$l_cal['ex_participants']);
4032                                }
4033                                if(count($l_categories) >= 2)
4034                                {
4035                                        //$this->so->set_category(implode(',',$l_categories));
4036                                }
4037                                else
4038                                {
4039                                        //$this->so->set_category(strval($l_categories[0]));
4040                                }
4041                                /*$this->so->set_title($l_cal['title']);
4042                                $this->so->set_description($l_cal['description']);
4043$this->so->set_description1($l_cal['description1']);
4044$this->so->set_participants1($l_cal['participants1']);
4045                                $this->so->set_ex_participants($l_cal['ex_participants']);
4046                                $this->so->set_start($l_start['year'],$l_start['month'],$l_start['mday'],$l_start['hour'],$l_start['min'],0);
4047                                $this->so->set_end($l_end['year'],$l_end['month'],$l_end['mday'],$l_end['hour'],$l_end['min'],0);
4048                                $this->so->set_class($is_public);
4049                                $this->so->add_attribute('reference',(@isset($l_cal['reference']) && $l_cal['reference']?$l_cal['reference']:0));
4050                                $this->so->add_attribute('location',(@isset($l_cal['location']) && $l_cal['location']?$l_cal['location']:''));*/
4051                                if($l_cal['id'])
4052                                {
4053                                        //$this->so->add_attribute('id',$l_cal['id']);
4054                                }
4055
4056                                if($l_cal['rpt_use_end'] != 'y')
4057                                {
4058                                        $l_recur_enddate['year'] = 0;
4059                                        $l_recur_enddate['month'] = 0;
4060                                        $l_recur_enddate['mday'] = 0;
4061                                }
4062                                elseif (isset($l_recur_enddate['str']))
4063                                {
4064                                        $l_recur_enddate = $this->jscal->input2date($l_recur_enddate['str'],False,'mday');
4065                                }
4066
4067                                switch((int)$l_cal['recur_type'])
4068                                {
4069
4070
4071                                        case MCAL_RECUR_NONE:
4072                                                //$this->so->set_recur_none();
4073
4074                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4075
4076                                                break;
4077                                        case MCAL_RECUR_DAILY:
4078                                                //$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']);
4079
4080                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4081
4082                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
4083                                                $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;
4084
4085                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
4086                                                {
4087
4088                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
4089                                                        $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;
4090
4091                                                }else { // se nao existe data final da repeticao (agendamento infinito):
4092
4093                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
4094                                                }
4095                                                break;
4096                                        case MCAL_RECUR_WEEKLY:
4097
4098                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4099
4100                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
4101                                                $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;
4102
4103                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
4104                                                {
4105
4106                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
4107                                                        $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;
4108
4109                                                }else { // se nao existe data final da repeticao (agendamento infinito):
4110
4111                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
4112                                                }
4113
4114                                                foreach(array('rpt_sun','rpt_mon','rpt_tue','rpt_wed','rpt_thu','rpt_fri','rpt_sat') as $rpt_day)
4115                                                {
4116                                                        $l_cal['recur_data'] += (int)$l_cal[$rpt_day];
4117                                                }
4118                                                if (is_array($l_cal['rpt_day']))
4119                                                {
4120                                                        foreach ($l_cal['rpt_day'] as $mask)
4121                                                        {
4122                                                                $l_cal['recur_data'] |= (int)$mask;
4123                                                                $rpt_wdays = $l_cal['recur_data']; // recebe os dias da semana (somatorio) para repetir o alarme;
4124                                                        }
4125                                                }
4126                                                //$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']);
4127                                                break;
4128                                        case MCAL_RECUR_MONTHLY_MDAY:
4129                                                //$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']);
4130
4131                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4132
4133                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
4134                                                $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;
4135
4136                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
4137                                                {
4138
4139                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
4140                                                        $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;
4141
4142                                                }else { // se nao existe data final da repeticao (agendamento infinito):
4143
4144                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
4145                                                }
4146                                                break;
4147                                        case MCAL_RECUR_MONTHLY_WDAY:
4148                                                //$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']);
4149                                                break;
4150                                        case MCAL_RECUR_YEARLY:
4151                                                //$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']);
4152
4153                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
4154
4155                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
4156                                                $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;
4157
4158                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
4159                                                {
4160
4161                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
4162                                                        $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;
4163
4164                                                }else { // se nao existe data final da repeticao (agendamento infinito):
4165
4166                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
4167                                                }
4168                                                break;
4169                                }
4170
4171                                if($l_participants)
4172                                {
4173                                        $parts = $l_participants;
4174                                        $minparts = min($l_participants);
4175                                        $part = Array();
4176                                        for($i=0;$i<count($parts);$i++)
4177                                        {
4178                                                if (($accept_type = substr($parts[$i],-1,1)) == '0' || (int)$accept_type > 0)
4179                                                {
4180                                                        $accept_type = 'U';
4181                                                }
4182                                                $acct_type = $GLOBALS['phpgw']->accounts->get_type((int)$parts[$i]);
4183                                                if($acct_type == 'u')
4184                                                {
4185                                                        $part[(int)$parts[$i]] = $accept_type;
4186                                                }
4187                                                elseif($acct_type == 'g')
4188                                                {
4189                                                        $part[(int)$parts[$i]] = $accept_type;
4190                                                        $groups[] = $parts[$i];
4191                                                        /* This pulls ALL users of a group and makes them as participants to the event */
4192                                                        /* I would like to turn this back into a group thing. */
4193                                                        $acct = CreateObject('phpgwapi.accounts',(int)$parts[$i]);
4194                                                        $members = $acct->member((int)$parts[$i]);
4195                                                        unset($acct);
4196                                                        if($members == False)
4197                                                        {
4198                                                                continue;
4199                                                        }
4200                                                        while($member = each($members))
4201                                                        {
4202                                                                $part[$member[1]['account_id']] = $accept_type;
4203                                                        }
4204                                                }
4205                                        }
4206                                }
4207                                else
4208                                {
4209                                        $part = False;
4210                                }
4211
4212                                if($part)
4213                                {
4214                                        @reset($part);
4215                                        while(list($key,$accept_type) = each($part))
4216                                        {
4217                                                //$this->so->add_attribute('participants',$accept_type,(int)$key);
4218                                        }
4219                                }
4220
4221                                if($groups)
4222                                {
4223                                        @reset($groups);
4224                                        //$this->so->add_attribute('groups',(int)$group_id);
4225                                }
4226
4227                                $event = $this->get_cached_event();
4228                                if(!is_int($minparts))
4229                                {
4230                                        $minparts = $this->owner;
4231                                }
4232                                if(!@isset($event['participants'][$l_cal['owner']]))
4233                                {
4234                                        //$this->so->add_attribute('owner',$minparts);
4235                                }
4236                                else
4237                                {
4238                                        //$this->so->add_attribute('owner',$l_cal['owner']);
4239                                }
4240                                //$this->so->add_attribute('priority',$l_cal['priority']);
4241
4242                                foreach($l_cal as $name => $value)
4243                                {
4244                                        if ($name[0] == '#')    // Custom field
4245                                        {
4246                                                //$this->so->add_attribute($name,stripslashes($value));
4247                                        }
4248                                }
4249                                if (isset($_POST['preserved']) && is_array($preserved = unserialize(stripslashes($_POST['preserved']))))
4250                                {
4251                                        foreach($preserved as $name => $value)
4252                                        {
4253                                                switch($name)
4254                                                {
4255                                                        case 'owner':
4256                                                                //$this->so->add_attribute('participants',$value,$l_cal['owner']);
4257                                                                break;
4258                                                        default:
4259                                                                //$this->so->add_attribute($name,str_replace(array('&amp;','&quot;','&lt;','&gt;'),array('&','"','<','>'),$value));
4260                                                }
4261                                        }
4262                                }
4263                                $event = $this->get_cached_event();
4264
4265                                if ($l_cal['alarmdays'] > 0 || $l_cal['alarmhours'] > 0 ||
4266                                                $l_cal['alarmminutes'] > 0)
4267                                {
4268                                        $offset = ($l_cal['alarmdays'] * 24 * 3600) +
4269                                                ($l_cal['alarmhours'] * 3600) + ($l_cal['alarmminutes'] * 60);
4270
4271                                        $time = $this->maketime($event['start']) - $offset;
4272
4273                                        $event['alarm'][] = Array(
4274                                                'time'    => $time,
4275                                                'offset'  => $offset,
4276                                                'owner'   => $this->owner,
4277                                                'enabled' => 1,
4278                                                'repeat'  => $repetido, // para repetir alarme;
4279                                                'init_rept' => $init_rept, // inicio repeticao;
4280                                                'end_rept' => $end_rept, // fim repeticao;
4281                                                'rpt_wdays' => $rpt_wdays // dias repeticao da semana;
4282                                        );
4283                                }
4284
4285                                $this->store_to_appsession($event);
4286                                $datetime_check = $this->validate_update($event);
4287                                print_debug('bo->validated_update() returnval',$datetime_check);
4288
4289                                /*if($datetime_check)
4290                                {
4291
4292
4293                                        if (!$send_to_ui)
4294                                        {
4295                                                return array($datetime_check => 'invalid input data');
4296                                        }
4297
4298
4299                                        ExecMethod($ui_return,
4300                                                Array(
4301                                                        'cd'            => $datetime_check,
4302                                                        'readsess'      => 1
4303                                                )
4304                                        );
4305
4306                                        if(!$params['from_mobile'])
4307                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
4308                                        else
4309                                                return;
4310
4311                                }/*/
4312                                if($event['id'])
4313                                {
4314                                        $event_ids[] = $event['id'];
4315                                }
4316                                if($event['reference'])
4317                                {
4318                                        $event_ids[] = $event['reference'];
4319                                }
4320
4321                                $overlapping_events = $this->overlap(
4322                                        $this->maketime($event['start']),
4323                                        $this->maketime($event['end']),
4324                                        $event['participants'],
4325                                        $event['owner'],
4326                                        $event_ids
4327                                );
4328                        }
4329                        if(!$this->ex_participants)
4330                                $this->ex_participants = $event['ex_participants'];                     
4331                        if($overlapping_events)
4332                        {
4333
4334
4335                                if($send_to_ui)
4336                                {
4337                                        $event['ex_participants'] = $this->ex_participants;
4338                                        unset($GLOBALS['phpgw_info']['flags']['noheader']);
4339                                        unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
4340                                        ExecMethod($ui_overlap,
4341                                                Array(
4342                                                        'o_events'      => $overlapping_events,
4343                                                        'this_event'    => $event
4344                                                )
4345                                        );
4346                                        if(!$params['from_mobile'])
4347                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
4348                                        else
4349                                                return;
4350                                }
4351                                else
4352                                {
4353                                        return $overlapping_events;
4354                                }
4355                        }
4356                        else
4357                        {
4358
4359
4360
4361                                if(!$event['id'])
4362                                {
4363
4364
4365
4366                                        //$this->so->add_entry($event);
4367                                        $this->send_update(MSG_ADDED,$event['participants'],'',$this->get_cached_event());
4368                                        print_debug('New Event ID',$event['id']);
4369                                }
4370                                else
4371                                {
4372
4373                                        print_debug('Updating Event ID',$event['id']);
4374                                        $new_event = $event;
4375                                        $old_event = $this->read_entry($event['id']);
4376                                        // if old event has alarm and the start-time changed => update them
4377                                        //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";
4378                                        if ($old_event['alarm'] &&
4379                                                $this->maketime($old_event['start']) != $this->maketime($event['start']))
4380                                        {
4381                                                //$this->so->delete_alarms($old_event['id']);
4382                                                foreach($old_event['alarm'] as $id => $alarm)
4383                                                {
4384                                                        $alarm['time'] = $this->maketime($event['start']) - $alarm['offset'];
4385                                                        $event['alarm'][] = $alarm;
4386                                                }
4387                                                //echo "updated alarms<pre>".print_r($event['alarm'],True)."</pre>\n";
4388                                        }
4389                                        //$this->so->cal->event = $event;
4390                                        //$this->so->add_entry($event);
4391                                        $this->prepare_recipients($new_event,$old_event);
4392                                }
4393
4394                                $date = sprintf("%04d%02d%02d",$event['start']['year'],$event['start']['month'],$event['start']['mday']);
4395                                if($send_to_ui)
4396                                {
4397                                        $this->read_sessiondata();
4398                                        if ($this->return_to)
4399                                        {
4400                                                $GLOBALS['phpgw']->redirect_link('/index.php','menuaction='.$this->return_to);
4401                                                $GLOBALS['phpgw']->common->phpgw_exit();
4402                                        }
4403                                        Execmethod($ui_index);
4404                                }
4405                                else
4406                                {
4407                                        return (int)$event['id'];
4408                                }
4409                        }
4410                        return True;
4411                }
4412
4413function date_filter($name,&$start,&$end_param)
4414        {
4415                $end = $end_param;
4416
4417                if ($name == 'custom' && $start)
4418                {
4419                        if ($end)
4420                        {
4421                                $end += 24*60*60;
4422                        }
4423                        else
4424                        {
4425                                $end = $start + 8*24*60*60;
4426                        }
4427                }
4428                else
4429                {
4430                        if (!isset($this->date_filters[$name]))
4431                        {
4432                                return '1=1';
4433                        }
4434                        $year  = (int) date('Y',$this->today);
4435                        $month = (int) date('m',$this->today);
4436                        $day   = (int) date('d',$this->today);
4437       
4438                        list($syear,$smonth,$sday,$sweek,$eyear,$emonth,$eday,$eweek) = $this->date_filters[$name];
4439                       
4440                        if ($syear || $eyear)
4441                        {
4442                                $start = mktime(0,0,0,1,1,$syear+$year);
4443                                $end   = mktime(0,0,0,1,1,$eyear+$year);
4444                        }
4445                        elseif ($smonth || $emonth)
4446                        {
4447                                $start = mktime(0,0,0,$smonth+$month,1,$year);
4448                                $end   = mktime(0,0,0,$emonth+$month,1,$year);
4449                        }
4450                        elseif ($sday || $eday)
4451                        {
4452                                $start = mktime(0,0,0,$month,$sday+$day,$year);
4453                                $end   = mktime(0,0,0,$month,$eday+$day,$year);
4454                        }
4455                        elseif ($sweek || $eweek)
4456                        {
4457                                $wday = (int) date('w',$this->today); // 0=sun, ..., 6=sat
4458                                switch($GLOBALS['phpgw_info']['user']['preferences']['calendar']['weekdaystarts'])
4459                                {
4460                                        case 'Sunday':
4461                                                $weekstart = $this->today - $wday * 24*60*60;
4462                                                break;
4463                                        case 'Saturday':
4464                                                $weekstart = $this->today - (6-$wday) * 24*60*60;
4465                                                break;
4466                                        case 'Moday':
4467                                        default:
4468                                                $weekstart = $this->today - ($wday ? $wday-1 : 6) * 24*60*60;
4469                                                break;
4470                                }
4471                                $start = $weekstart + $sweek*7*24*60*60;
4472                                $end   = $weekstart + $eweek*7*24*60*60;
4473                        }
4474                        $end_param = $end - 24*60*60;
4475                }
4476                //echo "<p align='right'>date_filter($name,$start,$end) today=".date('l, Y-m-d H:i',$this->today)." ==> ".date('l, Y-m-d H:i:s',$start)." <= date < ".date('l, Y-m-d H:i:s',$end)."</p>\n";
4477                // convert start + end from user to servertime for the filter
4478                return '('.($start-$this->tz_offset_s).' <= ts_start AND ts_start < '.($end-$this->tz_offset_s).')';
4479        }
4480/***********************************************/
4481        }
4482?>
Note: See TracBrowser for help on using the repository browser.