]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Event/RSVP.php
Cache RSVP counts for Event plugin
[quix0rs-gnu-social.git] / plugins / Event / 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('STATUSNET')) {
31     exit(1);
32 }
33
34 /**
35  * Data class for event RSVPs
36  *
37  * @category Event
38  * @package  StatusNet
39  * @author   Evan Prodromou <evan@status.net>
40  * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
41  * @link     http://status.net/
42  *
43  * @see      Managed_DataObject
44  */
45
46 class RSVP extends Managed_DataObject
47 {
48     const POSITIVE = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
49     const POSSIBLE = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
50     const NEGATIVE = 'http://activitystrea.ms/schema/1.0/rsvp-no';
51
52     public $__table = 'rsvp'; // table name
53     public $id;                // varchar(36) UUID
54     public $uri;               // varchar(255)
55     public $profile_id;        // int
56     public $event_id;          // varchar(36) UUID
57     public $response;            // tinyint
58     public $created;           // datetime
59
60     /**
61      * Get an instance by key
62      *
63      * @param string $k Key to use to lookup (usually 'id' for this class)
64      * @param mixed  $v Value to lookup
65      *
66      * @return RSVP object found, or null for no hits
67      *
68      */
69     function staticGet($k, $v=null)
70     {
71         return Memcached_DataObject::staticGet('RSVP', $k, $v);
72     }
73
74     /**
75      * Get an instance by compound key
76      *
77      * @param array $kv array of key-value mappings
78      *
79      * @return Bookmark object found, or null for no hits
80      *
81      */
82
83     function pkeyGet($kv)
84     {
85         return Memcached_DataObject::pkeyGet('RSVP', $kv);
86     }
87
88     /**
89      * Add the compound profile_id/event_id index to our cache keys
90      * since the DB_DataObject stuff doesn't understand compound keys
91      * except for the primary.
92      *
93      * @return array
94      */
95     function _allCacheKeys() {
96         $keys = parent::_allCacheKeys();
97         $keys[] = self::multicacheKey('RSVP', array('profile_id' => $this->profile_id,
98                                                     'event_id' => $this->event_id));
99         return $keys;
100     }
101
102     /**
103      * The One True Thingy that must be defined and declared.
104      */
105     public static function schemaDef()
106     {
107         return array(
108             'description' => 'Plan to attend event',
109             'fields' => array(
110                 'id' => array('type' => 'char',
111                               'length' => 36,
112                               'not null' => true,
113                               'description' => 'UUID'),
114                 'uri' => array('type' => 'varchar',
115                                'length' => 255,
116                                'not null' => true),
117                 'profile_id' => array('type' => 'int'),
118                 'event_id' => array('type' => 'char',
119                               'length' => 36,
120                               'not null' => true,
121                               'description' => 'UUID'),
122                 'response' => array('type' => 'char',
123                                   'length' => '1',
124                                   'description' => 'Y, N, or ? for three-state yes, no, maybe'),
125                 'created' => array('type' => 'datetime',
126                                    'not null' => true),
127             ),
128             'primary key' => array('id'),
129             'unique keys' => array(
130                 'rsvp_uri_key' => array('uri'),
131                 'rsvp_profile_event_key' => array('profile_id', 'event_id'),
132             ),
133             'foreign keys' => array('rsvp_event_id_key' => array('event', array('event_id' => 'id')),
134                                     'rsvp_profile_id__key' => array('profile', array('profile_id' => 'id'))),
135             'indexes' => array('rsvp_created_idx' => array('created')),
136         );
137     }
138
139     function saveNew($profile, $event, $verb, $options=array())
140     {
141         if (array_key_exists('uri', $options)) {
142             $other = RSVP::staticGet('uri', $options['uri']);
143             if (!empty($other)) {
144                 throw new ClientException(_m('RSVP already exists.'));
145             }
146         }
147
148         $other = RSVP::pkeyGet(array('profile_id' => $profile->id,
149                                      'event_id' => $event->id));
150
151         if (!empty($other)) {
152             throw new ClientException(_m('RSVP already exists.'));
153         }
154
155         $rsvp = new RSVP();
156
157         $rsvp->id          = UUID::gen();
158         $rsvp->profile_id  = $profile->id;
159         $rsvp->event_id    = $event->id;
160         $rsvp->response      = self::codeFor($verb);
161
162         if (array_key_exists('created', $options)) {
163             $rsvp->created = $options['created'];
164         } else {
165             $rsvp->created = common_sql_now();
166         }
167
168         if (array_key_exists('uri', $options)) {
169             $rsvp->uri = $options['uri'];
170         } else {
171             $rsvp->uri = common_local_url('showrsvp',
172                                         array('id' => $rsvp->id));
173         }
174
175         $rsvp->insert();
176
177         self::blow('rsvp:for-event:%s', $event->id);
178
179         // XXX: come up with something sexier
180
181         $content = $rsvp->asString();
182         
183         $rendered = $rsvp->asHTML();
184
185         $options = array_merge(array('object_type' => $verb),
186                                $options);
187
188         if (!array_key_exists('uri', $options)) {
189             $options['uri'] = $rsvp->uri;
190         }
191
192         $eventNotice = $event->getNotice();
193
194         if (!empty($eventNotice)) {
195             $options['reply_to'] = $eventNotice->id;
196         }
197
198         $saved = Notice::saveNew($profile->id,
199                                  $content,
200                                  array_key_exists('source', $options) ?
201                                  $options['source'] : 'web',
202                                  $options);
203
204         return $saved;
205     }
206
207     function codeFor($verb)
208     {
209         switch ($verb) {
210         case RSVP::POSITIVE:
211             return 'Y';
212             break;
213         case RSVP::NEGATIVE:
214             return 'N';
215             break;
216         case RSVP::POSSIBLE:
217             return '?';
218             break;
219         default:
220             throw new Exception(sprintf(_m('Unknown verb "%s"'),$verb));
221         }
222     }
223
224     static function verbFor($code)
225     {
226         switch ($code) {
227         case 'Y':
228             return RSVP::POSITIVE;
229             break;
230         case 'N':
231             return RSVP::NEGATIVE;
232             break;
233         case '?':
234             return RSVP::POSSIBLE;
235             break;
236         default:
237             throw new Exception(sprintf(_m('Unknown code "%s".'),$code));
238         }
239     }
240
241     function getNotice()
242     {
243         $notice = Notice::staticGet('uri', $this->uri);
244         if (empty($notice)) {
245             throw new ServerException(sprintf(_m('RSVP %s does not correspond to a notice in the database.'),$this->id));
246         }
247         return $notice;
248     }
249
250     static function fromNotice($notice)
251     {
252         return RSVP::staticGet('uri', $notice->uri);
253     }
254
255     static function forEvent($event)
256     {
257         $keypart = sprintf('rsvp:for-event:%s', $event->id);
258
259         $idstr = self::cacheGet($keypart);
260
261         if ($idstr !== false) {
262             $ids = explode(',', $idstr);
263         } else {
264             $ids = array();
265
266             $rsvp = new RSVP();
267
268             $rsvp->selectAdd();
269             $rsvp->selectAdd('id');
270
271             $rsvp->event_id = $event->id;
272
273             if ($rsvp->find()) {
274                 while ($rsvp->fetch()) {
275                     $ids[] = $rsvp->id;
276                 }
277             }
278             self::cacheSet($keypart, implode(',', $ids));
279         }
280
281         $rsvps = array(RSVP::POSITIVE => array(),
282                        RSVP::NEGATIVE => array(),
283                        RSVP::POSSIBLE => array());
284
285         foreach ($ids as $id) {
286             $rsvp = RSVP::staticGet('id', $id);
287             if (!empty($rsvp)) {
288                 $verb = self::verbFor($rsvp->response);
289                 $rsvps[$verb][] = $rsvp;
290             }
291         }
292
293         return $rsvps;
294     }
295
296     function getProfile()
297     {
298         $profile = Profile::staticGet('id', $this->profile_id);
299         if (empty($profile)) {
300             throw new Exception(sprintf(_m('No profile with ID %s.'),$this->profile_id));
301         }
302         return $profile;
303     }
304
305     function getEvent()
306     {
307         $event = Happening::staticGet('id', $this->event_id);
308         if (empty($event)) {
309             throw new Exception(sprintf(_m('No event with ID %s.'),$this->event_id));
310         }
311         return $event;
312     }
313
314     function asHTML()
315     {
316         $event = Happening::staticGet('id', $this->event_id);
317
318         return self::toHTML($this->getProfile(),
319                             $event,
320                             $this->response);
321     }
322
323     function asString()
324     {
325         $event = Happening::staticGet('id', $this->event_id);
326
327         return self::toString($this->getProfile(),
328                               $event,
329                               $this->response);
330     }
331
332     static function toHTML($profile, $event, $response)
333     {
334         $fmt = null;
335
336         switch ($response) {
337         case 'Y':
338             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> is attending <a href='%3\$s'>%4\$s</a>.</span>");
339             break;
340         case 'N':
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             $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> might attend <a href='%3\$s'>%4\$s</a>.</span>");
345             break;
346         default:
347             throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
348             break;
349         }
350
351         if (empty($event)) {
352             $eventUrl = '#';
353             $eventTitle = _m('an unknown event');
354         } else {
355             $notice = $event->getNotice();
356             $eventUrl = $notice->bestUrl();
357             $eventTitle = $event->title;
358         }
359
360         return sprintf($fmt,
361                        htmlspecialchars($profile->profileurl),
362                        htmlspecialchars($profile->getBestName()),
363                        htmlspecialchars($eventUrl),
364                        htmlspecialchars($eventTitle));
365     }
366
367     static function toString($profile, $event, $response)
368     {
369         $fmt = null;
370
371         switch ($response) {
372         case 'Y':
373             $fmt = _m('%1$s is attending %2$s.');
374             break;
375         case 'N':
376             $fmt = _m('%1$s is not attending %2$s.');
377             break;
378         case '?':
379             $fmt = _m('%1$s might attend %2$s.');
380             break;
381         default:
382             throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
383             break;
384         }
385
386         if (empty($event)) {
387             $eventTitle = _m('an unknown event');
388         } else {
389             $notice = $event->getNotice();
390             $eventTitle = $event->title;
391         }
392
393         return sprintf($fmt,
394                        $profile->getBestName(),
395                        $eventTitle);
396     }
397
398     function delete()
399     {
400         self::blow('rsvp:for-event:%s', $event->id);
401         parent::delete();
402     }
403 }