source: trunk/calendar/inc/class.socalendar_sql.inc.php @ 5243

Revision 5243, 36.8 KB checked in by gustavo, 12 years ago (diff)

Ticket #2375 - Verificar problema ao alternar entre a interface web/mobile

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2  /**************************************************************************\
3  * eGroupWare - Calendar                                                    *
4  * http://www.eGroupWare.org                                                *
5  * Maintained and further developed by RalfBecker@outdoor-training.de       *
6  * Based on Webcalendar by Craig Knudsen <cknudsen@radix.net>               *
7  *          http://www.radix.net/~cknudsen                                  *
8  * Originaly modified by Mark Peters <skeeter@phpgroupware.org>             *
9  * --------------------------------------------                             *
10  *  This program is free software; you can redistribute it and/or modify it *
11  *  under the terms of the GNU General Public License as published by the   *
12  *  Free Software Foundation; either version 2 of the License, or (at your  *
13  *  option) any later version.                                              *
14  \**************************************************************************/
15if($_SESSION['isCrun']){
16        $_SESSION['isCrun'] = false;
17        $_SESSION['rootPath'] = PHPGW_INCLUDE_ROOT;
18        require_once $_SESSION['rootPath'].'/API/class.servicelocator.php';
19}else if($_SESSION['rootPath']){
20        require_once $_SESSION['rootPath'].'/API/class.servicelocator.php';
21}else{
22        require_once PHPGW_INCLUDE_ROOT.'/API/class.servicelocator.php';
23}
24
25        if (@$GLOBALS['phpgw_info']['flags']['included_classes']['socalendar_'])
26        {
27                return;
28        }
29
30        $GLOBALS['phpgw_info']['flags']['included_classes']['socalendar_'] = True;
31
32        class socalendar_ extends socalendar__
33        {
34                var $deleted_events = Array();
35
36                var $cal_event;
37                var $today = Array('raw','day','month','year','full','dow','dm','bd');
38
39
40                function socalendar_()
41                {
42                        $this->socalendar__();
43
44                        if (!is_object($GLOBALS['phpgw']->asyncservice))
45                        {
46                                $GLOBALS['phpgw']->asyncservice = CreateObject('phpgwapi.asyncservice');
47                        }
48                        $this->async = &$GLOBALS['phpgw']->asyncservice;
49                }
50
51                function open($calendar='',$user='',$passwd='',$options='')
52                {
53                        if($user=='')
54                        {
55        //                      settype($user,'integer');
56                                $this->user = $GLOBALS['phpgw_info']['user']['account_id'];
57                        }
58                        elseif(is_int($user))
59                        {
60                                $this->user = $user;
61                        }
62                        elseif(is_string($user))
63                        {
64                                $this->user = $GLOBALS['phpgw']->accounts->name2id($user);
65                        }
66
67                        $this->stream = $GLOBALS['phpgw']->db;
68                        return $this->stream;
69                }
70
71                function popen($calendar='',$user='',$passwd='',$options='')
72                {
73                        return $this->open($calendar,$user,$passwd,$options);
74                }
75
76                function reopen($calendar,$options='')
77                {
78                        return $this->stream;
79                }
80
81                function close($options='')
82                {
83                        return True;
84                }
85
86                function create_calendar($calendar='')
87                {
88                        return $calendar;
89                }
90
91                function rename_calendar($old_name='',$new_name='')
92                {
93                        return $new_name;
94                }
95
96                function delete_calendar($calendar='')
97                {
98                        $this->stream->query('SELECT cal_id FROM phpgw_cal WHERE owner='.(int)$calendar,__LINE__,__FILE__);
99                        if($this->stream->num_rows())
100                        {
101                                while($this->stream->next_record())
102                                {
103                                        $this->delete_event((int)$this->stream->f('cal_id'));
104                                }
105                                $this->expunge();
106                        }
107                        $this->stream->lock(array('phpgw_cal_user'));
108                        $this->stream->query('DELETE FROM phpgw_cal_user WHERE cal_login='.(int)$calendar,__LINE__,__FILE__);
109                        $this->stream->unlock();
110
111                        return $calendar;
112                }
113
114                /*!
115                @function read_alarms
116                @abstract read the alarms of a calendar-event specified by $cal_id
117                @returns array of alarms with alarm-id as key
118                @note the alarm-id is a string of 'cal:'.$cal_id.':'.$alarm_nr, it is used as the job-id too
119                */
120                function read_alarms($cal_id)
121                {
122                        $alarms = array();
123
124                        if ($jobs = $this->async->read('cal:'.(int)$cal_id.':%'))
125                        {
126                                foreach($jobs as $id => $job)
127                                {
128                                        $alarm         = $job['data'];  // text, enabled
129                                        $alarm['id']   = $id;
130                                        $alarm['time'] = $job['next'];
131
132                                        $alarms[$id] = $alarm;
133                                }
134                        }
135                        return $alarms;
136                }
137
138                /*!
139                @function read_alarm
140                @abstract read a single alarm specified by it's $id
141                @returns array with data of the alarm
142                @note the alarm-id is a string of 'cal:'.$cal_id.':'.$alarm_nr, it is used as the job-id too
143                */
144                function read_alarm($id)
145                {
146                        if (!($jobs = $this->async->read($id)))
147                        {
148                                return False;
149                        }
150                        list($id,$job) = each($jobs);
151                        $alarm         = $job['data'];  // text, enabled
152                        $alarm['id']   = $id;
153                        $alarm['time'] = $job['next'];
154
155                        //echo "<p>read_alarm('$id')="; print_r($alarm); echo "</p>\n";
156                        return $alarm;
157                }
158
159/* Funcao save_alarm modificada para gerar alarmes repetidos, caso seja marcado um evento igualmente repetido. A funcao recebe qual o tipo
160de repeticao escolhido pelo usuario (diario, semanal, mensal, anual) e insere alarmes nas respectivas repeticoes do evento. */
161                /*!
162                @function save_alarm
163                @abstract saves a new or updated alarm
164                @syntax save_alarm($cal_id,$alarm,$id=False)
165                @param $cal_id Id of the calendar-entry
166                @param $alarm array with fields: text, owner, enabled, ..
167                @returns the id of the alarm
168                */
169                function save_alarm($cal_id,$alarm)
170                {
171
172                        if (!($id = $alarm['id']))
173                        {
174                                $alarm['time'] -= $GLOBALS['phpgw']->datetime->tz_offset;       // time should be stored in server timezone
175                                $alarms = $this->read_alarms($cal_id);  // find a free alarm#
176
177                                if($alarm['repeat'] == 1) // repeticao do tipo "Diariamente";
178                                {
179                                        $n = 0;
180
181                                        while(@isset($alarms[$id]));
182                                        {
183
184                                                $init_alarm = $alarm['init_rept'];
185                                                $end_alarm = $alarm['end_rept'];
186
187                                                if($end_alarm != 0)
188                                                {
189                                                        while($init_alarm <= $end_alarm)
190                                                        {
191                                                                $id = 'cal:'.(int)$cal_id.':'.$n;
192                                                                $n++;
193                                                               
194                                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
195
196                                                                unset($alarm['repeat']);
197                                                                unset($alarm['init_rept']);
198                                                                unset($alarm['end_rept']);
199                                                                unset($alarm['rpt_wdays']);
200
201                                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
202                                                                {
203                                                                        return False;
204                                                                }
205
206                                                                $alarm['time'] += 86400;
207                                                                $init_alarm += 86400;
208                                                        }
209                                                }
210                                        }
211
212                                }elseif($alarm['repeat'] == 2) { // repeticao do tipo "Semanalmente";
213
214                                        $n = 0;
215
216                                        $init_alarm = $data_atual = $alarm['init_rept'];
217                                        $end_alarm = $alarm['end_rept'];
218
219                                        $rpt_alarm_wdays = $alarm['rpt_wdays'];
220
221                                        $divisor = 64;
222                                        $quociente = 0;
223                                        $resto = 0;
224
225                                        $dia_semana = date("w",$init_alarm);
226
227                                        switch($dia_semana)
228                                        {
229                                                case 0:
230                                                        $dia = array(
231                                                                        0 => 'domingo',
232                                                                        1 => 'segunda',
233                                                                        2 => 'terca',
234                                                                        3 => 'quarta',
235                                                                        4 => 'quinta',
236                                                                        5 => 'sexta',
237                                                                        6 => 'sabado'
238                                                        );
239                                                        break;
240                                                case 1:
241                                                        $dia = array(
242                                                                        0 => 'segunda',
243                                                                        1 => 'terca',
244                                                                        2 => 'quarta',
245                                                                        3 => 'quinta',
246                                                                        4 => 'sexta',
247                                                                        5 => 'sabado',
248                                                                        6 => 'domingo'
249                                                        );
250                                                        break;
251                                                case 2:
252                                                        $dia = array(
253                                                                        0 => 'terca',
254                                                                        1 => 'quarta',
255                                                                        2 => 'quinta',
256                                                                        3 => 'sexta',
257                                                                        4 => 'sabado',
258                                                                        5 => 'domingo',
259                                                                        6 => 'segunda'
260                                                        );
261                                                        break;
262                                                case 3:
263                                                        $dia = array(
264                                                                        0 => 'quarta',
265                                                                        1 => 'quinta',
266                                                                        2 => 'sexta',
267                                                                        3 => 'sabado',
268                                                                        4 => 'domingo',
269                                                                        5 => 'segunda',
270                                                                        6 => 'terca'
271                                                        );
272                                                        break;
273                                                case 4:
274                                                        $dia = array(
275                                                                        0 => 'quinta',
276                                                                        1 => 'sexta',
277                                                                        2 => 'sabado',
278                                                                        3 => 'domingo',
279                                                                        4 => 'segunda',
280                                                                        5 => 'terca',
281                                                                        6 => 'quarta'
282                                                        );
283                                                        break;
284                                                case 5:
285                                                        $dia = array(
286                                                                        0 => 'sexta',
287                                                                        1 => 'sabado',
288                                                                        2 => 'domingo',
289                                                                        3 => 'segunda',
290                                                                        4 => 'terca',
291                                                                        5 => 'quarta',
292                                                                        6 => 'quinta'
293                                                        );
294                                                        break;
295                                                case 6:
296                                                        $dia = array(
297                                                                        0 => 'sabado',
298                                                                        1 => 'domingo',
299                                                                        2 => 'segunda',
300                                                                        3 => 'terca',
301                                                                        4 => 'quarta',
302                                                                        5 => 'quinta',
303                                                                        6 => 'sexta'
304                                                        );
305                                                        break;
306                                        }
307
308
309                                        $dias_semana = array(
310                                                                64 => 'sabado',
311                                                                32 => 'sexta',
312                                                                16 => 'quinta',
313                                                                8 => 'quarta',
314                                                                4 => 'terca',
315                                                                2 => 'segunda',
316                                                                1 => 'domingo'
317                                                        );
318
319                                        $result = array();
320                                        do
321                                        {
322
323                                                $resto = ($rpt_alarm_wdays % $divisor);
324                                                $quociente = floor($rpt_alarm_wdays / $divisor);
325
326                                                if($quociente == 1)
327                                                {
328                                                        $result[] = $dias_semana[$divisor];
329
330                                                        $divisor = $divisor / 2;
331                                                        $rpt_alarm_wdays = $resto;
332
333                                                }else {
334
335                                                        while($rpt_alarm_wdays < $divisor)
336                                                        {
337                                                                $divisor = $divisor / 2;
338                                                        }
339
340                                                        $resto = ($rpt_alarm_wdays % $divisor);
341                                                        $quociente = floor($rpt_alarm_wdays / $divisor);
342
343                                                        if($quociente == 1)
344                                                        {
345
346                                                                $result[] = $dias_semana[$divisor];
347
348                                                                $divisor = $divisor / 2;
349                                                                $rpt_alarm_wdays = $resto;
350                                                        }
351                                                }
352
353                                        }
354                                        while($resto != 0);
355
356                                        krsort($result);
357
358                                        $week_num = 0;
359                                        $y = 0;
360
361                                        while(@isset($alarms[$id]));
362                                        {
363
364                                                if($end_alarm != 0)
365                                                {
366
367                                                        while($data_atual <= $end_alarm)
368                                                        {
369
370                                                                foreach($dia as $index => $value)
371                                                                {
372                                                                        if(in_array($value,$result))
373                                                                        {
374
375                                                                                $nova_data = $init_alarm + (86400 * ($index + (7 * $y)));
376
377                                                                                if($nova_data == $init_alarm){
378
379                                                                                        continue;
380                                                                                }
381
382                                                                                $id = 'cal:'.(int)$cal_id.':'.$n;
383                                                                                $n++;
384
385                                                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
386
387                                                                                unset($alarm['repeat']);
388                                                                                unset($alarm['init_rept']);
389                                                                                unset($alarm['end_rept']);
390                                                                                unset($alarm['rpt_wdays']);
391                                                                               
392                                                                                $data_atual = $nova_data;
393
394                                                                                if($data_atual > $end_alarm){
395                                                                                        if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
396                                                                                        {
397                                                                                                return False;
398                                                                                        }
399                                                                                        break;
400                                                                                }
401
402                                                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
403                                                                                {
404                                                                                        return False;
405                                                                                }
406                                                                                        $alarm['time'] = $nova_data - $alarm['offset'] - $GLOBALS['phpgw']->datetime->tz_offset;
407                                                                        }
408                                                                }
409                                                                $y++;
410                                                        }
411                                                }
412                                        }
413
414                                }elseif($alarm['repeat'] == 3) { // repeticao do tipo "Mensalmente (por data)";
415
416                                        $n = 0;
417
418                                        $init_alarm = $alarm['init_rept'];
419                                        $end_alarm = $alarm['end_rept'];
420                                       
421                                        while(@isset($alarms[$id]));
422                                        {
423
424                                                if($end_alarm != 0)
425                                                {
426                                                        while($init_alarm <= $end_alarm)
427                                                        {
428
429                                                                $next_month = date("n",$init_alarm) + 1;
430                                                                $next_alarm = mktime(date("G",$alarm['time']),date("i",$alarm['time']),date("s",$alarm['time']),$next_month,date("j",$alarm['time']),date("Y",$alarm['time']));
431
432                                                                $id = 'cal:'.(int)$cal_id.':'.$n;
433                                                                $n++;
434
435                                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
436
437                                                                unset($alarm['repeat']);
438                                                                unset($alarm['init_rept']);
439                                                                unset($alarm['end_rept']);
440                                                                unset($alarm['rpt_wdays']);
441
442                                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
443                                                                {
444                                                                        return False;
445                                                                }
446
447                                                                $alarm['time'] = $next_alarm;
448                                                                $init_alarm = $next_alarm;
449
450                                                        }
451                                                }
452                                        }
453
454                                }elseif($alarm['repeat'] == 5) { // repeticao do tipo "Anualmente";
455
456                                        $n = 0;
457
458                                        $init_alarm = $alarm['init_rept'];
459                                        $end_alarm = $alarm['end_rept'];
460                                       
461                                        while(@isset($alarms[$id]));
462                                        {
463
464
465                                                if($end_alarm != 0)
466                                                {
467                                                        while($init_alarm < $end_alarm)
468                                                        {
469
470                                                                $next_year = date("Y",$init_alarm) + 1;
471                                                                $next_alarm = mktime(date("G",$alarm['time']),date("i",$alarm['time']),date("s",$alarm['time']),date("n",$alarm['time']),date("j",$alarm['time']),$next_year);
472
473                                                                $id = 'cal:'.(int)$cal_id.':'.$n;
474                                                                $n++;
475
476                                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
477
478                                                                unset($alarm['repeat']);
479                                                                unset($alarm['init_rept']);
480                                                                unset($alarm['end_rept']);
481                                                                unset($alarm['rpt_wdays']);
482
483                                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
484                                                                {
485                                                                        return False;
486                                                                }
487
488                                                                $alarm['time'] = $next_alarm;
489                                                                $init_alarm = $next_alarm;
490                                                        }
491                                                }
492                                        }
493
494                                }else {
495                                        $alarm['time'] -= $GLOBALS['phpgw']->datetime->tz_offset;       // time should be stored in server timezone
496                                        $n = count($alarms);
497                                        while(@isset($alarms[$id]));
498                                        {
499
500                                                $id = 'cal:'.(int)$cal_id.':'.$n;
501
502                                                unset($alarm['repeat']);
503                                                unset($alarm['init_rept']);
504                                                unset($alarm['end_rept']);
505                                                unset($alarm['rpt_wdays']);
506
507                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
508                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
509                                                {
510                                                        return False;
511                                                }
512
513                                                ++$n;
514                                        }
515                                }
516
517                        }
518                        else
519                        {
520                                $this->async->cancel_timer($id);
521                        }
522                        $alarm['time'] -= $GLOBALS['phpgw']->datetime->tz_offset;       // time should be stored in server timezone
523                        return $id;
524                }
525
526                /*!
527                @function delete_alarms($cal_id)
528                @abstract delete all alarms of a calendar-entry
529                @returns the number of alarms deleted
530                */
531                function delete_alarms($cal_id)
532                {
533                        $alarms = $this->read_alarms($cal_id);
534
535                        foreach($alarms as $id => $alarm)
536                        {
537                                $this->async->cancel_timer($id);
538                        }
539                        return count($alarms);
540                }
541
542                /*!
543                @function delete_alarm($id)
544                @abstract delete one alarms identified by its id
545                @returns the number of alarms deleted
546                */
547                function delete_alarm($id)
548                {
549                        return $this->async->cancel_timer($id);
550                }
551
552                function fetch_event($event_id,$options='')
553                {
554                        if(!isset($this->stream))
555                        {
556                                return False;
557                        }
558
559                        $event_id = (int)$event_id;
560
561                        $this->stream->lock(array('phpgw_cal','phpgw_cal_user','phpgw_cal_repeats','phpgw_cal_extra'/* OLD-ALARM,'phpgw_cal_alarm'*/));
562
563                        $this->stream->query('SELECT * FROM phpgw_cal WHERE cal_id='.$event_id,__LINE__,__FILE__);
564
565                        if($this->stream->num_rows() > 0)
566                        {
567                                $this->event_init();
568
569                                $this->stream->next_record();
570                                // Load the calendar event data from the db into $event structure
571                                // Use http://www.php.net/manual/en/function.mcal-fetch-event.php as the reference
572                                $this->add_attribute('owner',(int)$this->stream->f('owner'));
573                                $this->add_attribute('id',(int)$this->stream->f('cal_id'));
574                                $this->add_attribute('type',$this->stream->f('cal_type'));
575                                $this->set_class((int)$this->stream->f('is_public'));
576                                $this->set_category($this->stream->f('category'));
577                                $this->set_title(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('title'))));
578                                $this->set_description(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('description'))));
579                                $this->set_ex_participants(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('ex_participants'))));
580                                $this->add_attribute('uid',$GLOBALS['phpgw']->strip_html($this->stream->f('uid')));
581                                $this->add_attribute('location',stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('location'))));
582                                $this->add_attribute('organizer',stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('organizer'))));
583                                $this->add_attribute('reference',(int)$this->stream->f('reference'));
584
585                                // This is the preferred method once everything is normalized...
586                                //$this->event->alarm = (int)$this->stream->f('alarm');
587                                // But until then, do it this way...
588                                //Legacy Support (New)
589
590                                $datetime = $GLOBALS['phpgw']->datetime->localdates($this->stream->f('datetime'));
591                                $this->set_start($datetime['year'],$datetime['month'],$datetime['day'],$datetime['hour'],$datetime['minute'],$datetime['second']);
592
593                                $datetime = $GLOBALS['phpgw']->datetime->localdates($this->stream->f('mdatetime'));
594                                $this->set_date('modtime',$datetime['year'],$datetime['month'],$datetime['day'],$datetime['hour'],$datetime['minute'],$datetime['second']);
595
596                                $datetime = $GLOBALS['phpgw']->datetime->localdates($this->stream->f('edatetime'));
597                                $this->set_end($datetime['year'],$datetime['month'],$datetime['day'],$datetime['hour'],$datetime['minute'],$datetime['second']);
598
599                        //Legacy Support
600                                $this->add_attribute('priority',(int)$this->stream->f('priority'));
601                                if($this->stream->f('cal_group') || $this->stream->f('groups') != 'NULL')
602                                {
603                                        $groups = explode(',',$this->stream->f('groups'));
604                                        for($j=1;$j<count($groups) - 1;$j++)
605                                        {
606                                                $this->add_attribute('groups',$groups[$j],$j-1);
607                                        }
608                                }
609
610                                $this->stream->query('SELECT * FROM phpgw_cal_repeats WHERE cal_id='.$event_id,__LINE__,__FILE__);
611                                if($this->stream->num_rows())
612                                {
613                                        $this->stream->next_record();
614
615                                        $this->add_attribute('recur_type',(int)$this->stream->f('recur_type'));
616                                        $this->add_attribute('recur_interval',(int)$this->stream->f('recur_interval'));
617                                        $enddate = $this->stream->f('recur_enddate');
618                                        if($enddate != 0 && $enddate != Null)
619                                        {
620                                                $datetime = $GLOBALS['phpgw']->datetime->localdates($enddate);
621                                                $this->add_attribute('recur_enddate',$datetime['year'],'year');
622                                                $this->add_attribute('recur_enddate',$datetime['month'],'month');
623                                                $this->add_attribute('recur_enddate',$datetime['day'],'mday');
624                                                $this->add_attribute('recur_enddate',$datetime['hour'],'hour');
625                                                $this->add_attribute('recur_enddate',$datetime['minute'],'min');
626                                                $this->add_attribute('recur_enddate',$datetime['second'],'sec');
627                                        }
628                                        else
629                                        {
630                                                $this->add_attribute('recur_enddate',0,'year');
631                                                $this->add_attribute('recur_enddate',0,'month');
632                                                $this->add_attribute('recur_enddate',0,'mday');
633                                                $this->add_attribute('recur_enddate',0,'hour');
634                                                $this->add_attribute('recur_enddate',0,'min');
635                                                $this->add_attribute('recur_enddate',0,'sec');
636                                        }
637                                        $this->add_attribute('recur_enddate',0,'alarm');
638                                        if($this->debug)
639                                        {
640                                                echo 'Event ID#'.$this->event['id'].' : Enddate = '.$enddate."<br>\n";
641                                        }
642                                        $this->add_attribute('recur_data',$this->stream->f('recur_data'));
643
644                                        $exception_list = $this->stream->f('recur_exception');
645                                        $exceptions = Array();
646                                        if(strpos(' '.$exception_list,','))
647                                        {
648                                                $exceptions = explode(',',$exception_list);
649                                        }
650                                        elseif($exception_list != '')
651                                        {
652                                                $exceptions[]= $exception_list;
653                                        }
654                                        $this->add_attribute('recur_exception',$exceptions);
655                                }
656
657                        //Legacy Support
658                                $this->stream->query('SELECT * FROM phpgw_cal_user WHERE cal_id='.$event_id,__LINE__,__FILE__);
659                                if($this->stream->num_rows())
660                                {
661                                        while($this->stream->next_record())
662                                        {
663                                                if((int)$this->stream->f('cal_login') == (int)$this->user)
664                                                {
665                                                        $this->add_attribute('users_status',$this->stream->f('cal_status'));
666                                                }
667                                                $this->add_attribute('participants',$this->stream->f('cal_status'),(int)$this->stream->f('cal_login'));
668                                        }
669                                }
670
671                        // Custom fields
672                                $this->stream->query('SELECT * FROM phpgw_cal_extra WHERE cal_id='.$event_id,__LINE__,__FILE__);
673                                if($this->stream->num_rows())
674                                {
675                                        while($this->stream->next_record())
676                                        {
677                                                $this->add_attribute('#'.$this->stream->f('cal_extra_name'),$this->stream->f('cal_extra_value'));
678                                        }
679                                }
680
681        /* OLD-ALARM
682                                if($this->event['reference'])
683                                {
684                                        // What is event['reference']???
685                                        $alarm_cal_id = $event_id.','.$this->event['reference'];
686                                }
687                                else
688                                {
689                                        $alarm_cal_id = $event_id;
690                                }
691
692                                //echo '<!-- cal_id='.$alarm_cal_id.' -->'."\n";
693                                //$this->stream->query('SELECT * FROM phpgw_cal_alarm WHERE cal_id in ('.$alarm_cal_id.') AND cal_owner='.$this->user,__LINE__,__FILE__);
694                                $this->stream->query('SELECT * FROM phpgw_cal_alarm WHERE cal_id='.$event_id.' AND cal_owner='.$this->user,__LINE__,__FILE__);
695                                if($this->stream->num_rows())
696                                {
697                                        while($this->stream->next_record())
698                                        {
699                                                $this->event['alarm'][] = Array(
700                                                        'id'            => (int)$this->stream->f('alarm_id'),
701                                                        'time'  => (int)$this->stream->f('cal_time'),
702                                                        'text'  => $this->stream->f('cal_text'),
703                                                        'enabled'       => (int)$this->stream->f('alarm_enabled')
704                                                );
705                                        }
706                                }
707        */
708                        }
709                        else
710                        {
711                                $this->event = False;
712                        }
713
714                        $this->stream->unlock();
715
716                        if ($this->event)
717                        {
718                                $this->event['alarm'] = $this->read_alarms($event_id);
719
720                                if($this->event['reference'])
721                                {
722                                        $this->event['alarm'] += $this->read_alarms($event_id);
723                                }
724                        }
725                        return $this->event;
726                }
727
728                function list_events($startYear,$startMonth,$startDay,$endYear=0,$endMonth=0,$endDay=0,$extra='',$tz_offset=0,$owner_id=0)
729                {
730                        if(!isset($this->stream))
731                        {
732                                return False;
733                        }
734
735                        $datetime = mktime(0,0,0,$startMonth,$startDay,$startYear) - $tz_offset;
736
737                        $user_where = ' AND (phpgw_cal_user.cal_login in (';
738                        if(is_array($owner_id) && count($owner_id))
739                        {
740                                $user_where .= implode(',',$owner_id);
741                        }
742                        else
743                        {
744                                $user_where .= $this->user . ') OR (phpgw_cal.owner=' . $this->user;
745                        }
746                        $member_groups = $GLOBALS['phpgw']->accounts->membership($this->user);
747                        @reset($member_groups);
748                        while($member_groups != False && list($key,$group_info) = each($member_groups))
749                        {
750                                $member[] = $group_info['account_id'];
751                        }
752                        @reset($member);
753        //              $user_where .= ','.implode(',',$member);
754                        $user_where .= ')) ';
755
756                        if($this->debug)
757                        {
758                                echo '<!-- '.$user_where.' -->'."\n";
759                        }
760
761                        $startDate = 'AND ( ( (phpgw_cal.datetime >= '.$datetime.') ';
762
763                        $enddate = '';
764                        if($endYear != 0 && $endMonth != 0 && $endDay != 0)
765                        {
766                                $edatetime = mktime(23,59,59,(int)$endMonth,(int)$endDay,(int)$endYear) - $tz_offset;
767                                $endDate .= 'AND (phpgw_cal.edatetime <= '.$edatetime.') ) '
768                                        . 'OR ( (phpgw_cal.datetime <= '.$datetime.') '
769                                        . 'AND (phpgw_cal.edatetime >= '.$edatetime.') ) '
770                                        . 'OR ( (phpgw_cal.datetime >= '.$datetime.') '
771                                        . 'AND (phpgw_cal.datetime <= '.$edatetime.') '
772                                        . 'AND (phpgw_cal.edatetime >= '.$edatetime.') ) '
773                                        . 'OR ( (phpgw_cal.datetime <= '.$datetime.') '
774                                        . 'AND (phpgw_cal.edatetime >= '.$datetime.') '
775                                        . 'AND (phpgw_cal.edatetime <= '.$edatetime.') ';
776                        }
777                        $endDate .= ') ) ';
778
779                        $order_by = 'ORDER BY phpgw_cal.datetime ASC, phpgw_cal.edatetime ASC, phpgw_cal.priority ASC';
780                        if($this->debug)
781                        {
782                                echo "SQL : ".$user_where.$startDate.$endDate.$extra."<br>\n";
783                        }
784                        return $this->get_event_ids(False,$user_where.$startDate.$endDate.$extra.$order_by);
785                }
786
787                function append_event()
788                {
789                        $this->save_event($this->event);
790                        $this->send_update(MSG_ADDED,$this->event->participants,'',$this->event);
791                        return $this->event['id'];
792                }
793
794                function store_event()
795                {
796                        return $this->save_event(&$this->event);
797                }
798
799                function delete_event($event_id)
800                {
801                        $this->deleted_events[] = $event_id;
802                }
803
804                function snooze($event_id)
805                {
806                //Turn off an alarm for an event
807                //Returns true.
808                }
809
810                function list_alarms($begin_year='',$begin_month='',$begin_day='',$end_year='',$end_month='',$end_day='')
811                {
812                //Return a list of events that has an alarm triggered at the given datetime
813                //Returns an array of event ID's
814                }
815
816                // The function definition doesn't look correct...
817                // Need more information for this function
818                function next_recurrence($weekstart,$next)
819                {
820        //              return next_recurrence (int stream, int weekstart, array next);
821                }
822
823                function expunge()
824                {
825                        if(count($this->deleted_events) <= 0)
826                        {
827                                return 1;
828                        }
829                        $this_event = $this->event;
830                        $locks = Array(
831                                'phpgw_cal',
832                                'phpgw_cal_user',
833                                'phpgw_cal_repeats',
834                                'phpgw_cal_extra'
835        // OLD-ALARM                    'phpgw_cal_alarm'
836                        );
837                        $this->stream->lock($locks);
838                        foreach($this->deleted_events as $cal_id)
839                        {
840                                foreach ($locks as $table)
841                                {
842                                        $this->stream->query('DELETE FROM '.$table.' WHERE cal_id='.$cal_id,__LINE__,__FILE__);
843                                }
844                        }
845                        $this->stream->unlock();
846
847                        foreach($this->deleted_events as $cal_id)
848                        {
849                                $this->delete_alarms($cal_id);
850                        }
851                        $this->deleted_events = array();
852
853                        $this->event = $this_event;
854                        return 1;
855                }
856
857                /***************** Local functions for SQL based Calendar *****************/
858
859                function get_event_ids($search_repeats=False,$extra='',$search_extra=False)
860                {
861                        $from = $where = ' ';
862                        if($search_repeats)
863                        {
864                                $from  = ', phpgw_cal_repeats ';
865                                $where = 'AND (phpgw_cal_repeats.cal_id = phpgw_cal.cal_id) ';
866                        }
867                        if($search_extra)
868                        {
869                                $from  .= 'LEFT JOIN phpgw_cal_extra ON phpgw_cal_extra.cal_id = phpgw_cal.cal_id ';
870                        }
871
872                        $sql = 'SELECT DISTINCT phpgw_cal.cal_id,'
873                                        . 'phpgw_cal.datetime,phpgw_cal.edatetime,'
874                                        . 'phpgw_cal.priority '
875                                        . 'FROM phpgw_cal_user, phpgw_cal'
876                                        . $from
877                                        . 'WHERE (phpgw_cal_user.cal_id = phpgw_cal.cal_id) '
878                                        . $where . $extra;
879
880                        if($this->debug)
881                        {
882                                echo "FULL SQL : ".$sql."<br>\n";
883                        }
884
885                        $this->stream->query($sql,__LINE__,__FILE__);
886
887                        $retval = Array();
888                        if($this->stream->num_rows() == 0)
889                        {
890                                if($this->debug)
891                                {
892                                        echo "No records found!<br>\n";
893                                }
894                                return $retval;
895                        }
896
897                        while($this->stream->next_record())
898                        {
899                                $retval[] = (int)$this->stream->f('cal_id');
900                        }
901                        if($this->debug)
902                        {
903                                echo "Records found!<br>\n";
904                        }
905                        return $retval;
906                }
907
908                function save_event(&$event,$sendMail = true, $importAccount = false)
909                {
910
911                        $GLOBALS['calendar']->bocalendar = CreateObject('calendar.bocalendar');
912
913                        $locks = Array(
914                                'phpgw_cal',
915                                'phpgw_cal_user',
916                                'phpgw_cal_repeats',
917                                'phpgw_cal_extra'
918        // OLD-ALARM                    'phpgw_cal_alarm'
919                        );
920                        $this->stream->lock($locks);
921                        if($event['id'] == 0)
922                        {
923                                if(!$event['uid'])
924                                {
925                                        if ($GLOBALS['phpgw_info']['server']['hostname'] != '')
926                                        {
927                                                $id_suffix = $GLOBALS['phpgw_info']['server']['hostname'];
928                                        }
929                                        else
930                                        {
931                                                $id_suffix = $GLOBALS['phpgw']->common->randomstring(3).'local';
932                                        }
933                                        $parts = Array(
934                                                0 => 'title',
935                                                1 => 'description',
936                                                2 => 'ex_participants'
937                                        );
938                                        @reset($parts);
939                                        while(list($key,$field) = each($parts))
940                                        {
941                                                $part[$key] = substr($GLOBALS['phpgw']->crypto->encrypt($event[$field]),0,20);
942                                                if(!$GLOBALS['phpgw']->crypto->enabled)
943                                                {
944                                                        $part[$key] = bin2hex(unserialize($part[$key]));
945                                                }
946                                        }
947                                        $event['uid'] = $part[0].'-'.$part[1].'@'.$id_suffix;
948                                }
949                                $this->stream->query('INSERT INTO phpgw_cal(uid,title,owner,priority,is_public,category) '
950                                        . "values('".$event['uid']."','".$this->stream->db_addslashes($event['title'])
951                                        . "',".(int)$event['owner'].','.(int)$event['priority'].','.(int)$event['public'].",'"
952                                        . $event['category']."')",__LINE__,__FILE__);
953                                $event['id'] = $this->stream->get_last_insert_id('phpgw_cal','cal_id');
954                                $last_status = true;
955                        }
956
957                        $date = $this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
958                        $enddate = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
959                        $today = time() - $GLOBALS['phpgw']->datetime->tz_offset;
960
961
962                                if ($event['type'] == 'hourAppointment')
963                                        $type = 'H';
964                                else if($event['type'] == 'privateHiddenFields'){
965                                        $type = 'P';
966                                }else
967                                        $type = 'E';
968                       
969
970                        $sql = 'UPDATE phpgw_cal SET '
971                                        . 'owner='.(int)$event['owner'].', '
972                                        . 'datetime='.(int)$date.', '
973                                        . 'mdatetime='.(int)$today.', '
974                                        . 'edatetime='.(int)$enddate.', '
975                                        . 'priority='.(int)$event['priority'].', '
976                                        . "category='".$this->stream->db_addslashes($event['category'])."', "
977                                        . "cal_type='".$this->stream->db_addslashes($type)."', "
978                                        . 'is_public='.(int)$event['public'].', '
979                                        . "title='".$this->stream->db_addslashes($event['title'])."', "
980                                        . "description='".$this->stream->db_addslashes($event['description'])."', "
981                                        . "ex_participants='".$this->stream->db_addslashes($event['ex_participants'])."', "
982                                        . "organizer='".$this->stream->db_addslashes($event['organizer'])."', "
983                                        . "location='".$this->stream->db_addslashes($event['location'])."', "
984                                        . ($event['groups']?"groups='".(count($event['groups'])>1?implode(',',$event['groups']):','.$event['groups'][0].',')."', ":'')
985                                        . 'reference='.(int)$event['reference'].' '
986                                        . ',last_status = '.($last_status ? "'N'" : "'U'").',last_update = '.time()."000". ' '
987                                        . 'WHERE cal_id='.(int)$event['id'];
988
989                        $this->stream->query($sql,__LINE__,__FILE__);
990
991                        $this->stream->query('DELETE FROM phpgw_cal_user WHERE cal_id='.(int)$event['id'],__LINE__,__FILE__);
992
993                        @reset($event['participants']);
994                        while (list($key,$value) = @each($event['participants']))
995                        {
996                                if((int)$key == $event['owner'])
997                                {
998                                        $value = 'A';
999                                }
1000                                $this->stream->query('INSERT INTO phpgw_cal_user(cal_id,cal_login,cal_status) '
1001                                        . 'VALUES('.(int)$event['id'].','.(int)$key.",'".$this->stream->db_addslashes($value)."')",__LINE__,__FILE__);
1002                        }
1003
1004                        if($event['recur_type'] != MCAL_RECUR_NONE)
1005                        {
1006                                if($event['recur_enddate']['month'] != 0 && $event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['year'] != 0)
1007                                {
1008                                        $end = $this->maketime($event['recur_enddate']) - $GLOBALS['phpgw']->datetime->tz_offset;
1009                                }
1010                                else
1011                                {
1012                                        $end = 0;
1013                                }
1014
1015                                $this->stream->query('SELECT count(cal_id) FROM phpgw_cal_repeats WHERE cal_id='.(int)$event['id'],__LINE__,__FILE__);
1016                                $this->stream->next_record();
1017                                $num_rows = $this->stream->f(0);
1018                                if($num_rows == 0)
1019                                {
1020                                        $this->stream->query('INSERT INTO phpgw_cal_repeats(cal_id,recur_type,recur_enddate,recur_data,recur_interval) '
1021                                                .'VALUES('.(int)$event['id'].','.$event['recur_type'].','.(int)$end.','.$event['recur_data'].','.$event['recur_interval'].')',__LINE__,__FILE__);
1022                                }
1023                                else
1024                                {
1025                                        $this->stream->query('UPDATE phpgw_cal_repeats '
1026                                                . 'SET recur_type='.$event['recur_type'].', '
1027                                                . 'recur_enddate='.(int)$end.', '
1028                                                . 'recur_data='.$event['recur_data'].', '
1029                                                . 'recur_interval='.$event['recur_interval'].', '
1030                                                . "recur_exception='".(count($event['recur_exception'])>1?implode(',',$event['recur_exception']):(count($event['recur_exception'])==1?$event['recur_exception'][0]:''))."' "
1031                                                . 'WHERE cal_id='.$event['id'],__LINE__,__FILE__);
1032                                }
1033
1034                        }
1035                        else
1036                        {
1037                                $this->stream->query('DELETE FROM phpgw_cal_repeats WHERE cal_id='.$event['id'],__LINE__,__FILE__);
1038                        }
1039                        // Custom fields
1040                        $this->stream->query('DELETE FROM phpgw_cal_extra WHERE cal_id='.$event['id'],__LINE__,__FILE__);
1041
1042                        foreach($event as $name => $value)
1043                        {
1044                                if ($name[0] == '#' && strlen($value))
1045                                {
1046                                        $this->stream->query('INSERT INTO phpgw_cal_extra (cal_id,cal_extra_name,cal_extra_value) '
1047                                        . 'VALUES('.$event['id'].",'".addslashes(substr($name,1))."','".addslashes($value)."')",__LINE__,__FILE__);
1048                                }
1049                        }
1050        /*
1051                        $alarmcount = count($event['alarm']);
1052                        if ($alarmcount > 1)
1053                        {
1054                                // this should never happen, $event['alarm'] should only be set
1055                                // if creating a new event and uicalendar only sets up 1 alarm
1056                                // the user must use "Alarm Management" to create/establish multiple
1057                                // alarms or to edit/change an alarm
1058                                echo '<!-- how did this happen, too many alarms -->'."\n";
1059                                $this->stream->unlock();
1060                                return True;
1061                        }
1062
1063                        if ($alarmcount == 1)
1064                        {
1065
1066                                list($key,$alarm) = @each($event['alarm']);
1067
1068                                $this->stream->query('INSERT INTO phpgw_cal_alarm(cal_id,cal_owner,cal_time,cal_text,alarm_enabled) VALUES('.$event['id'].','.$event['owner'].','.$alarm['time'].",'".$alarm['text']."',".$alarm['enabled'].')',__LINE__,__FILE__);
1069                                $this->stream->query('SELECT LAST_INSERT_ID()');
1070                                $this->stream->next_record();
1071                                $alarm['id'] = $this->stream->f(0);
1072                        }
1073        */
1074                        print_debug('Event Saved: ID #',$event['id']);
1075
1076                        $this->stream->unlock();
1077
1078                        if (is_array($event['alarm']))
1079                        {
1080                                foreach ($event['alarm'] as $alarm)     // this are all new alarms
1081                                {
1082                                        $this->save_alarm($event['id'],$alarm);
1083                                }
1084                        }
1085                        $GLOBALS['phpgw_info']['cal_new_event_id'] = $event['id'];
1086                        $this->event = $event;
1087
1088                        if($sendMail)
1089                        {
1090                            if($importAccount)
1091                                $this->sendEmailEvendAccepted($event,$importAccount);
1092                            else
1093                                $this->sendEmailEvendAccepted($event);
1094                        }
1095       
1096                        return True;
1097                }
1098
1099                function sendEmailEvendAccepted($event,$importAccount = false)
1100                {
1101
1102                    if(!$importAccount)
1103                        $importAccount['mail'] = $GLOBALS['phpgw_info']['user']['email'];
1104
1105                    //verifica se eh um evento externo se sim envia o vcard de aceitação em anexo
1106                    if($event['owner'] == '-2')
1107                    {
1108                        $mailService = ServiceLocator::getService('mail');
1109
1110                        $tmpbody.= "<b>".lang("Event Accepted")."</b> ";
1111                        $tmpbody.= "<br><br>".lang("name").": ".$event['title']."<br>";
1112                        $tmpbody.= "<br>".lang("description").": ".$event['description']."<br>";
1113
1114                        $ev[0] = $event;
1115
1116                        $tmpattach=  $GLOBALS['calendar']->bocalendar->create_vcard($ev,'REPLY',true,$importAccount);
1117                       
1118                        $mailService->addStringAttachment($tmpattach, 'suggestion.ics', 'application/ics');
1119                        $mailService->addStringAttachment($tmpattach, 'vcalendar.ics', 'utf-8', 'text/calendar; charset=utf-8; method=REPLY;', '7bit', '');
1120                 
1121                        if(strchr($event['organizer'],'@') && strchr($event['organizer'],'<') && strchr($event['organizer'],'>'))
1122                        {
1123                            $mail = substr($event['organizer'], strpos($event['organizer'],'<'), strpos($event['organizer'],'>'));
1124                            $mail = str_replace('<','', str_replace('>','',$mail));
1125                        }
1126
1127                        if($mail)
1128                            $mailService->sendMail($mail,$importAccount['mail'],$event['title'],$tmpbody);
1129
1130                    }
1131                    else
1132                        $GLOBALS['calendar']->bocalendar->send_update(MSG_ACCEPTED, $event['participants'],$event);
1133
1134                    return;
1135                }
1136
1137                function get_alarm($cal_id)
1138                {
1139        /* OLD-ALARM
1140                        $this->stream->query('SELECT cal_time, cal_text FROM phpgw_cal_alarm WHERE cal_id='.$id.' AND cal_owner='.$this->user,__LINE__,__FILE__);
1141                        if($this->stream->num_rows())
1142                        {
1143                                while($this->stream->next_record())
1144                                {
1145                                        $alarm[$this->stream->f('cal_time')] = $this->stream->f('cal_text');
1146                                }
1147                                @reset($alarm);
1148                                return $alarm;
1149                        }
1150                        else
1151                        {
1152                                return False;
1153                        }
1154        */
1155                        $alarms = $this->read_alarms($cal_id);
1156                        $ret = False;
1157
1158                        foreach($alarms as $alarm)
1159                        {
1160                                if ($alarm['owner'] == $this->user || !$alarm['owner'])
1161                                {
1162                                        $ret[$alarm['time']] = $alarm['text'];
1163                                }
1164                        }
1165                        return $ret;
1166                }
1167
1168                function set_status($id,$owner,$status)
1169                {
1170                        $status_code_short = Array(
1171                                REJECTED =>     'R',
1172                                NO_RESPONSE     => 'U',
1173                                TENTATIVE       =>      'T',
1174                                ACCEPTED        =>      'A'
1175                        );
1176
1177                        $this->stream->query("UPDATE phpgw_cal_user SET cal_status='".$status_code_short[$status]."' WHERE cal_id=".$id." AND cal_login=".$owner,__LINE__,__FILE__);
1178        /* OLD-ALARM
1179                        if ($status == 'R')
1180                        {
1181                                $this->stream->query('UPDATE phpgw_cal_alarm set alarm_enabled=0 where cal_id='.$id.' and cal_owner='.$owner,__LINE__,__FILE__);
1182                        }
1183        */
1184                        return True;
1185                }
1186
1187        // End of ICal style support.......
1188
1189                function group_search($owner=0)
1190                {
1191                        $owner = ($owner==$GLOBALS['phpgw_info']['user']['account_id']?0:$owner);
1192                        $groups = substr($GLOBALS['phpgw']->common->sql_search('phpgw_cal.groups',(int)$owner),4);
1193                        if (!$groups)
1194                        {
1195                                return '';
1196                        }
1197                        else
1198                        {
1199                                return "(phpgw_cal.is_public=2 AND (". $groups .')) ';
1200                        }
1201                }
1202
1203                function splittime_($time)
1204                {
1205                        $temp = array('hour','minute','second','ampm');
1206                        $time = strrev($time);
1207                        $second = (int)strrev(substr($time,0,2));
1208                        $minute = (int)strrev(substr($time,2,2));
1209                        $hour   = (int)strrev(substr($time,4));
1210                        $temp['second'] = (int)$second;
1211                        $temp['minute'] = (int)$minute;
1212                        $temp['hour']   = (int)$hour;
1213                        $temp['ampm']   = '  ';
1214
1215                        return $temp;
1216                }
1217
1218                function date_to_epoch($d)
1219                {
1220                        return $this->localdates(mktime(0,0,0,(int)(substr($d,4,2)),(int)(substr($d,6,2)),(int)(substr($d,0,4))));
1221                }
1222
1223                function list_dirty_events($lastmod=-1,$repeats=false)
1224                {
1225                        if(!isset($this->stream))
1226                        {
1227                                return False;
1228                        }
1229                        $lastmod = (int)  $lastmod;
1230                        $repeats = (bool) $repeats;
1231
1232                        $user_where = " AND phpgw_cal_user.cal_login = $this->user";
1233
1234                        $member_groups = $GLOBALS['phpgw']->accounts->membership($this->user);
1235                        @reset($member_groups);
1236                        while($member_groups != False && list($key,$group_info) = each($member_groups))
1237                        {
1238                                $member[] = $group_info['account_id'];
1239                        }
1240                        @reset($member);
1241        //              $user_where .= ','.implode(',',$member);
1242                        //$user_where .= ')) ';
1243
1244                        if($this->debug)
1245                        {
1246                                echo '<!-- '.$user_where.' -->'."\n";
1247                        }
1248
1249                        if($lastmod > 0)
1250                        {
1251                                $wheremod = "AND mdatetime = $lastmod";
1252                        }
1253
1254                        $order_by = ' ORDER BY phpgw_cal.cal_id ASC';
1255                        if($this->debug)
1256                        {
1257                                echo "SQL : ".$user_where.$wheremod.$extra."<br>\n";
1258                        }
1259                        return $this->get_event_ids($repeats,$user_where.$wheremod.$extra.$order_by);
1260                }
1261
1262        /* OLD-ALARM
1263                function add_alarm($eventid,$alarm,$owner)
1264                {
1265                        $this->stream->query('INSERT INTO phpgw_cal_alarm(cal_id,cal_owner,cal_time,cal_text,alarm_enabled) VALUES('.$eventid.','.$owner.','.$alarm['time'].",'".$alarm['text']."',1)",__LINE__,__FILE__);
1266                        $this->stream->query('SELECT LAST_INSERT_ID()');
1267                        $this->stream->next_record();
1268                        return($this->stream->f(0));
1269                }
1270                function delete_alarm($alarmid)
1271                {
1272                        $this->stream->query('DELETE FROM phpgw_cal_alarm WHERE alarm_id='.$alarmid,__LINE__,__FILE__);
1273                }
1274        */
1275        }
Note: See TracBrowser for help on using the repository browser.