source: contrib/Resources/inc/class.boresources.inc.php @ 4362

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