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