]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Event/classes/RSVP.php
f6b8c0aa7c847a2a28509132f8a6d9ebe8209df0
[quix0rs-gnu-social.git] / plugins / Event / classes / RSVP.php
1 <?php
2 /**
3  * Data class for event RSVPs
4  *
5  * PHP version 5
6  *
7  * @category Data
8  * @package  StatusNet
9  * @author   Evan Prodromou <evan@status.net>
10  * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
11  * @link     http://status.net/
12  *
13  * StatusNet - the distributed open-source microblogging tool
14  * Copyright (C) 2011, StatusNet, Inc.
15  *
16  * This program is free software: you can redistribute it and/or modify
17  * it under the terms of the GNU Affero General Public License as published by
18  * the Free Software Foundation, either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
24  * GNU Affero General Public License for more details.
25  *
26  * You should have received a copy of the GNU Affero General Public License
27  * along with this program. If not, see <http://www.gnu.org/licenses/>.
28  */
29
30 if (!defined('GNUSOCIAL')) { exit(1); }
31
32 /**
33  * Data class for event RSVPs
34  *
35  * @category Event
36  * @package  StatusNet
37  * @author   Evan Prodromou <evan@status.net>
38  * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
39  * @link     http://status.net/
40  *
41  * @see      Managed_DataObject
42  */
43 class RSVP extends Managed_DataObject
44 {
45     const POSITIVE = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
46     const POSSIBLE = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
47     const NEGATIVE = 'http://activitystrea.ms/schema/1.0/rsvp-no';
48
49     public $__table = 'rsvp'; // table name
50     public $id;                // varchar(36) UUID
51     public $uri;               // varchar(191)   not 255 because utf8mb4 takes more space
52     public $profile_id;        // int
53     public $event_uri;         // varchar(191)   not 255 because utf8mb4 takes more space
54     public $response;            // tinyint
55     public $created;           // datetime
56
57     /**
58      * The One True Thingy that must be defined and declared.
59      */
60     public static function schemaDef()
61     {
62         return array(
63             'description' => 'Plan to attend event',
64             'fields' => array(
65                 'id' => array('type' => 'char',
66                               'length' => 36,
67                               'not null' => true,
68                               'description' => 'UUID'),
69                 'uri' => array('type' => 'varchar',
70                                'length' => 191,
71                                'not null' => true),
72                 'profile_id' => array('type' => 'int'),
73                 'event_uri' => array('type' => 'varchar',
74                               'length' => 191,
75                               'not null' => true,
76                               'description' => 'Event URI'),
77                 'response' => array('type' => 'char',
78                                   'length' => '1',
79                                   'description' => 'Y, N, or ? for three-state yes, no, maybe'),
80                 'created' => array('type' => 'datetime',
81                                    'not null' => true),
82             ),
83             'primary key' => array('id'),
84             'unique keys' => array(
85                 'rsvp_uri_key' => array('uri'),
86                 'rsvp_profile_event_key' => array('profile_id', 'event_uri'),
87             ),
88             'foreign keys' => array('rsvp_event_uri_key' => array('happening', array('event_uri' => 'uri')),
89                                     'rsvp_profile_id__key' => array('profile', array('profile_id' => 'id'))),
90             'indexes' => array('rsvp_created_idx' => array('created')),
91         );
92     }
93
94     static public function beforeSchemaUpdate()
95     {
96         $table = strtolower(get_called_class());
97         $schema = Schema::get();
98         $schemadef = $schema->getTableDef($table);
99
100         // 2015-12-31 RSVPs refer to Happening by event_uri now, not event_id. Let's migrate!
101         if (isset($schemadef['fields']['event_uri'])) {
102             // We seem to have already migrated, good!
103             return;
104         }
105
106         // this is a "normal" upgrade from StatusNet for example
107         echo "\nFound old $table table, upgrading it to add 'event_uri' field...";
108
109         $schemadef['fields']['event_uri'] = array('type' => 'varchar', 'length' => 191, 'not null' => true, 'description' => 'Event URI');
110         $schema->ensureTable($table, $schemadef);
111
112         $rsvp = new RSVP();
113         $rsvp->find();
114         while ($rsvp->fetch()) {
115             $event = Happening::getKV('id', $rsvp->event_id);
116             if (!$event instanceof Happening) {
117                 $rsvp->delete();
118                 continue;
119             }
120             $orig = clone($rsvp);
121             $rsvp->event_uri = $event->uri;
122             $rsvp->updateWithKeys($orig);
123         }
124         print "DONE.\n";
125         print "Resuming core schema upgrade...";
126     }
127
128     function saveNew(Profile $profile, $event, $verb, array $options = array())
129     {
130         $eventNotice = $event->getNotice();
131         $options = array_merge(array('source' => 'web'), $options);
132
133         $act = new Activity();
134         $act->type    = ActivityObject::ACTIVITY;
135         $act->verb    = $verb;
136         $act->time    = $options['created'] ? strtotime($options['created']) : time();
137         $act->title   = _m("RSVP");
138         $act->actor   = $profile->asActivityObject();
139         $act->target  = $eventNotice->asActivityObject();
140         $act->objects = array(clone($act->target));
141         $act->content = RSVP::toHTML($profile, $event, self::codeFor($verb));
142
143         $act->id = common_local_url('showrsvp', array('id' => UUID::gen()));
144         $act->link = $act->id;
145
146         $saved = Notice::saveActivity($act, $profile, $options);
147
148         return $saved;
149     }
150
151     function saveNewFromNotice($notice, $event, $verb)
152     {
153         $other = RSVP::getKV('uri', $notice->uri);
154         if (!empty($other)) {
155             // TRANS: Client exception thrown when trying to save an already existing RSVP ("please respond").
156             throw new ClientException(_m('RSVP already exists.'));
157         }
158
159         $profile = $notice->getProfile();
160
161         try {
162             $other = RSVP::getByKeys( [ 'profile_id' => $profile->getID(),
163                                         'event_uri' => $event->getUri(),
164                                       ] );
165             // TRANS: Client exception thrown when trying to save an already existing RSVP ("please respond").
166             throw new AlreadyFulfilledException(_m('RSVP already exists.'));
167         } catch (NoResultException $e) {
168             // No previous RSVP, so go ahead and add.
169         }
170
171         $rsvp = new RSVP();
172
173         preg_match('/\/([^\/]+)\/*/', $notice->uri, $match);
174         $rsvp->id          = $match[1] ? $match[1] : UUID::gen();
175         $rsvp->profile_id  = $profile->id;
176         $rsvp->event_id    = $event->id;
177         $rsvp->response    = self::codeFor($verb);
178         $rsvp->created     = $notice->created;
179         $rsvp->uri         = $notice->uri;
180
181         $rsvp->insert();
182
183         self::blow('rsvp:for-event:%s', $event->getUri());
184
185         return $rsvp;
186     }
187
188     function codeFor($verb)
189     {
190         switch ($verb) {
191         case RSVP::POSITIVE:
192             return 'Y';
193             break;
194         case RSVP::NEGATIVE:
195             return 'N';
196             break;
197         case RSVP::POSSIBLE:
198             return '?';
199             break;
200         default:
201             // TRANS: Exception thrown when requesting an undefined verb for RSVP.
202             throw new Exception(sprintf(_m('Unknown verb "%s".'),$verb));
203         }
204     }
205
206     static function verbFor($code)
207     {
208         switch ($code) {
209         case 'Y':
210             return RSVP::POSITIVE;
211             break;
212         case 'N':
213             return RSVP::NEGATIVE;
214             break;
215         case '?':
216             return RSVP::POSSIBLE;
217             break;
218         default:
219             // TRANS: Exception thrown when requesting an undefined code for RSVP.
220             throw new Exception(sprintf(_m('Unknown code "%s".'),$code));
221         }
222     }
223
224     function getNotice()
225     {
226         $notice = Notice::getKV('uri', $this->uri);
227         if (empty($notice)) {
228             // TRANS: Server exception thrown when requesting a non-exsting notice for an RSVP ("please respond").
229             // TRANS: %s is the RSVP with the missing notice.
230             throw new ServerException(sprintf(_m('RSVP %s does not correspond to a notice in the database.'),$this->id));
231         }
232         return $notice;
233     }
234
235     static function fromNotice(Notice $notice)
236     {
237         $rsvp = new RSVP();
238         $rsvp->uri = $notice->uri;
239         if (!$rsvp->find(true)) {
240             throw new NoResultException($rsvp);
241         }
242         return $rsvp;
243     }
244
245     static function forEvent(Happening $event)
246     {
247         $keypart = sprintf('rsvp:for-event:%s', $event->getUri());
248
249         $idstr = self::cacheGet($keypart);
250
251         if ($idstr !== false) {
252             $ids = explode(',', $idstr);
253         } else {
254             $ids = array();
255
256             $rsvp = new RSVP();
257
258             $rsvp->selectAdd();
259             $rsvp->selectAdd('id');
260
261             $rsvp->event_uri = $event->getUri();
262
263             if ($rsvp->find()) {
264                 while ($rsvp->fetch()) {
265                     $ids[] = $rsvp->id;
266                 }
267             }
268             self::cacheSet($keypart, implode(',', $ids));
269         }
270
271         $rsvps = array(RSVP::POSITIVE => array(),
272                        RSVP::NEGATIVE => array(),
273                        RSVP::POSSIBLE => array());
274
275         foreach ($ids as $id) {
276             $rsvp = RSVP::getKV('id', $id);
277             if (!empty($rsvp)) {
278                 $verb = self::verbFor($rsvp->response);
279                 $rsvps[$verb][] = $rsvp;
280             }
281         }
282
283         return $rsvps;
284     }
285
286     function getProfile()
287     {
288         $profile = Profile::getKV('id', $this->profile_id);
289         if (empty($profile)) {
290             // TRANS: Exception thrown when requesting a non-existing profile.
291             // TRANS: %s is the ID of the non-existing profile.
292             throw new Exception(sprintf(_m('No profile with ID %s.'),$this->profile_id));
293         }
294         return $profile;
295     }
296
297     function getEvent()
298     {
299         $event = Happening::getKV('uri', $this->event_uri);
300         if (empty($event)) {
301             // TRANS: Exception thrown when requesting a non-existing event.
302             // TRANS: %s is the ID of the non-existing event.
303             throw new Exception(sprintf(_m('No event with URI %s.'),$this->event_uri));
304         }
305         return $event;
306     }
307
308     function asHTML()
309     {
310         return self::toHTML($this->getProfile(),
311                             $this->getEvent(),
312                             $this->response);
313     }
314
315     function asString()
316     {
317         return self::toString($this->getProfile(),
318                               $this->getEvent(),
319                               $this->response);
320     }
321
322     static function toHTML(Profile $profile, Event $event, $response)
323     {
324         $fmt = null;
325
326         switch ($response) {
327         case 'Y':
328             // TRANS: HTML version of an RSVP ("please respond") status for a user.
329             // TRANS: %1$s is a profile URL, %2$s a profile name,
330             // TRANS: %3$s is an event URL, %4$s an event title.
331             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> is attending <a href='%3\$s'>%4\$s</a>.</span>");
332             break;
333         case 'N':
334             // TRANS: HTML version of an RSVP ("please respond") status for a user.
335             // TRANS: %1$s is a profile URL, %2$s a profile name,
336             // TRANS: %3$s is an event URL, %4$s an event title.
337             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> is not attending <a href='%3\$s'>%4\$s</a>.</span>");
338             break;
339         case '?':
340             // TRANS: HTML version of an RSVP ("please respond") status for a user.
341             // TRANS: %1$s is a profile URL, %2$s a profile name,
342             // TRANS: %3$s is an event URL, %4$s an event title.
343             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> might attend <a href='%3\$s'>%4\$s</a>.</span>");
344             break;
345         default:
346             // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
347             // TRANS: %s is the non-existing response code.
348             throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
349         }
350
351         if (empty($event)) {
352             $eventUrl = '#';
353             // TRANS: Used as event title when not event title is available.
354             // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
355             $eventTitle = _m('an unknown event');
356         } else {
357             $notice = $event->getNotice();
358             $eventUrl = $notice->getUrl();
359             $eventTitle = $event->title;
360         }
361
362         return sprintf($fmt,
363                        htmlspecialchars($profile->profileurl),
364                        htmlspecialchars($profile->getBestName()),
365                        htmlspecialchars($eventUrl),
366                        htmlspecialchars($eventTitle));
367     }
368
369     static function toString($profile, $event, $response)
370     {
371         $fmt = null;
372
373         switch ($response) {
374         case 'Y':
375             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
376             // TRANS: %1$s is a profile name, %2$s is an event title.
377             $fmt = _m('%1$s is attending %2$s.');
378             break;
379         case 'N':
380             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
381             // TRANS: %1$s is a profile name, %2$s is an event title.
382             $fmt = _m('%1$s is not attending %2$s.');
383             break;
384         case '?':
385             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
386             // TRANS: %1$s is a profile name, %2$s is an event title.
387             $fmt = _m('%1$s might attend %2$s.');
388             break;
389         default:
390             // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
391             // TRANS: %s is the non-existing response code.
392             throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
393             break;
394         }
395
396         if (empty($event)) {
397             // TRANS: Used as event title when not event title is available.
398             // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
399             $eventTitle = _m('an unknown event');
400         } else {
401             $notice = $event->getNotice();
402             $eventTitle = $event->title;
403         }
404
405         return sprintf($fmt,
406                        $profile->getBestName(),
407                        $eventTitle);
408     }
409
410     function delete($useWhere=false)
411     {
412         self::blow('rsvp:for-event:%s', $this->id);
413         return parent::delete($useWhere);
414     }
415 }