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