Merge remote-tracking branch 'upstream/master' into social-master
[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                 continue;
118             }
119             $orig = clone($rsvp);
120             $rsvp->event_uri = $event->uri;
121             $rsvp->updateWithKeys($orig);
122         }
123         print "DONE.\n";
124         print "Resuming core schema upgrade...";
125     }
126
127     function saveNew(Profile $profile, $event, $verb, array $options = array())
128     {
129         if (array_key_exists('uri', $options)) {
130             $other = RSVP::getKV('uri', $options['uri']);
131             if (!empty($other)) {
132                 // TRANS: Client exception thrown when trying to save an already existing RSVP ("please respond").
133                 throw new ClientException(_m('RSVP already exists.'));
134             }
135         }
136
137         try {
138             $other = RSVP::getByKeys( [ 'profile_id' => $profile->getID(),
139                                         'event_uri' => $event->getUri(),
140                                       ] );
141             // TRANS: Client exception thrown when trying to save an already existing RSVP ("please respond").
142             throw new AlreadyFulfilledException(_m('RSVP already exists.'));
143         } catch (NoResultException $e) {
144             // No previous RSVP, so go ahead and add.
145         }
146
147         $rsvp = new RSVP();
148
149         $rsvp->id          = UUID::gen();
150         $rsvp->profile_id  = $profile->getID();
151         $rsvp->event_uri    = $event->getUri();
152         $rsvp->response      = self::codeFor($verb);
153
154         if (array_key_exists('created', $options)) {
155             $rsvp->created = $options['created'];
156         } else {
157             $rsvp->created = common_sql_now();
158         }
159
160         if (array_key_exists('uri', $options)) {
161             $rsvp->uri = $options['uri'];
162         } else {
163             $rsvp->uri = common_local_url('showrsvp',
164                                         array('id' => $rsvp->id));
165         }
166
167         $rsvp->insert();
168
169         self::blow('rsvp:for-event:%s', $event->getUri());
170
171         // XXX: come up with something sexier
172
173         $content = $rsvp->asString();
174
175         $rendered = $rsvp->asHTML();
176
177         $options = array_merge(array('object_type' => $verb),
178                                $options);
179
180         if (!array_key_exists('uri', $options)) {
181             $options['uri'] = $rsvp->uri;
182         }
183
184         $eventNotice = $event->getNotice();
185
186         if (!empty($eventNotice)) {
187             $options['reply_to'] = $eventNotice->getID();
188         }
189
190         $saved = Notice::saveNew($profile->getID(),
191                                  $content,
192                                  array_key_exists('source', $options) ?
193                                  $options['source'] : 'web',
194                                  $options);
195
196         return $saved;
197     }
198
199     function codeFor($verb)
200     {
201         switch ($verb) {
202         case RSVP::POSITIVE:
203             return 'Y';
204             break;
205         case RSVP::NEGATIVE:
206             return 'N';
207             break;
208         case RSVP::POSSIBLE:
209             return '?';
210             break;
211         default:
212             // TRANS: Exception thrown when requesting an undefined verb for RSVP.
213             throw new Exception(sprintf(_m('Unknown verb "%s".'),$verb));
214         }
215     }
216
217     static function verbFor($code)
218     {
219         switch ($code) {
220         case 'Y':
221             return RSVP::POSITIVE;
222             break;
223         case 'N':
224             return RSVP::NEGATIVE;
225             break;
226         case '?':
227             return RSVP::POSSIBLE;
228             break;
229         default:
230             // TRANS: Exception thrown when requesting an undefined code for RSVP.
231             throw new Exception(sprintf(_m('Unknown code "%s".'),$code));
232         }
233     }
234
235     function getNotice()
236     {
237         $notice = Notice::getKV('uri', $this->uri);
238         if (empty($notice)) {
239             // TRANS: Server exception thrown when requesting a non-exsting notice for an RSVP ("please respond").
240             // TRANS: %s is the RSVP with the missing notice.
241             throw new ServerException(sprintf(_m('RSVP %s does not correspond to a notice in the database.'),$this->id));
242         }
243         return $notice;
244     }
245
246     static function fromNotice(Notice $notice)
247     {
248         $rsvp = new RSVP();
249         $rsvp->uri = $notice->uri;
250         if (!$rsvp->find(true)) {
251             throw new NoResultException($rsvp);
252         }
253         return $rsvp;
254     }
255
256     static function forEvent(Happening $event)
257     {
258         $keypart = sprintf('rsvp:for-event:%s', $event->getUri());
259
260         $idstr = self::cacheGet($keypart);
261
262         if ($idstr !== false) {
263             $ids = explode(',', $idstr);
264         } else {
265             $ids = array();
266
267             $rsvp = new RSVP();
268
269             $rsvp->selectAdd();
270             $rsvp->selectAdd('id');
271
272             $rsvp->event_uri = $event->getUri();
273
274             if ($rsvp->find()) {
275                 while ($rsvp->fetch()) {
276                     $ids[] = $rsvp->id;
277                 }
278             }
279             self::cacheSet($keypart, implode(',', $ids));
280         }
281
282         $rsvps = array(RSVP::POSITIVE => array(),
283                        RSVP::NEGATIVE => array(),
284                        RSVP::POSSIBLE => array());
285
286         foreach ($ids as $id) {
287             $rsvp = RSVP::getKV('id', $id);
288             if (!empty($rsvp)) {
289                 $verb = self::verbFor($rsvp->response);
290                 $rsvps[$verb][] = $rsvp;
291             }
292         }
293
294         return $rsvps;
295     }
296
297     function getProfile()
298     {
299         $profile = Profile::getKV('id', $this->profile_id);
300         if (empty($profile)) {
301             // TRANS: Exception thrown when requesting a non-existing profile.
302             // TRANS: %s is the ID of the non-existing profile.
303             throw new Exception(sprintf(_m('No profile with ID %s.'),$this->profile_id));
304         }
305         return $profile;
306     }
307
308     function getEvent()
309     {
310         $event = Happening::getKV('uri', $this->event_uri);
311         if (empty($event)) {
312             // TRANS: Exception thrown when requesting a non-existing event.
313             // TRANS: %s is the ID of the non-existing event.
314             throw new Exception(sprintf(_m('No event with URI %s.'),$this->event_uri));
315         }
316         return $event;
317     }
318
319     function asHTML()
320     {
321         return self::toHTML($this->getProfile(),
322                             $this->getEvent(),
323                             $this->response);
324     }
325
326     function asString()
327     {
328         return self::toString($this->getProfile(),
329                               $this->getEvent(),
330                               $this->response);
331     }
332
333     static function toHTML(Profile $profile, Event $event, $response)
334     {
335         $fmt = null;
336
337         switch ($response) {
338         case 'Y':
339             // TRANS: HTML version of an RSVP ("please respond") status for a user.
340             // TRANS: %1$s is a profile URL, %2$s a profile name,
341             // TRANS: %3$s is an event URL, %4$s an event title.
342             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> is attending <a href='%3\$s'>%4\$s</a>.</span>");
343             break;
344         case 'N':
345             // TRANS: HTML version of an RSVP ("please respond") status for a user.
346             // TRANS: %1$s is a profile URL, %2$s a profile name,
347             // TRANS: %3$s is an event URL, %4$s an event title.
348             $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>");
349             break;
350         case '?':
351             // TRANS: HTML version of an RSVP ("please respond") status for a user.
352             // TRANS: %1$s is a profile URL, %2$s a profile name,
353             // TRANS: %3$s is an event URL, %4$s an event title.
354             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> might attend <a href='%3\$s'>%4\$s</a>.</span>");
355             break;
356         default:
357             // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
358             // TRANS: %s is the non-existing response code.
359             throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
360         }
361
362         if (empty($event)) {
363             $eventUrl = '#';
364             // TRANS: Used as event title when not event title is available.
365             // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
366             $eventTitle = _m('an unknown event');
367         } else {
368             $notice = $event->getNotice();
369             $eventUrl = $notice->getUrl();
370             $eventTitle = $event->title;
371         }
372
373         return sprintf($fmt,
374                        htmlspecialchars($profile->profileurl),
375                        htmlspecialchars($profile->getBestName()),
376                        htmlspecialchars($eventUrl),
377                        htmlspecialchars($eventTitle));
378     }
379
380     static function toString($profile, $event, $response)
381     {
382         $fmt = null;
383
384         switch ($response) {
385         case 'Y':
386             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
387             // TRANS: %1$s is a profile name, %2$s is an event title.
388             $fmt = _m('%1$s is attending %2$s.');
389             break;
390         case 'N':
391             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
392             // TRANS: %1$s is a profile name, %2$s is an event title.
393             $fmt = _m('%1$s is not attending %2$s.');
394             break;
395         case '?':
396             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
397             // TRANS: %1$s is a profile name, %2$s is an event title.
398             $fmt = _m('%1$s might attend %2$s.');
399             break;
400         default:
401             // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
402             // TRANS: %s is the non-existing response code.
403             throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
404             break;
405         }
406
407         if (empty($event)) {
408             // TRANS: Used as event title when not event title is available.
409             // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
410             $eventTitle = _m('an unknown event');
411         } else {
412             $notice = $event->getNotice();
413             $eventTitle = $event->title;
414         }
415
416         return sprintf($fmt,
417                        $profile->getBestName(),
418                        $eventTitle);
419     }
420
421     function delete($useWhere=false)
422     {
423         self::blow('rsvp:for-event:%s', $this->id);
424         return parent::delete($useWhere);
425     }
426 }