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