]> git.mxchange.org Git - friendica.git/blob - include/event.php
implement a public calendar for vistors of someones profile page
[friendica.git] / include / event.php
1 <?php
2 /**
3  * @file include/event.php
4  * @brief functions specific to event handling
5  */
6
7 require_once('include/bbcode.php');
8 require_once('include/map.php');
9 require_once('include/datetime.php');
10
11 function format_event_html($ev, $simple = false) {
12
13
14
15         if(! ((is_array($ev)) && count($ev)))
16                 return '';
17
18         $bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
19
20         $event_start = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
21                         $ev['start'] , $bd_format ))
22                         :  day_translate(datetime_convert('UTC', 'UTC',
23                         $ev['start'] , $bd_format)));
24
25         $event_end = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
26                                 $ev['finish'] , $bd_format ))
27                                 :  day_translate(datetime_convert('UTC', 'UTC',
28                                 $ev['finish'] , $bd_format )));
29
30         if ($simple) {
31                 $o = "<h3>".bbcode($ev['summary'])."</h3>";
32
33                 $o .= "<p>".bbcode($ev['desc'])."</p>";
34
35                 $o .= "<h4>".t('Starts:')."</h4><p>".$event_start."</p>";
36
37                 if(! $ev['nofinish'])
38                         $o .= "<h4>".t('Finishes:')."</h4><p>".$event_end."</p>";
39
40                 if(strlen($ev['location']))
41                         $o .= "<h4>".t('Location:')."</h4><p>".$ev['location']."</p>";
42
43                 return $o;
44         }
45
46         $o = '<div class="vevent">' . "\r\n";
47
48
49         $o .= '<p class="summary event-summary">' . bbcode($ev['summary']) .  '</p>' . "\r\n";
50
51         $o .= '<p class="description event-description">' . bbcode($ev['desc']) .  '</p>' . "\r\n";
52
53         $o .= '<p class="event-start">' . t('Starts:') . ' <abbr class="dtstart" title="'
54                 . datetime_convert('UTC','UTC',$ev['start'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
55                 . '" >'.$event_start
56                 . '</abbr></p>' . "\r\n";
57
58         if(! $ev['nofinish'])
59                 $o .= '<p class="event-end" >' . t('Finishes:') . ' <abbr class="dtend" title="'
60                         . datetime_convert('UTC','UTC',$ev['finish'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
61                         . '" >'.$event_end
62                         . '</abbr></p>'  . "\r\n";
63
64         if(strlen($ev['location'])){
65                 $o .= '<p class="event-location"> ' . t('Location:') . ' <span class="location">'
66                         . bbcode($ev['location'])
67                         . '</span></p>' . "\r\n";
68
69                 if (strpos($ev['location'], "[map") !== False) {
70                         $map = generate_named_map($ev['location']);
71                         if ($map!==$ev['location']) $o.=$map;
72                 }
73
74         }
75
76         $o .= '</div>' . "\r\n";
77         return $o;
78 }
79
80 /*
81 function parse_event($h) {
82
83         require_once('include/Scrape.php');
84         require_once('include/html2bbcode');
85
86         $h = '<html><body>' . $h . '</body></html>';
87
88         $ret = array();
89
90
91         try {
92                 $dom = HTML5_Parser::parse($h);
93         } catch (DOMException $e) {
94                 logger('parse_event: parse error: ' . $e);
95         }
96
97         if(! $dom)
98                 return $ret;
99
100         $items = $dom->getElementsByTagName('*');
101
102         foreach($items as $item) {
103                 if(attribute_contains($item->getAttribute('class'), 'vevent')) {
104                         $level2 = $item->getElementsByTagName('*');
105                         foreach($level2 as $x) {
106                                 if(attribute_contains($x->getAttribute('class'),'dtstart') && $x->getAttribute('title')) {
107                                         $ret['start'] = $x->getAttribute('title');
108                                         if(! strpos($ret['start'],'Z'))
109                                                 $ret['adjust'] = true;
110                                 }
111                                 if(attribute_contains($x->getAttribute('class'),'dtend') && $x->getAttribute('title'))
112                                         $ret['finish'] = $x->getAttribute('title');
113
114                                 if(attribute_contains($x->getAttribute('class'),'description'))
115                                         $ret['desc'] = $x->textContent;
116                                 if(attribute_contains($x->getAttribute('class'),'location'))
117                                         $ret['location'] = $x->textContent;
118                         }
119                 }
120         }
121
122         // sanitise
123
124         if((x($ret,'desc')) && ((strpos($ret['desc'],'<') !== false) || (strpos($ret['desc'],'>') !== false))) {
125                 $config = HTMLPurifier_Config::createDefault();
126                 $config->set('Cache.DefinitionImpl', null);
127                 $purifier = new HTMLPurifier($config);
128                 $ret['desc'] = html2bbcode($purifier->purify($ret['desc']));
129         }
130
131         if((x($ret,'location')) && ((strpos($ret['location'],'<') !== false) || (strpos($ret['location'],'>') !== false))) {
132                 $config = HTMLPurifier_Config::createDefault();
133                 $config->set('Cache.DefinitionImpl', null);
134                 $purifier = new HTMLPurifier($config);
135                 $ret['location'] = html2bbcode($purifier->purify($ret['location']));
136         }
137
138         if(x($ret,'start'))
139                 $ret['start'] = datetime_convert('UTC','UTC',$ret['start']);
140         if(x($ret,'finish'))
141                 $ret['finish'] = datetime_convert('UTC','UTC',$ret['finish']);
142
143         return $ret;
144 }
145 */
146
147 function format_event_bbcode($ev) {
148
149         $o = '';
150
151         if($ev['summary'])
152                 $o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';
153
154         if($ev['desc'])
155                 $o .= '[event-description]' . $ev['desc'] . '[/event-description]';
156
157         if($ev['start'])
158                 $o .= '[event-start]' . $ev['start'] . '[/event-start]';
159
160         if(($ev['finish']) && (! $ev['nofinish']))
161                 $o .= '[event-finish]' . $ev['finish'] . '[/event-finish]';
162
163         if($ev['location'])
164                 $o .= '[event-location]' . $ev['location'] . '[/event-location]';
165
166         if($ev['adjust'])
167                 $o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
168
169
170         return $o;
171
172 }
173
174 function bbtovcal($s) {
175         $o = '';
176         $ev = bbtoevent($s);
177         if($ev['desc'])
178                 $o = format_event_html($ev);
179         return $o;
180 }
181
182
183 function bbtoevent($s) {
184
185         $ev = array();
186
187         $match = '';
188         if(preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is",$s,$match))
189                 $ev['summary'] = $match[1];
190         $match = '';
191         if(preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is",$s,$match))
192                 $ev['desc'] = $match[1];
193         $match = '';
194         if(preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is",$s,$match))
195                 $ev['start'] = $match[1];
196         $match = '';
197         if(preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is",$s,$match))
198                 $ev['finish'] = $match[1];
199         $match = '';
200         if(preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is",$s,$match))
201                 $ev['location'] = $match[1];
202         $match = '';
203         if(preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is",$s,$match))
204                 $ev['adjust'] = $match[1];
205         $ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
206         return $ev;
207
208 }
209
210
211 function sort_by_date($a) {
212
213         usort($a,'ev_compare');
214         return $a;
215 }
216
217
218 function ev_compare($a,$b) {
219
220         $date_a = (($a['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$a['start']) : $a['start']);
221         $date_b = (($b['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$b['start']) : $b['start']);
222
223         if($date_a === $date_b)
224                 return strcasecmp($a['desc'],$b['desc']);
225
226         return strcmp($date_a,$date_b);
227 }
228
229 function event_delete($event_id) {
230         if ($event_id == 0)
231                 return;
232
233         q("DELETE FROM `event` WHERE `id` = %d", intval($event_id));
234         logger("Deleted event ".$event_id, LOGGER_DEBUG);
235 }
236
237 function event_store($arr) {
238
239         require_once('include/datetime.php');
240         require_once('include/items.php');
241         require_once('include/bbcode.php');
242
243         $a = get_app();
244
245         $arr['created'] = (($arr['created']) ? $arr['created'] : datetime_convert());
246         $arr['edited']  = (($arr['edited']) ? $arr['edited'] : datetime_convert());
247         $arr['type']    = (($arr['type']) ? $arr['type'] : 'event' );
248         $arr['cid']     = ((intval($arr['cid'])) ? intval($arr['cid']) : 0);
249         $arr['uri']     = (x($arr,'uri') ? $arr['uri'] : item_new_uri($a->get_hostname(),$arr['uid']));
250         $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0);
251
252         if($arr['cid'])
253                 $c = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
254                         intval($arr['cid']),
255                         intval($arr['uid'])
256                 );
257         else
258                 $c = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
259                         intval($arr['uid'])
260                 );
261
262         if(count($c))
263                 $contact = $c[0];
264
265
266         // Existing event being modified
267
268         if($arr['id']) {
269
270                 // has the event actually changed?
271
272                 $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
273                         intval($arr['id']),
274                         intval($arr['uid'])
275                 );
276                 if((! count($r)) || ($r[0]['edited'] === $arr['edited'])) {
277
278                         // Nothing has changed. Grab the item id to return.
279
280                         $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
281                                 intval($arr['id']),
282                                 intval($arr['uid'])
283                         );
284                         return((count($r)) ? $r[0]['id'] : 0);
285                 }
286
287                 // The event changed. Update it.
288
289                 $r = q("UPDATE `event` SET
290                         `edited` = '%s',
291                         `start` = '%s',
292                         `finish` = '%s',
293                         `summary` = '%s',
294                         `desc` = '%s',
295                         `location` = '%s',
296                         `type` = '%s',
297                         `adjust` = %d,
298                         `nofinish` = %d,
299                         WHERE `id` = %d AND `uid` = %d",
300
301                         dbesc($arr['edited']),
302                         dbesc($arr['start']),
303                         dbesc($arr['finish']),
304                         dbesc($arr['summary']),
305                         dbesc($arr['desc']),
306                         dbesc($arr['location']),
307                         dbesc($arr['type']),
308                         intval($arr['adjust']),
309                         intval($arr['nofinish']),
310                         intval($arr['id']),
311                         intval($arr['uid'])
312                 );
313                 $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
314                         intval($arr['id']),
315                         intval($arr['uid'])
316                 );
317                 if(count($r)) {
318                         $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
319                         $object .= '<content>' . xmlify(format_event_bbcode($arr)) . '</content>';
320                         $object .= '</object>' . "\n";
321
322
323                         q("UPDATE `item` SET `body` = '%s', `object` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d",
324                                 dbesc(format_event_bbcode($arr)),
325                                 dbesc($object),
326                                 dbesc($arr['edited']),
327                                 intval($r[0]['id']),
328                                 intval($arr['uid'])
329                         );
330
331                         $item_id = $r[0]['id'];
332                 } else
333                         $item_id = 0;
334
335                 call_hooks("event_updated", $arr['id']);
336
337                 return $item_id;
338         }
339         else {
340
341                 // New event. Store it.
342
343                 $r = q("INSERT INTO `event` ( `uid`,`cid`,`uri`,`created`,`edited`,`start`,`finish`,`summary`, `desc`,`location`,`type`,
344                         `adjust`,`nofinish`,`allow_cid`,`allow_gid`,`deny_cid`,`deny_gid`)
345                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
346                         intval($arr['uid']),
347                         intval($arr['cid']),
348                         dbesc($arr['uri']),
349                         dbesc($arr['created']),
350                         dbesc($arr['edited']),
351                         dbesc($arr['start']),
352                         dbesc($arr['finish']),
353                         dbesc($arr['summary']),
354                         dbesc($arr['desc']),
355                         dbesc($arr['location']),
356                         dbesc($arr['type']),
357                         intval($arr['adjust']),
358                         intval($arr['nofinish']),
359                         dbesc($arr['allow_cid']),
360                         dbesc($arr['allow_gid']),
361                         dbesc($arr['deny_cid']),
362                         dbesc($arr['deny_gid'])
363
364                 );
365
366                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
367                         dbesc($arr['uri']),
368                         intval($arr['uid'])
369                 );
370                 if(count($r))
371                         $event = $r[0];
372
373                 $item_arr = array();
374
375                 $item_arr['uid']           = $arr['uid'];
376                 $item_arr['contact-id']    = $arr['cid'];
377                 $item_arr['uri']           = $arr['uri'];
378                 $item_arr['parent-uri']    = $arr['uri'];
379                 $item_arr['guid']          = $arr['guid'];
380                 $item_arr['type']          = 'activity';
381                 $item_arr['wall']          = (($arr['cid']) ? 0 : 1);
382                 $item_arr['contact-id']    = $contact['id'];
383                 $item_arr['owner-name']    = $contact['name'];
384                 $item_arr['owner-link']    = $contact['url'];
385                 $item_arr['owner-avatar']  = $contact['thumb'];
386                 $item_arr['author-name']   = $contact['name'];
387                 $item_arr['author-link']   = $contact['url'];
388                 $item_arr['author-avatar'] = $contact['thumb'];
389                 $item_arr['title']         = '';
390                 $item_arr['allow_cid']     = $arr['allow_cid'];
391                 $item_arr['allow_gid']     = $arr['allow_gid'];
392                 $item_arr['deny_cid']      = $arr['deny_cid'];
393                 $item_arr['deny_gid']      = $arr['deny_gid'];
394                 $item_arr['private']       = $arr['private'];
395                 $item_arr['last-child']    = 1;
396                 $item_arr['visible']       = 1;
397                 $item_arr['verb']          = ACTIVITY_POST;
398                 $item_arr['object-type']   = ACTIVITY_OBJ_EVENT;
399                 $item_arr['origin']        = ((intval($arr['cid']) == 0) ? 1 : 0);
400                 $item_arr['body']          = format_event_bbcode($event);
401
402
403                 $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
404                 $item_arr['object'] .= '<content>' . xmlify(format_event_bbcode($event)) . '</content>';
405                 $item_arr['object'] .= '</object>' . "\n";
406
407                 $item_id = item_store($item_arr);
408
409                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
410                         intval($arr['uid'])
411                 );
412                 //if(count($r))
413                 //      $plink = $a->get_baseurl() . '/display/' . $r[0]['nickname'] . '/' . $item_id;
414
415
416                 if($item_id) {
417                         //q("UPDATE `item` SET `plink` = '%s', `event-id` = %d  WHERE `uid` = %d AND `id` = %d",
418                         //      dbesc($plink),
419                         //      intval($event['id']),
420                         //      intval($arr['uid']),
421                         //      intval($item_id)
422                         //);
423                         q("UPDATE `item` SET `event-id` = %d  WHERE `uid` = %d AND `id` = %d",
424                                 intval($event['id']),
425                                 intval($arr['uid']),
426                                 intval($item_id)
427                         );
428                 }
429
430                 call_hooks("event_created", $event['id']);
431
432                 return $item_id;
433         }
434 }
435
436 function get_event_strings() {
437         // First day of the week (0 = Sunday)
438         $firstDay = get_pconfig(local_user(),'system','first_day_of_week');
439         if ($firstDay === false) $firstDay=0;
440
441         $i18n = array(
442                         "firstDay" => $firstDay,
443                         "Sun" => t("Sun"),
444                         "Mon" => t("Mon"),
445                         "Tue" => t("Tue"),
446                         "Wed" => t("Wed"),
447                         "Thu" => t("Thu"),
448                         "Fri" => t("Fri"),
449                         "Sat" => t("Sat"),
450                         "Sunday" => t("Sunday"),
451                         "Monday" => t("Monday"),
452                         "Tuesday" => t("Tuesday"),
453                         "Wednesday" => t("Wednesday"),
454                         "Thursday" => t("Thursday"),
455                         "Friday" => t("Friday"),
456                         "Saturday" => t("Saturday"),
457                         "Jan" => t("Jan"),
458                         "Feb" => t("Feb"),
459                         "Mar" => t("Mar"),
460                         "Apr" => t("Apr"),
461                         "May" => t("May"),
462                         "Jun" => t("Jun"),
463                         "Jul" => t("Jul"),
464                         "Aug" => t("Aug"),
465                         "Sep" => t("Sept"),
466                         "Oct" => t("Oct"),
467                         "Nov" => t("Nov"),
468                         "Dec" => t("Dec"),
469                         "January" => t("January"),
470                         "February" => t("February"),
471                         "March" => t("March"),
472                         "April" => t("April"),
473                         "May" => t("May"),
474                         "June" => t("June"),
475                         "July" => t("July"),
476                         "August" => t("August"),
477                         "September" => t("September"),
478                         "October" => t("October"),
479                         "November" => t("November"),
480                         "December" => t("December"),
481                         "today" => t("today"),
482                         "month" => t("month"),
483                         "week" => t("week"),
484                         "day" => t("day"),
485                 );
486
487         return $i18n;
488 }
489
490 /**
491  * @brief Get an event by its event ID
492  * 
493  * @param type $owner_uid The User ID of the owner of the event
494  * @param type $event_params An assoziative array with
495  *      int 'event_id' => The ID of the event in the event table
496  * @param type $sql_extra
497  * @return array Query result
498  */
499 function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
500         // ownly allow events if there is a valid owner_id
501         if($owner_uid == 0)
502                 return;
503
504         // query for the event by event id
505         $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
506                         `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
507                 LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
508                 WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
509                 intval($owner_uid),
510                 intval($event_params["event_id"])
511         );
512
513         if(count($r))
514                 return $r;
515
516 }
517
518 /**
519  * @brief Get all events in a specific timeframe
520  * 
521  * @param int $owner_uid The User ID of the owner of the events
522  * @param array $event_params An assoziative array with
523  *      int 'ignored' => 
524  *      string 'start' => Start time of the timeframe
525  *      string 'finish' => Finish time of the timeframe
526  *      string 'adjust_start' => 
527  *      string 'adjust_start' =>
528  *      
529  * @param string $sql_extra Additional sql conditions (e.g. permission request)
530  * @return array Query results
531  */
532 function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
533         // ownly allow events if there is a valid owner_id
534         if($owner_uid == 0)
535                 return;
536
537         // query for the event by date
538         $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
539                                 `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
540                         LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
541                         WHERE `event`.`uid` = %d AND event.ignore = %d
542                         AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
543                         OR  (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
544                         $sql_extra ",
545                         intval($owner_uid),
546                         intval($event_params["ignored"]),
547                         dbesc($event_params["start"]),
548                         dbesc($event_params["start"]),
549                         dbesc($event_params["finish"]),
550                         dbesc($event_params["adjust_start"]),
551                         dbesc($event_params["adjust_start"]),
552                         dbesc($event_params["adjust_finish"])
553         );
554
555         if(count($r))
556                 return $r;
557 }
558
559 /**
560  * @brief Convert an array query results in an arry which could be used by the events template
561  * 
562  * @param array $arr Event query array
563  * @return array Event array for the template
564  */
565 function process_events ($arr) {
566         $events=array();
567
568         $last_date = '';
569         $fmt = t('l, F j');
570         if (count($arr)) {
571                 foreach($arr as $rr) {
572
573                         $j = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], 'j') : datetime_convert('UTC','UTC',$rr['start'],'j'));
574                         $d = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], $fmt) : datetime_convert('UTC','UTC',$rr['start'],$fmt));
575                         $d = day_translate($d);
576
577                         $start = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['start'], 'c') : datetime_convert('UTC','UTC',$rr['start'],'c'));
578                         if ($rr['nofinish']){
579                                 $end = null;
580                         } else {
581                                 $end = (($rr['adjust']) ? datetime_convert('UTC',date_default_timezone_get(),$rr['finish'], 'c') : datetime_convert('UTC','UTC',$rr['finish'],'c'));
582                         }
583
584
585                         $is_first = ($d !== $last_date);
586
587                         $last_date = $d;
588                         $edit = ((! $rr['cid']) ? array(App::get_baseurl().'/events/event/'.$rr['id'],t('Edit event'),'','') : null);
589                         $title = strip_tags(html_entity_decode(bbcode($rr['summary']),ENT_QUOTES,'UTF-8'));
590                         if(! $title) {
591                                 list($title, $_trash) = explode("<br",bbcode($rr['desc']),2);
592                                 $title = strip_tags(html_entity_decode($title,ENT_QUOTES,'UTF-8'));
593                         }
594
595                         $html = format_event_html($rr);
596                         $rr['desc'] = bbcode($rr['desc']);
597                         $rr['location'] = bbcode($rr['location']);
598                         $events[] = array(
599                                 'id'=>$rr['id'],
600                                 'start'=> $start,
601                                 'end' => $end,
602                                 'allDay' => false,
603                                 'title' => $title,
604
605                                 'j' => $j,
606                                 'd' => $d,
607                                 'is_first'=>$is_first,
608                                 'item'=>$rr,
609                                 'html'=>$html,
610                                 'plink' => array($rr['plink'],t('link to source'),'',''),
611                         );
612                 }
613         }
614
615         return $events;
616 }