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('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                      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         $notice = null;
193
194         switch ($activity->verb) {
195         case ActivityVerb::POST:
196                 // FIXME: get startTime, endTime, location and URL
197             $notice = Happening::saveNew($actor,
198                                          $start_time,
199                                          $end_time,
200                                          $happeningObj->title,
201                                          $location,
202                                          $happeningObj->summary,
203                                          $url,
204                                          $options);
205             break;
206         case RSVP::POSITIVE:
207         case RSVP::NEGATIVE:
208         case RSVP::POSSIBLE:
209             $happening = Happening::getKV('uri', $happeningObj->id);
210             if (empty($happening)) {
211                 // FIXME: save the event
212                 // TRANS: Exception thrown when trying to RSVP for an unknown event.
213                 throw new Exception(_m('RSVP for unknown event.'));
214             }
215             $notice = RSVP::saveNew($actor, $happening, $activity->verb, $options);
216             break;
217         default:
218             // TRANS: Exception thrown when event plugin comes across a undefined verb.
219             throw new Exception(_m('Unknown verb for events.'));
220         }
221
222         return $notice;
223     }
224
225     /**
226      * Turn a Notice into an activity object
227      *
228      * @param Notice $notice
229      *
230      * @return ActivityObject
231      */
232     function activityObjectFromNotice(Notice $notice)
233     {
234         $happening = null;
235
236         switch ($notice->object_type) {
237         case Happening::OBJECT_TYPE:
238             $happening = Happening::fromNotice($notice);
239             break;
240         case RSVP::POSITIVE:
241         case RSVP::NEGATIVE:
242         case RSVP::POSSIBLE:
243             $rsvp  = RSVP::fromNotice($notice);
244             $happening = $rsvp->getEvent();
245             break;
246         }
247
248         if (empty($happening)) {
249             // TRANS: Exception thrown when event plugin comes across a unknown object type.
250             throw new Exception(_m('Unknown object type.'));
251         }
252
253         $notice = $happening->getNotice();
254
255         if (empty($notice)) {
256             // TRANS: Exception thrown when referring to a notice that is not an event an in event context.
257             throw new Exception(_m('Unknown event notice.'));
258         }
259
260         $obj = new ActivityObject();
261
262         $obj->id      = $happening->uri;
263         $obj->type    = Happening::OBJECT_TYPE;
264         $obj->title   = $happening->title;
265         $obj->summary = $happening->description;
266         $obj->link    = $notice->getUrl();
267
268         // XXX: how to get this stuff into JSON?!
269
270         $obj->extra[] = array('dtstart',
271                               array('xmlns' => 'urn:ietf:params:xml:ns:xcal'),
272                               common_date_iso8601($happening->start_time));
273
274         $obj->extra[] = array('dtend',
275                               array('xmlns' => 'urn:ietf:params:xml:ns:xcal'),
276                               common_date_iso8601($happening->end_time));
277
278         $obj->extra[] = array('location', false, $happening->location);
279         $obj->extra[] = array('url', false, $happening->url);
280
281         // XXX: probably need other stuff here
282
283         return $obj;
284     }
285
286     /**
287      * Change the verb on RSVP notices
288      *
289      * @param Notice $notice
290      *
291      * @return ActivityObject
292      */
293     protected function extendActivity(Notice $stored, Activity $act, Profile $scoped=null) {
294         switch ($stored->object_type) {
295         case RSVP::POSITIVE:
296         case RSVP::NEGATIVE:
297         case RSVP::POSSIBLE:
298             $act->verb = $stored->object_type;
299             break;
300         }
301         return true;
302     }
303
304     /**
305      * Form for our app
306      *
307      * @param HTMLOutputter $out
308      * @return Widget
309      */
310     function entryForm($out)
311     {
312         return new EventForm($out);
313     }
314
315     /**
316      * When a notice is deleted, clean up related tables.
317      *
318      * @param Notice $notice
319      */
320     function deleteRelated(Notice $notice)
321     {
322         switch ($notice->object_type) {
323         case Happening::OBJECT_TYPE:
324             common_debug("Deleting event from notice...");
325             $happening = Happening::fromNotice($notice);
326             $happening->delete();
327             break;
328         case RSVP::POSITIVE:
329         case RSVP::NEGATIVE:
330         case RSVP::POSSIBLE:
331             common_debug("Deleting rsvp from notice...");
332             $rsvp = RSVP::fromNotice($notice);
333             common_debug("to delete: $rsvp->id");
334             $rsvp->delete();
335             break;
336         default:
337             common_debug("Not deleting related, wtf...");
338         }
339     }
340
341     function onEndShowScripts(Action $action)
342     {
343         $action->script($this->path('js/event.js'));
344     }
345
346     function onEndShowStyles(Action $action)
347     {
348         $action->cssLink($this->path('css/event.css'));
349         return true;
350     }
351
352     function onStartAddNoticeReply($nli, $parent, $child)
353     {
354         // Filter out any poll responses
355         if (($parent->object_type == Happening::OBJECT_TYPE) &&
356             in_array($child->object_type, array(RSVP::POSITIVE, RSVP::NEGATIVE, RSVP::POSSIBLE))) {
357             return false;
358         }
359         return true;
360     }
361
362     protected function showNoticeItemNotice(NoticeListItem $nli)
363     {
364         $nli->showAuthor();
365         $nli->showContent();
366     }
367
368     protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
369     {
370         switch ($stored->object_type) {
371         case Happening::OBJECT_TYPE:
372             $this->showEvent($stored, $out, $scoped);
373             break;
374         case RSVP::POSITIVE:
375         case RSVP::NEGATIVE:
376         case RSVP::POSSIBLE:
377             $this->showRSVP($stored, $out, $scoped);
378             break;
379         }
380     }
381
382     protected function showEvent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
383     {
384         $profile = $stored->getProfile();
385         $event   = Happening::fromNotice($stored);
386
387         if (!$event instanceof Happening) {
388             // TRANS: Content for a deleted RSVP list item (RSVP stands for "please respond").
389             $out->element('p', null, _m('Deleted.'));
390             return;
391         }
392
393         $out->elementStart('div', 'h-event');
394
395         $out->elementStart('h3', 'p-summary p-name');
396
397         try {
398             $out->element('a', array('href' => $event->getUrl()), $event->title);
399         } catch (InvalidUrlException $e) {
400             $out->text($event->title);
401         }
402
403         $out->elementEnd('h3');
404
405         $now       = new DateTime();
406         $startDate = new DateTime($event->start_time);
407         $endDate   = new DateTime($event->end_time);
408         $userTz    = new DateTimeZone(common_timezone());
409
410         // Localize the time for the observer
411         $now->setTimeZone($userTz);
412         $startDate->setTimezone($userTz);
413         $endDate->setTimezone($userTz);
414
415         $thisYear  = $now->format('Y');
416         $startYear = $startDate->format('Y');
417         $endYear   = $endDate->format('Y');
418
419         $dateFmt = 'D, F j, '; // e.g.: Mon, Aug 31
420
421         if ($startYear != $thisYear || $endYear != $thisYear) {
422             $dateFmt .= 'Y,'; // append year if we need to think about years
423         }
424
425         $startDateStr = $startDate->format($dateFmt);
426         $endDateStr = $endDate->format($dateFmt);
427
428         $timeFmt = 'g:ia';
429
430         $startTimeStr = $startDate->format($timeFmt);
431         $endTimeStr = $endDate->format("{$timeFmt} (T)");
432
433         $out->elementStart('div', 'event-times'); // VEVENT/EVENT-TIMES IN
434
435         // TRANS: Field label for event description.
436         $out->element('strong', null, _m('Time:'));
437
438         $out->element('time', array('class' => 'dt-start',
439                                     'datetime' => common_date_iso8601($event->start_time)),
440                       $startDateStr . ' ' . $startTimeStr);
441         $out->text(' – ');
442         $out->element('time', array('class' => 'dt-end',
443                                     'datetime' => common_date_iso8601($event->end_time)),
444                       $startDateStr != $endDateStr
445                                     ? "$endDateStr $endTimeStr"
446                                     :  $endTimeStr);
447
448         $out->elementEnd('div'); // VEVENT/EVENT-TIMES OUT
449
450         if (!empty($event->location)) {
451             $out->elementStart('div', 'event-location');
452             // TRANS: Field label for event description.
453             $out->element('strong', null, _m('Location:'));
454             $out->element('span', 'p-location', $event->location);
455             $out->elementEnd('div');
456         }
457
458         if (!empty($event->description)) {
459             $out->elementStart('div', 'event-description');
460             // TRANS: Field label for event description.
461             $out->element('strong', null, _m('Description:'));
462             $out->element('div', 'p-description', $event->description);
463             $out->elementEnd('div');
464         }
465
466         $rsvps = $event->getRSVPs();
467
468         $out->elementStart('div', 'event-rsvps');
469
470         // TRANS: Field label for event description.
471         $out->element('strong', null, _m('Attending:'));
472         $out->elementStart('ul', 'attending-list');
473
474         foreach ($rsvps as $verb => $responses) {
475             $out->elementStart('li', 'rsvp-list');
476             switch ($verb) {
477             case RSVP::POSITIVE:
478                 $out->text(_('Yes:'));
479                 break;
480             case RSVP::NEGATIVE:
481                 $out->text(_('No:'));
482                 break;
483             case RSVP::POSSIBLE:
484                 $out->text(_('Maybe:'));
485                 break;
486             }
487             $ids = array();
488             foreach ($responses as $response) {
489                 $ids[] = $response->profile_id;
490             }
491             $ids = array_slice($ids, 0, ProfileMiniList::MAX_PROFILES + 1);
492             $minilist = new ProfileMiniList(Profile::multiGet('id', $ids), $out);
493             $minilist->show();
494
495             $out->elementEnd('li');
496         }
497
498         $out->elementEnd('ul');
499         $out->elementEnd('div');
500
501         if ($scoped instanceof Profile) {
502             $rsvp = $event->getRSVP($scoped);
503
504             if (empty($rsvp)) {
505                 $form = new RSVPForm($event, $out);
506             } else {
507                 $form = new CancelRSVPForm($rsvp, $out);
508             }
509
510             $form->show();
511         }
512         $out->elementEnd('div');
513     }
514
515     protected function showRSVP(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
516     {
517         $rsvp = RSVP::fromNotice($stored);
518
519         if (empty($rsvp)) {
520             // TRANS: Content for a deleted RSVP list item (RSVP stands for "please respond").
521             $out->element('p', null, _m('Deleted.'));
522             return;
523         }
524
525         $out->elementStart('div', 'rsvp');
526         $out->raw($rsvp->asHTML());
527         $out->elementEnd('div');
528     }
529
530     function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
531     {
532         $menu->menuItem(common_local_url('events', array('nickname' => $target->getNickname())),
533                           // TRANS: Menu item in sample plugin.
534                           _m('Happenings'),
535                           // TRANS: Menu item title in sample plugin.
536                           _m('A list of your events'), false, 'nav_timeline_events');
537         return true;
538     }
539 }