]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Event/classes/RSVP.php
f2ab8f0aa3e81845aef66bd885daeb8a74739f4b
[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         $schemadef['fields']['uri']['length'] = 191;    // we likely don't have to discover too long keys here
111         $schema->ensureTable($table, $schemadef);
112
113         $rsvp = new RSVP();
114         $rsvp->find();
115         while ($rsvp->fetch()) {
116             $event = Happening::getKV('id', $rsvp->event_id);
117             if (!$event instanceof Happening) {
118                 $rsvp->delete();
119                 continue;
120             }
121             $orig = clone($rsvp);
122             $rsvp->event_uri = $event->uri;
123             $rsvp->updateWithKeys($orig);
124         }
125         print "DONE.\n";
126         print "Resuming core schema upgrade...";
127     }
128
129     static function saveActivityObject(Activity $act, Notice $stored)
130     {
131         $target = Notice::getByKeys(array('uri'=>$act->target->id));
132         if (!ActivityUtils::compareTypes($target->getObjectType(), [ Happening::OBJECT_TYPE ])) {
133             throw new ClientException('RSVP not aimed at a Happening');
134         }
135
136         // FIXME: Maybe we need some permission handling here, though I think it's taken care of in saveActivity?
137
138         try {
139             $other = RSVP::getByKeys( [ 'profile_id' => $stored->getProfile()->getID(),
140                                         'event_uri' => $target->getUri(),
141                                       ] );
142             // TRANS: Client exception thrown when trying to save an already existing RSVP ("please respond").
143             throw new AlreadyFulfilledException(_m('RSVP already exists.'));
144         } catch (NoResultException $e) {
145             // No previous RSVP, so go ahead and add.
146         }
147
148         $rsvp = new RSVP();
149         $rsvp->id          = UUID::gen();   // remove this
150         $rsvp->uri         = $stored->getUri();
151         $rsvp->profile_id  = $stored->getProfile()->getID();
152         $rsvp->event_uri   = $target->getUri();
153         $rsvp->response    = self::codeFor($stored->getVerb());
154         $rsvp->created     = $stored->getCreated();
155
156         $rsvp->insert();
157
158         self::blow('rsvp:for-event:%s', $target->getUri());
159
160         return $rsvp;
161     }
162
163     static public function getObjectType()
164     {
165         return ActivityObject::ACTIVITY;
166     }
167
168     public function asActivityObject()
169     {
170         $happening = $this->getEvent();
171
172         $actobj = new ActivityObject();
173         $actobj->id = $this->getUri();
174         $actobj->type = self::getObjectType();
175         $actobj->title = $this->asString();
176         $actobj->content = $this->asString();
177         $actobj->target = array($happening->asActivityObject());
178
179         return $actobj;
180     }
181
182     static function codeFor($verb)
183     {
184         switch (true) {
185         case ActivityUtils::compareVerbs($verb, [RSVP::POSITIVE]):
186             return 'Y';
187             break;
188         case ActivityUtils::compareVerbs($verb, [RSVP::NEGATIVE]):
189             return 'N';
190             break;
191         case ActivityUtils::compareVerbs($verb, [RSVP::POSSIBLE]):
192             return '?';
193             break;
194         default:
195             // TRANS: Exception thrown when requesting an undefined verb for RSVP.
196             throw new Exception(sprintf(_m('Unknown verb "%s".'),$verb));
197         }
198     }
199
200     static function verbFor($code)
201     {
202         switch ($code) {
203         case 'Y':
204         case 'yes':
205             return RSVP::POSITIVE;
206             break;
207         case 'N':
208         case 'no':
209             return RSVP::NEGATIVE;
210             break;
211         case '?':
212         case 'maybe':
213             return RSVP::POSSIBLE;
214             break;
215         default:
216             // TRANS: Exception thrown when requesting an undefined code for RSVP.
217             throw new ClientException(sprintf(_m('Unknown code "%s".'), $code));
218         }
219     }
220
221     public function getUri()
222     {
223         return $this->uri;
224     }
225
226     public function getEventUri()
227     {
228         return $this->event_uri;
229     }
230
231     public function getStored()
232     {
233         return Notice::getByKeys(['uri' => $this->getUri()]);
234     }
235
236     static function fromStored(Notice $stored)
237     {
238         return self::getByKeys(['uri' => $stored->getUri()]);
239     }
240
241     static function byEventAndActor(Happening $event, Profile $actor)
242     {
243         return self::getByKeys(['event_uri' => $event->getUri(),
244                                 'profile_id' => $actor->getID()]);
245     }
246
247     static function forEvent(Happening $event)
248     {
249         $keypart = sprintf('rsvp:for-event:%s', $event->getUri());
250
251         $idstr = self::cacheGet($keypart);
252
253         if ($idstr !== false) {
254             $ids = explode(',', $idstr);
255         } else {
256             $ids = array();
257
258             $rsvp = new RSVP();
259
260             $rsvp->selectAdd();
261             $rsvp->selectAdd('id');
262
263             $rsvp->event_uri = $event->getUri();
264
265             if ($rsvp->find()) {
266                 while ($rsvp->fetch()) {
267                     $ids[] = $rsvp->id;
268                 }
269             }
270             self::cacheSet($keypart, implode(',', $ids));
271         }
272
273         $rsvps = array(RSVP::POSITIVE => array(),
274                        RSVP::NEGATIVE => array(),
275                        RSVP::POSSIBLE => array());
276
277         foreach ($ids as $id) {
278             $rsvp = RSVP::getKV('id', $id);
279             if (!empty($rsvp)) {
280                 $verb = self::verbFor($rsvp->response);
281                 $rsvps[$verb][] = $rsvp;
282             }
283         }
284
285         return $rsvps;
286     }
287
288     function getProfile()
289     {
290         return Profile::getByID($this->profile_id);
291     }
292
293     function getEvent()
294     {
295         return Happening::getByKeys(['uri' => $this->getEventUri()]);
296     }
297
298     function asHTML()
299     {
300         return self::toHTML($this->getProfile(),
301                             $this->getEvent(),
302                             $this->response);
303     }
304
305     function asString()
306     {
307         return self::toString($this->getProfile(),
308                               $this->getEvent(),
309                               $this->response);
310     }
311
312     static function toHTML(Profile $profile, Happening $event, $response)
313     {
314         $fmt = null;
315
316         switch ($response) {
317         case 'Y':
318             // TRANS: HTML version of an RSVP ("please respond") status for a user.
319             // TRANS: %1$s is a profile URL, %2$s a profile name,
320             // TRANS: %3$s is an event URL, %4$s an event title.
321             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> is attending <a href='%3\$s'>%4\$s</a>.</span>");
322             break;
323         case 'N':
324             // TRANS: HTML version of an RSVP ("please respond") status for a user.
325             // TRANS: %1$s is a profile URL, %2$s a profile name,
326             // TRANS: %3$s is an event URL, %4$s an event title.
327             $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>");
328             break;
329         case '?':
330             // TRANS: HTML version of an RSVP ("please respond") status for a user.
331             // TRANS: %1$s is a profile URL, %2$s a profile name,
332             // TRANS: %3$s is an event URL, %4$s an event title.
333             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> might attend <a href='%3\$s'>%4\$s</a>.</span>");
334             break;
335         default:
336             // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
337             // TRANS: %s is the non-existing response code.
338             throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
339         }
340
341         if (empty($event)) {
342             $eventUrl = '#';
343             // TRANS: Used as event title when not event title is available.
344             // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
345             $eventTitle = _m('an unknown event');
346         } else {
347             $eventUrl = $event->getStored()->getUrl();
348             $eventTitle = $event->title;
349         }
350
351         return sprintf($fmt,
352                        htmlspecialchars($profile->getUrl()),
353                        htmlspecialchars($profile->getBestName()),
354                        htmlspecialchars($eventUrl),
355                        htmlspecialchars($eventTitle));
356     }
357
358     static function toString($profile, $event, $response)
359     {
360         $fmt = null;
361
362         switch ($response) {
363         case 'Y':
364             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
365             // TRANS: %1$s is a profile name, %2$s is an event title.
366             $fmt = _m('%1$s is attending %2$s.');
367             break;
368         case 'N':
369             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
370             // TRANS: %1$s is a profile name, %2$s is an event title.
371             $fmt = _m('%1$s is not attending %2$s.');
372             break;
373         case '?':
374             // TRANS: Plain text version of an RSVP ("please respond") status for a user.
375             // TRANS: %1$s is a profile name, %2$s is an event title.
376             $fmt = _m('%1$s might attend %2$s.');
377             break;
378         default:
379             // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
380             // TRANS: %s is the non-existing response code.
381             throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
382             break;
383         }
384
385         if (empty($event)) {
386             // TRANS: Used as event title when not event title is available.
387             // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
388             $eventTitle = _m('an unknown event');
389         } else {
390             $eventTitle = $event->title;
391         }
392
393         return sprintf($fmt,
394                        $profile->getBestName(),
395                        $eventTitle);
396     }
397
398     public function delete($useWhere=false)
399     {
400         self::blow('rsvp:for-event:%s', $this->id);
401         return parent::delete($useWhere);
402     }
403
404     public function insert()
405     {
406         $result = parent::insert();
407         if ($result === false) {
408             common_log_db_error($this, 'INSERT', __FILE__);
409             throw new ServerException(_('Failed to insert '._ve(get_called_class()).' into database'));
410         }
411         return $result;
412     }
413 }