]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Event/EventPlugin.php
01e6da902cefefa5a38f0f57505dafa421dcd138
[quix0rs-gnu-social.git] / plugins / Event / EventPlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2011, StatusNet, Inc.
5  *
6  * Microapp plugin for event invitations and RSVPs
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Event
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2011 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     // This check helps protect against security problems;
33     // your code file can't be executed directly from the web.
34     exit(1);
35 }
36
37 /**
38  * Event plugin
39  *
40  * @category  Event
41  * @package   StatusNet
42  * @author    Evan Prodromou <evan@status.net>
43  * @copyright 2011 StatusNet, Inc.
44  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
45  * @link      http://status.net/
46  */
47 class EventPlugin extends MicroAppPlugin
48 {
49
50     var $oldSaveNew = true;
51
52     /**
53      * Set up our tables (event and rsvp)
54      *
55      * @see Schema
56      * @see ColumnDef
57      *
58      * @return boolean hook value; true means continue processing, false means stop.
59      */
60     function onCheckSchema()
61     {
62         $schema = Schema::get();
63
64         $schema->ensureTable('happening', Happening::schemaDef());
65         $schema->ensureTable('rsvp', RSVP::schemaDef());
66
67         return true;
68     }
69
70     public function onBeforePluginCheckSchema()
71     {
72         RSVP::beforeSchemaUpdate();
73         return true;
74     }
75
76     /**
77      * Map URLs to actions
78      *
79      * @param URLMapper $m path-to-action mapper
80      *
81      * @return boolean hook value; true means continue processing, false means stop.
82      */
83     public function onRouterInitialized(URLMapper $m)
84     {
85         $m->connect('main/event/new',
86                     array('action' => 'newevent'));
87         $m->connect('main/event/rsvp',
88                     array('action' => 'newrsvp'));
89         $m->connect('main/event/rsvp/cancel',
90                     array('action' => 'cancelrsvp'));
91         $m->connect('event/:id',
92                     array('action' => 'showevent'),
93                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
94         $m->connect('rsvp/:id',
95                     array('action' => 'showrsvp'),
96                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
97         $m->connect('main/event/updatetimes',
98                     array('action' => 'timelist'));
99
100         $m->connect(':nickname/events',
101                     array('action' => 'events'),
102                     array('nickname' => Nickname::DISPLAY_FMT));
103         return true;
104     }
105
106     function onPluginVersion(array &$versions)
107     {
108         $versions[] = array('name' => 'Event',
109                             'version' => GNUSOCIAL_VERSION,
110                             'author' => 'Evan Prodromou',
111                             'homepage' => 'http://status.net/wiki/Plugin:Event',
112                             'description' =>
113                             // TRANS: Plugin description.
114                             _m('Event invitations and RSVPs.'));
115         return true;
116     }
117
118     function appTitle() {
119         // TRANS: Title for event application.
120         return _m('TITLE','Event');
121     }
122
123     function tag() {
124         return 'event';
125     }
126
127     function types() {
128         return array(Happening::OBJECT_TYPE);
129     }
130
131     function verbs() {
132         return array(ActivityVerb::POST,
133                      RSVP::POSITIVE,
134                      RSVP::NEGATIVE,
135                      RSVP::POSSIBLE);
136     }
137
138     /**
139      * Given a parsed ActivityStreams activity, save it into a notice
140      * and other data structures.
141      *
142      * @param Activity $activity
143      * @param Profile $actor
144      * @param array $options=array()
145      *
146      * @return Notice the resulting notice
147      */
148     function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
149     {
150         if (count($activity->objects) != 1) {
151             // TRANS: Exception thrown when there are too many activity objects.
152             throw new Exception(_m('Too many activity objects.'));
153         }
154
155         $happeningObj = $activity->objects[0];
156
157         if ($happeningObj->type != Happening::OBJECT_TYPE) {
158             // TRANS: Exception thrown when event plugin comes across a non-event type object.
159             throw new Exception(_m('Wrong type for object.'));
160         }
161
162         $dtstart = $happeningObj->element->getElementsByTagName('dtstart');
163         if($dtstart->length == 0) {
164             // TRANS: Exception thrown when has no start date
165             throw new Exception(_m('No start date for event.'));
166         }
167
168         $dtend = $happeningObj->element->getElementsByTagName('dtend');
169         if($dtend->length == 0) {
170             // TRANS: Exception thrown when has no end date
171             throw new Exception(_m('No end date for event.'));
172         }
173
174         // convert RFC3339 dates delivered in Activity Stream to MySQL DATETIME date format
175         $start_time = new DateTime($dtstart->item(0)->nodeValue);
176         $start_time->setTimezone(new DateTimeZone('UTC'));
177         $start_time = $start_time->format('Y-m-d H:i:s');
178         $end_time = new DateTime($dtend->item(0)->nodeValue);
179         $end_time->setTimezone(new DateTimeZone('UTC'));
180         $end_time = $end_time->format('Y-m-d H:i:s');
181
182         // location is optional
183         $location = null;
184         $location_object = $happeningObj->element->getElementsByTagName('location');
185         if($location_object->length > 0) {
186             $location = $location_object->item(0)->nodeValue;
187         }
188
189         // url is optional
190         $url = null;
191         $url_object = $happeningObj->element->getElementsByTagName('url');
192         if($url_object->length > 0) {
193             $url = $url_object->item(0)->nodeValue;
194         }
195
196         switch ($activity->verb) {
197         case ActivityVerb::POST:
198                 // FIXME: get startTime, endTime, location and URL
199             $notice = Happening::saveNew($actor,
200                                          $start_time,
201                                          $end_time,
202                                          $happeningObj->title,
203                                          $location,
204                                          $happeningObj->summary,
205                                          $url,
206                                          $options);
207             break;
208         case RSVP::POSITIVE:
209         case RSVP::NEGATIVE:
210         case RSVP::POSSIBLE:
211             return Notice::saveActivity($activity, $actor, $options);
212             break;
213         default:
214             // TRANS: Exception thrown when event plugin comes across a undefined verb.
215             throw new Exception(_m('Unknown verb for events.'));
216         }
217     }
218
219     protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
220     {
221         $happeningObj = $activity->objects[0];
222
223         switch ($activity->verb) {
224         case RSVP::POSITIVE:
225         case RSVP::NEGATIVE:
226         case RSVP::POSSIBLE:
227             $happening = Happening::getKV('uri', $happeningObj->id);
228             if (empty($happening)) {
229                 // FIXME: save the event
230                 // TRANS: Exception thrown when trying to RSVP for an unknown event.
231                 throw new Exception(_m('RSVP for unknown event.'));
232             }
233             $object = RSVP::saveNewFromNotice($stored, $happening, $activity->verb);
234             // Our data model expects this
235             $stored->object_type = $activity->verb;
236             return $object;
237             break;
238         default:
239             common_log(LOG_ERR, 'Unknown verb for events.');
240             return NULL;
241         }
242     }
243
244     /**
245      * Turn a Notice into an activity object
246      *
247      * @param Notice $notice
248      *
249      * @return ActivityObject
250      */
251     function activityObjectFromNotice(Notice $notice)
252     {
253         $happening = null;
254
255         switch ($notice->object_type) {
256         case Happening::OBJECT_TYPE:
257             $happening = Happening::fromNotice($notice);
258             break;
259         case RSVP::POSITIVE:
260         case RSVP::NEGATIVE:
261         case RSVP::POSSIBLE:
262             $rsvp  = RSVP::fromNotice($notice);
263             $happening = $rsvp->getEvent();
264             break;
265         }
266
267         if (empty($happening)) {
268             // TRANS: Exception thrown when event plugin comes across a unknown object type.
269             throw new Exception(_m('Unknown object type.'));
270         }
271
272         $notice = $happening->getNotice();
273
274         if (empty($notice)) {
275             // TRANS: Exception thrown when referring to a notice that is not an event an in event context.
276             throw new Exception(_m('Unknown event notice.'));
277         }
278
279         $obj = new ActivityObject();
280
281         $obj->id      = $happening->uri;
282         $obj->type    = Happening::OBJECT_TYPE;
283         $obj->title   = $happening->title;
284         $obj->summary = $happening->description;
285         $obj->link    = $notice->getUrl();
286
287         // XXX: how to get this stuff into JSON?!
288
289         $obj->extra[] = array('dtstart',
290                               array('xmlns' => 'urn:ietf:params:xml:ns:xcal'),
291                               common_date_iso8601($happening->start_time));
292
293         $obj->extra[] = array('dtend',
294                               array('xmlns' => 'urn:ietf:params:xml:ns:xcal'),
295                               common_date_iso8601($happening->end_time));
296
297         $obj->extra[] = array('location', false, $happening->location);
298         $obj->extra[] = array('url', false, $happening->url);
299
300         // XXX: probably need other stuff here
301
302         return $obj;
303     }
304
305     /**
306      * Change the verb on RSVP notices
307      *
308      * @param Notice $notice
309      *
310      * @return ActivityObject
311      */
312     protected function extendActivity(Notice $stored, Activity $act, Profile $scoped=null) {
313         switch ($stored->object_type) {
314         case RSVP::POSITIVE:
315         case RSVP::NEGATIVE:
316         case RSVP::POSSIBLE:
317             $act->verb = $stored->object_type;
318             break;
319         }
320         return true;
321     }
322
323     /**
324      * Form for our app
325      *
326      * @param HTMLOutputter $out
327      * @return Widget
328      */
329     function entryForm($out)
330     {
331         return new EventForm($out);
332     }
333
334     /**
335      * When a notice is deleted, clean up related tables.
336      *
337      * @param Notice $notice
338      */
339     function deleteRelated(Notice $notice)
340     {
341         switch ($notice->object_type) {
342         case Happening::OBJECT_TYPE:
343             common_log(LOG_DEBUG, "Deleting event from notice...");
344             $happening = Happening::fromNotice($notice);
345             $happening->delete();
346             break;
347         case RSVP::POSITIVE:
348         case RSVP::NEGATIVE:
349         case RSVP::POSSIBLE:
350             common_log(LOG_DEBUG, "Deleting rsvp from notice...");
351             $rsvp = RSVP::fromNotice($notice);
352             common_log(LOG_DEBUG, "to delete: $rsvp->id");
353             $rsvp->delete();
354             break;
355         default:
356             common_log(LOG_DEBUG, "Not deleting related, wtf...");
357         }
358     }
359
360     function onEndShowScripts($action)
361     {
362         $action->script($this->path('js/event.js'));
363     }
364
365     function onEndShowStyles($action)
366     {
367         $action->cssLink($this->path('css/event.css'));
368         return true;
369     }
370
371     function onStartAddNoticeReply($nli, $parent, $child)
372     {
373         // Filter out any poll responses
374         if (($parent->object_type == Happening::OBJECT_TYPE) &&
375             in_array($child->object_type, array(RSVP::POSITIVE, RSVP::NEGATIVE, RSVP::POSSIBLE))) {
376             return false;
377         }
378         return true;
379     }
380
381     protected function showNoticeItemNotice(NoticeListItem $nli)
382     {
383         $nli->showAuthor();
384         $nli->showContent();
385     }
386
387     protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
388     {
389         switch ($stored->object_type) {
390         case Happening::OBJECT_TYPE:
391             $this->showEvent($stored, $out, $scoped);
392             break;
393         case RSVP::POSITIVE:
394         case RSVP::NEGATIVE:
395         case RSVP::POSSIBLE:
396             $this->showRSVP($stored, $out, $scoped);
397             break;
398         }
399     }
400
401     protected function showEvent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
402     {
403         $profile = $stored->getProfile();
404         $event   = Happening::fromNotice($stored);
405
406         if (!$event instanceof Happening) {
407             // TRANS: Content for a deleted RSVP list item (RSVP stands for "please respond").
408             $out->element('p', null, _m('Deleted.'));
409             return;
410         }
411
412         $out->elementStart('div', 'h-event');
413
414         $out->elementStart('h3', 'p-summary p-name');
415
416         try {
417             $out->element('a', array('href' => $event->getUrl()), $event->title);
418         } catch (InvalidUrlException $e) {
419             $out->text($event->title);
420         }
421
422         $out->elementEnd('h3');
423
424         $now       = new DateTime();
425         $startDate = new DateTime($event->start_time);
426         $endDate   = new DateTime($event->end_time);
427         $userTz    = new DateTimeZone(common_timezone());
428
429         // Localize the time for the observer
430         $now->setTimeZone($userTz);
431         $startDate->setTimezone($userTz);
432         $endDate->setTimezone($userTz);
433
434         $thisYear  = $now->format('Y');
435         $startYear = $startDate->format('Y');
436         $endYear   = $endDate->format('Y');
437
438         $dateFmt = 'D, F j, '; // e.g.: Mon, Aug 31
439
440         if ($startYear != $thisYear || $endYear != $thisYear) {
441             $dateFmt .= 'Y,'; // append year if we need to think about years
442         }
443
444         $startDateStr = $startDate->format($dateFmt);
445         $endDateStr = $endDate->format($dateFmt);
446
447         $timeFmt = 'g:ia';
448
449         $startTimeStr = $startDate->format($timeFmt);
450         $endTimeStr = $endDate->format("{$timeFmt} (T)");
451
452         $out->elementStart('div', 'event-times'); // VEVENT/EVENT-TIMES IN
453
454         // TRANS: Field label for event description.
455         $out->element('strong', null, _m('Time:'));
456
457         $out->element('time', array('class' => 'dt-start',
458                                     'datetime' => common_date_iso8601($event->start_time)),
459                       $startDateStr . ' ' . $startTimeStr);
460         $out->text(' – ');
461         $out->element('time', array('class' => 'dt-end',
462                                     'datetime' => common_date_iso8601($event->end_time)),
463                       $startDateStr != $endDateStr
464                                     ? "$endDateStr $endTimeStr"
465                                     :  $endTimeStr);
466
467         $out->elementEnd('div'); // VEVENT/EVENT-TIMES OUT
468
469         if (!empty($event->location)) {
470             $out->elementStart('div', 'event-location');
471             // TRANS: Field label for event description.
472             $out->element('strong', null, _m('Location:'));
473             $out->element('span', 'p-location', $event->location);
474             $out->elementEnd('div');
475         }
476
477         if (!empty($event->description)) {
478             $out->elementStart('div', 'event-description');
479             // TRANS: Field label for event description.
480             $out->element('strong', null, _m('Description:'));
481             $out->element('div', 'p-description', $event->description);
482             $out->elementEnd('div');
483         }
484
485         $rsvps = $event->getRSVPs();
486
487         $out->elementStart('div', 'event-rsvps');
488
489         // TRANS: Field label for event description.
490         $out->element('strong', null, _m('Attending:'));
491         $out->elementStart('ul', 'attending-list');
492
493         foreach ($rsvps as $verb => $responses) {
494             $out->elementStart('li', 'rsvp-list');
495             switch ($verb) {
496             case RSVP::POSITIVE:
497                 $out->text(_('Yes:'));
498                 break;
499             case RSVP::NEGATIVE:
500                 $out->text(_('No:'));
501                 break;
502             case RSVP::POSSIBLE:
503                 $out->text(_('Maybe:'));
504                 break;
505             }
506             $ids = array();
507             foreach ($responses as $response) {
508                 $ids[] = $response->profile_id;
509             }
510             $ids = array_slice($ids, 0, ProfileMiniList::MAX_PROFILES + 1);
511             $minilist = new ProfileMiniList(Profile::multiGet('id', $ids), $out);
512             $minilist->show();
513
514             $out->elementEnd('li');
515         }
516
517         $out->elementEnd('ul');
518         $out->elementEnd('div');
519
520         if ($scoped instanceof Profile) {
521             $rsvp = $event->getRSVP($scoped);
522
523             if (empty($rsvp)) {
524                 $form = new RSVPForm($event, $out);
525             } else {
526                 $form = new CancelRSVPForm($rsvp, $out);
527             }
528
529             $form->show();
530         }
531         $out->elementEnd('div');
532     }
533
534     protected function showRSVP(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
535     {
536         $rsvp = RSVP::fromNotice($stored);
537
538         if (empty($rsvp)) {
539             // TRANS: Content for a deleted RSVP list item (RSVP stands for "please respond").
540             $out->element('p', null, _m('Deleted.'));
541             return;
542         }
543
544         $out->elementStart('div', 'rsvp');
545         $out->raw($rsvp->asHTML());
546         $out->elementEnd('div');
547     }
548
549     function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
550     {
551         $menu->menuItem(common_local_url('events', array('nickname' => $target->getNickname())),
552                           // TRANS: Menu item in sample plugin.
553                           _m('Happenings'),
554                           // TRANS: Menu item title in sample plugin.
555                           _m('A list of your events'), false, 'nav_timeline_events');
556         return true;
557     }
558 }