RSVP.php 14.5 KB
Newer Older
Evan Prodromou's avatar
Evan Prodromou committed
1 2
<?php
/**
3
 * Data class for event RSVPs
Evan Prodromou's avatar
Evan Prodromou committed
4 5 6 7 8 9 10 11 12 13
 *
 * PHP version 5
 *
 * @category Data
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 *
 * StatusNet - the distributed open-source microblogging tool
14
 * Copyright (C) 2011, StatusNet, Inc.
Evan Prodromou's avatar
Evan Prodromou committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('STATUSNET')) {
    exit(1);
}

/**
35
 * Data class for event RSVPs
Evan Prodromou's avatar
Evan Prodromou committed
36
 *
37
 * @category Event
Evan Prodromou's avatar
Evan Prodromou committed
38 39 40 41 42
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 *
43
 * @see      Managed_DataObject
Evan Prodromou's avatar
Evan Prodromou committed
44
 */
45
class RSVP extends Managed_DataObject
Evan Prodromou's avatar
Evan Prodromou committed
46
{
47 48 49 50 51 52 53 54 55
    const POSITIVE = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
    const POSSIBLE = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
    const NEGATIVE = 'http://activitystrea.ms/schema/1.0/rsvp-no';

    public $__table = 'rsvp'; // table name
    public $id;                // varchar(36) UUID
    public $uri;               // varchar(255)
    public $profile_id;        // int
    public $event_id;          // varchar(36) UUID
56
    public $response;            // tinyint
57
    public $created;           // datetime
Evan Prodromou's avatar
Evan Prodromou committed
58 59 60 61

    /**
     * Get an instance by key
     *
62
     * @param string $k Key to use to lookup (usually 'id' for this class)
Evan Prodromou's avatar
Evan Prodromou committed
63 64
     * @param mixed  $v Value to lookup
     *
65
     * @return RSVP object found, or null for no hits
Evan Prodromou's avatar
Evan Prodromou committed
66 67 68
     */
    function staticGet($k, $v=null)
    {
69
        return Memcached_DataObject::staticGet('RSVP', $k, $v);
Evan Prodromou's avatar
Evan Prodromou committed
70 71
    }

72 73 74 75 76 77 78 79 80 81 82 83 84
    /**
     * Get an instance by compound key
     *
     * @param array $kv array of key-value mappings
     *
     * @return Bookmark object found, or null for no hits
     */

    function pkeyGet($kv)
    {
        return Memcached_DataObject::pkeyGet('RSVP', $kv);
    }

Brion Vibber's avatar
Brion Vibber committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98
    /**
     * Add the compound profile_id/event_id index to our cache keys
     * since the DB_DataObject stuff doesn't understand compound keys
     * except for the primary.
     *
     * @return array
     */
    function _allCacheKeys() {
        $keys = parent::_allCacheKeys();
        $keys[] = self::multicacheKey('RSVP', array('profile_id' => $this->profile_id,
                                                    'event_id' => $this->event_id));
        return $keys;
    }

Evan Prodromou's avatar
Evan Prodromou committed
99
    /**
100
     * The One True Thingy that must be defined and declared.
Evan Prodromou's avatar
Evan Prodromou committed
101
     */
102
    public static function schemaDef()
Evan Prodromou's avatar
Evan Prodromou committed
103
    {
104
        return array(
105
            'description' => 'Plan to attend event',
106 107 108 109 110 111 112 113 114 115 116 117 118
            'fields' => array(
                'id' => array('type' => 'char',
                              'length' => 36,
                              'not null' => true,
                              'description' => 'UUID'),
                'uri' => array('type' => 'varchar',
                               'length' => 255,
                               'not null' => true),
                'profile_id' => array('type' => 'int'),
                'event_id' => array('type' => 'char',
                              'length' => 36,
                              'not null' => true,
                              'description' => 'UUID'),
119 120 121
                'response' => array('type' => 'char',
                                  'length' => '1',
                                  'description' => 'Y, N, or ? for three-state yes, no, maybe'),
122 123 124 125 126 127 128 129 130 131 132 133
                'created' => array('type' => 'datetime',
                                   'not null' => true),
            ),
            'primary key' => array('id'),
            'unique keys' => array(
                'rsvp_uri_key' => array('uri'),
                'rsvp_profile_event_key' => array('profile_id', 'event_id'),
            ),
            'foreign keys' => array('rsvp_event_id_key' => array('event', array('event_id' => 'id')),
                                    'rsvp_profile_id__key' => array('profile', array('profile_id' => 'id'))),
            'indexes' => array('rsvp_created_idx' => array('created')),
        );
Evan Prodromou's avatar
Evan Prodromou committed
134 135
    }

136
    function saveNew($profile, $event, $verb, $options=array())
Evan Prodromou's avatar
Evan Prodromou committed
137
    {
138 139 140
        if (array_key_exists('uri', $options)) {
            $other = RSVP::staticGet('uri', $options['uri']);
            if (!empty($other)) {
141
                // TRANS: Client exception thrown when trying to save an already existing RSVP ("please respond").
142
                throw new ClientException(_m('RSVP already exists.'));
143 144
            }
        }
Evan Prodromou's avatar
Evan Prodromou committed
145

146 147
        $other = RSVP::pkeyGet(array('profile_id' => $profile->id,
                                     'event_id' => $event->id));
Evan Prodromou's avatar
Evan Prodromou committed
148

149
        if (!empty($other)) {
150
            // TRANS: Client exception thrown when trying to save an already existing RSVP ("please respond").
151
            throw new ClientException(_m('RSVP already exists.'));
152
        }
Evan Prodromou's avatar
Evan Prodromou committed
153

154 155 156 157 158
        $rsvp = new RSVP();

        $rsvp->id          = UUID::gen();
        $rsvp->profile_id  = $profile->id;
        $rsvp->event_id    = $event->id;
159
        $rsvp->response      = self::codeFor($verb);
160 161 162 163 164 165

        if (array_key_exists('created', $options)) {
            $rsvp->created = $options['created'];
        } else {
            $rsvp->created = common_sql_now();
        }
Evan Prodromou's avatar
Evan Prodromou committed
166

167 168 169 170 171 172
        if (array_key_exists('uri', $options)) {
            $rsvp->uri = $options['uri'];
        } else {
            $rsvp->uri = common_local_url('showrsvp',
                                        array('id' => $rsvp->id));
        }
Evan Prodromou's avatar
Evan Prodromou committed
173

174
        $rsvp->insert();
Evan Prodromou's avatar
Evan Prodromou committed
175

176 177
        self::blow('rsvp:for-event:%s', $event->id);

178
        // XXX: come up with something sexier
Evan Prodromou's avatar
Evan Prodromou committed
179

180
        $content = $rsvp->asString();
181

182
        $rendered = $rsvp->asHTML();
Evan Prodromou's avatar
Evan Prodromou committed
183

184
        $options = array_merge(array('object_type' => $verb),
185
                               $options);
Evan Prodromou's avatar
Evan Prodromou committed
186

187 188 189
        if (!array_key_exists('uri', $options)) {
            $options['uri'] = $rsvp->uri;
        }
Evan Prodromou's avatar
Evan Prodromou committed
190

191
        $eventNotice = $event->getNotice();
Evan Prodromou's avatar
Evan Prodromou committed
192

193 194
        if (!empty($eventNotice)) {
            $options['reply_to'] = $eventNotice->id;
Evan Prodromou's avatar
Evan Prodromou committed
195 196
        }

197 198 199 200 201 202 203 204 205 206 207
        $saved = Notice::saveNew($profile->id,
                                 $content,
                                 array_key_exists('source', $options) ?
                                 $options['source'] : 'web',
                                 $options);

        return $saved;
    }

    function codeFor($verb)
    {
208 209 210 211 212 213 214 215 216 217 218
        switch ($verb) {
        case RSVP::POSITIVE:
            return 'Y';
            break;
        case RSVP::NEGATIVE:
            return 'N';
            break;
        case RSVP::POSSIBLE:
            return '?';
            break;
        default:
219 220
            // TRANS: Exception thrown when requesting an undefined verb for RSVP.
            throw new Exception(sprintf(_m('Unknown verb "%s".'),$verb));
221
        }
222 223
    }

224
    static function verbFor($code)
225
    {
226 227 228 229 230 231 232 233 234 235 236
        switch ($code) {
        case 'Y':
            return RSVP::POSITIVE;
            break;
        case 'N':
            return RSVP::NEGATIVE;
            break;
        case '?':
            return RSVP::POSSIBLE;
            break;
        default:
237
            // TRANS: Exception thrown when requesting an undefined code for RSVP.
238
            throw new Exception(sprintf(_m('Unknown code "%s".'),$code));
239
        }
240 241 242 243
    }

    function getNotice()
    {
244 245
        $notice = Notice::staticGet('uri', $this->uri);
        if (empty($notice)) {
246 247
            // TRANS: Server exception thrown when requesting a non-exsting notice for an RSVP ("please respond").
            // TRANS: %s is the RSVP with the missing notice.
248
            throw new ServerException(sprintf(_m('RSVP %s does not correspond to a notice in the database.'),$this->id));
249 250
        }
        return $notice;
251 252
    }

Evan Prodromou's avatar
Evan Prodromou committed
253
    static function fromNotice($notice)
254 255
    {
        return RSVP::staticGet('uri', $notice->uri);
Evan Prodromou's avatar
Evan Prodromou committed
256
    }
Evan Prodromou's avatar
Evan Prodromou committed
257 258 259

    static function forEvent($event)
    {
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        $keypart = sprintf('rsvp:for-event:%s', $event->id);

        $idstr = self::cacheGet($keypart);

        if ($idstr !== false) {
            $ids = explode(',', $idstr);
        } else {
            $ids = array();

            $rsvp = new RSVP();

            $rsvp->selectAdd();
            $rsvp->selectAdd('id');

            $rsvp->event_id = $event->id;

            if ($rsvp->find()) {
                while ($rsvp->fetch()) {
                    $ids[] = $rsvp->id;
                }
            }
            self::cacheSet($keypart, implode(',', $ids));
        }

284 285 286
        $rsvps = array(RSVP::POSITIVE => array(),
                       RSVP::NEGATIVE => array(),
                       RSVP::POSSIBLE => array());
Evan Prodromou's avatar
Evan Prodromou committed
287

288 289 290
        foreach ($ids as $id) {
            $rsvp = RSVP::staticGet('id', $id);
            if (!empty($rsvp)) {
291
                $verb = self::verbFor($rsvp->response);
292
                $rsvps[$verb][] = $rsvp;
Evan Prodromou's avatar
Evan Prodromou committed
293 294 295 296 297
            }
        }

        return $rsvps;
    }
298 299 300 301 302

    function getProfile()
    {
        $profile = Profile::staticGet('id', $this->profile_id);
        if (empty($profile)) {
303 304
            // TRANS: Exception thrown when requesting a non-existing profile.
            // TRANS: %s is the ID of the non-existing profile.
305
            throw new Exception(sprintf(_m('No profile with ID %s.'),$this->profile_id));
306 307 308 309 310 311 312 313
        }
        return $profile;
    }

    function getEvent()
    {
        $event = Happening::staticGet('id', $this->event_id);
        if (empty($event)) {
314 315
            // TRANS: Exception thrown when requesting a non-existing event.
            // TRANS: %s is the ID of the non-existing event.
316
            throw new Exception(sprintf(_m('No event with ID %s.'),$this->event_id));
317 318 319 320 321 322
        }
        return $event;
    }

    function asHTML()
    {
323 324
        $event = Happening::staticGet('id', $this->event_id);

325
        return self::toHTML($this->getProfile(),
326
                            $event,
327 328 329 330 331
                            $this->response);
    }

    function asString()
    {
332 333
        $event = Happening::staticGet('id', $this->event_id);

334
        return self::toString($this->getProfile(),
335
                              $event,
336 337 338 339 340 341 342 343 344
                              $this->response);
    }

    static function toHTML($profile, $event, $response)
    {
        $fmt = null;

        switch ($response) {
        case 'Y':
345 346 347
            // TRANS: HTML version of an RSVP ("please respond") status for a user.
            // TRANS: %1$s is a profile URL, %2$s a profile name,
            // 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 attending <a href='%3\$s'>%4\$s</a>.</span>");
349 350
            break;
        case 'N':
351 352 353
            // TRANS: HTML version of an RSVP ("please respond") status for a user.
            // TRANS: %1$s is a profile URL, %2$s a profile name,
            // 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> is not attending <a href='%3\$s'>%4\$s</a>.</span>");
355 356
            break;
        case '?':
357 358 359
            // TRANS: HTML version of an RSVP ("please respond") status for a user.
            // TRANS: %1$s is a profile URL, %2$s a profile name,
            // TRANS: %3$s is an event URL, %4$s an event title.
360
            $fmt = _m("<span class='automatic event-rsvp'><a href='%1\$s'>%2\$s</a> might attend <a href='%3\$s'>%4\$s</a>.</span>");
361 362
            break;
        default:
363 364
            // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
            // TRANS: %s is the non-existing response code.
365
            throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
366 367 368
            break;
        }

369 370
        if (empty($event)) {
            $eventUrl = '#';
371 372
            // TRANS: Used as event title when not event title is available.
            // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
373
            $eventTitle = _m('an unknown event');
374 375 376 377 378 379
        } else {
            $notice = $event->getNotice();
            $eventUrl = $notice->bestUrl();
            $eventTitle = $event->title;
        }

380 381 382
        return sprintf($fmt,
                       htmlspecialchars($profile->profileurl),
                       htmlspecialchars($profile->getBestName()),
383 384
                       htmlspecialchars($eventUrl),
                       htmlspecialchars($eventTitle));
385 386 387 388 389 390 391 392
    }

    static function toString($profile, $event, $response)
    {
        $fmt = null;

        switch ($response) {
        case 'Y':
393 394
            // TRANS: Plain text version of an RSVP ("please respond") status for a user.
            // TRANS: %1$s is a profile name, %2$s is an event title.
395
            $fmt = _m('%1$s is attending %2$s.');
396 397
            break;
        case 'N':
398 399
            // TRANS: Plain text version of an RSVP ("please respond") status for a user.
            // TRANS: %1$s is a profile name, %2$s is an event title.
400
            $fmt = _m('%1$s is not attending %2$s.');
401 402
            break;
        case '?':
403 404
            // TRANS: Plain text version of an RSVP ("please respond") status for a user.
            // TRANS: %1$s is a profile name, %2$s is an event title.
405
            $fmt = _m('%1$s might attend %2$s.');
406 407
            break;
        default:
408 409
            // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
            // TRANS: %s is the non-existing response code.
410
            throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
411 412 413
            break;
        }

414
        if (empty($event)) {
415 416
            // TRANS: Used as event title when not event title is available.
            // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
417
            $eventTitle = _m('an unknown event');
418 419 420 421 422
        } else {
            $notice = $event->getNotice();
            $eventTitle = $event->title;
        }

423 424
        return sprintf($fmt,
                       $profile->getBestName(),
425
                       $eventTitle);
426
    }
427 428 429 430 431 432

    function delete()
    {
        self::blow('rsvp:for-event:%s', $event->id);
        parent::delete();
    }
Evan Prodromou's avatar
Evan Prodromou committed
433
}