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