We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

RSVP.php 14.3 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
 *
 * 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/>.
 */

30
if (!defined('GNUSOCIAL')) { exit(1); }
Evan Prodromou's avatar
Evan Prodromou committed
31 32

/**
33
 * Data class for event RSVPs
Evan Prodromou's avatar
Evan Prodromou committed
34
 *
35
 * @category Event
Evan Prodromou's avatar
Evan Prodromou committed
36 37 38 39 40
 * @package  StatusNet
 * @author   Evan Prodromou <evan@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 *
41
 * @see      Managed_DataObject
Evan Prodromou's avatar
Evan Prodromou committed
42
 */
43
class RSVP extends Managed_DataObject
Evan Prodromou's avatar
Evan Prodromou committed
44
{
45 46 47 48 49 50
    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
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
Evan Prodromou's avatar
Evan Prodromou committed
56 57

    /**
58
     * The One True Thingy that must be defined and declared.
Evan Prodromou's avatar
Evan Prodromou committed
59
     */
60
    public static function schemaDef()
Evan Prodromou's avatar
Evan Prodromou committed
61
    {
62
        return array(
Evan Prodromou's avatar
Evan Prodromou committed
63
            'description' => 'Plan to attend event',
64 65 66 67 68 69
            'fields' => array(
                'id' => array('type' => 'char',
                              'length' => 36,
                              'not null' => true,
                              'description' => 'UUID'),
                'uri' => array('type' => 'varchar',
70
                               'length' => 191,
71 72
                               'not null' => true),
                'profile_id' => array('type' => 'int'),
73 74
                'event_uri' => array('type' => 'varchar',
                              'length' => 191,
75
                              'not null' => true,
76
                              'description' => 'Event URI'),
77 78 79
                'response' => array('type' => 'char',
                                  'length' => '1',
                                  'description' => 'Y, N, or ? for three-state yes, no, maybe'),
80 81 82 83 84 85
                'created' => array('type' => 'datetime',
                                   'not null' => true),
            ),
            'primary key' => array('id'),
            'unique keys' => array(
                '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 90 91
                                    'rsvp_profile_id__key' => array('profile', array('profile_id' => 'id'))),
            'indexes' => array('rsvp_created_idx' => array('created')),
        );
Evan Prodromou's avatar
Evan Prodromou committed
92 93
    }

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    static public function beforeSchemaUpdate()
    {
        $table = strtolower(get_called_class());
        $schema = Schema::get();
        $schemadef = $schema->getTableDef($table);

        // 2015-12-31 RSVPs refer to Happening by event_uri now, not event_id. Let's migrate!
        if (isset($schemadef['fields']['event_uri'])) {
            // We seem to have already migrated, good!
            return;
        }

        // this is a "normal" upgrade from StatusNet for example
        echo "\nFound old $table table, upgrading it to add 'event_uri' field...";

        $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 112 113 114 115 116 117
        $schema->ensureTable($table, $schemadef);

        $rsvp = new RSVP();
        $rsvp->find();
        while ($rsvp->fetch()) {
            $event = Happening::getKV('id', $rsvp->event_id);
            if (!$event instanceof Happening) {
118
                $rsvp->delete();
119 120 121 122 123 124 125 126 127 128
                continue;
            }
            $orig = clone($rsvp);
            $rsvp->event_uri = $event->uri;
            $rsvp->updateWithKeys($orig);
        }
        print "DONE.\n";
        print "Resuming core schema upgrade...";
    }

129
    static function saveActivityObject(Activity $act, Notice $stored)
Evan Prodromou's avatar
Evan Prodromou committed
130
    {
131 132 133
        $target = Notice::getByKeys(array('uri'=>$act->target->id));
        if (!ActivityUtils::compareTypes($target->getObjectType(), [ Happening::OBJECT_TYPE ])) {
            throw new ClientException('RSVP not aimed at a Happening');
134
        }
Evan Prodromou's avatar
Evan Prodromou committed
135

136
        // FIXME: Maybe we need some permission handling here, though I think it's taken care of in saveActivity?
137

138
        try {
139 140
            $other = RSVP::getByKeys( [ 'profile_id' => $stored->getProfile()->getID(),
                                        'event_uri' => $target->getUri(),
141
                                      ] );
142
            // TRANS: Client exception thrown when trying to save an already existing RSVP ("please respond").
143 144 145
            throw new AlreadyFulfilledException(_m('RSVP already exists.'));
        } catch (NoResultException $e) {
            // No previous RSVP, so go ahead and add.
146
        }
Evan Prodromou's avatar
Evan Prodromou committed
147

148
        $rsvp = new RSVP();
149 150 151 152 153 154
        $rsvp->id          = UUID::gen();   // remove this
        $rsvp->uri         = $stored->getUri();
        $rsvp->profile_id  = $stored->getProfile()->getID();
        $rsvp->event_uri   = $target->getUri();
        $rsvp->response    = self::codeFor($stored->getVerb());
        $rsvp->created     = $stored->getCreated();
Evan Prodromou's avatar
Evan Prodromou committed
155

156
        $rsvp->insert();
Evan Prodromou's avatar
Evan Prodromou committed
157

158
        self::blow('rsvp:for-event:%s', $target->getUri());
159

160
        return $rsvp;
161 162
    }

mattl's avatar
mattl committed
163 164 165 166 167 168 169 170 171 172
    static public function getObjectType()
    {
        return ActivityObject::ACTIVITY;
    }

    public function asActivityObject()
    {
        $happening = $this->getEvent();

        $actobj = new ActivityObject();
mattl's avatar
mattl committed
173
        $actobj->id = $this->getUri();
mattl's avatar
mattl committed
174 175 176 177 178 179 180 181
        $actobj->type = self::getObjectType();
        $actobj->title = $this->asString();
        $actobj->content = $this->asString();
        $actobj->target = array($happening->asActivityObject());

        return $actobj;
    }

182
    static function codeFor($verb)
183
    {
184 185
        switch (true) {
        case ActivityUtils::compareVerbs($verb, [RSVP::POSITIVE]):
186 187
            return 'Y';
            break;
188
        case ActivityUtils::compareVerbs($verb, [RSVP::NEGATIVE]):
189 190
            return 'N';
            break;
191
        case ActivityUtils::compareVerbs($verb, [RSVP::POSSIBLE]):
192 193 194
            return '?';
            break;
        default:
195 196
            // TRANS: Exception thrown when requesting an undefined verb for RSVP.
            throw new Exception(sprintf(_m('Unknown verb "%s".'),$verb));
197
        }
198 199
    }

Evan Prodromou's avatar
Evan Prodromou committed
200
    static function verbFor($code)
201
    {
202 203
        switch ($code) {
        case 'Y':
204
        case 'yes':
205 206 207
            return RSVP::POSITIVE;
            break;
        case 'N':
208
        case 'no':
209 210 211
            return RSVP::NEGATIVE;
            break;
        case '?':
212
        case 'maybe':
213 214 215
            return RSVP::POSSIBLE;
            break;
        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 229 230
        return $this->event_uri;
    }

mattl's avatar
mattl committed
231
    public function getStored()
232 233 234 235 236 237 238
    {
        return Notice::getByKeys(['uri' => $this->getUri()]);
    }

    static function fromStored(Notice $stored)
    {
        return self::getByKeys(['uri' => $stored->getUri()]);
Evan Prodromou's avatar
Evan Prodromou committed
239
    }
Evan Prodromou's avatar
Evan Prodromou committed
240

mattl's avatar
mattl committed
241 242 243 244 245 246
    static function byEventAndActor(Happening $event, Profile $actor)
    {
        return self::getByKeys(['event_uri' => $event->getUri(),
                                'profile_id' => $actor->getID()]);
    }

mattl's avatar
mattl committed
247
    static function forEvent(Happening $event)
Evan Prodromou's avatar
Evan Prodromou committed
248
    {
249
        $keypart = sprintf('rsvp:for-event:%s', $event->getUri());
250 251 252 253 254 255 256 257 258 259 260 261 262

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

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

            $rsvp = new RSVP();

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

263
            $rsvp->event_uri = $event->getUri();
264 265 266 267 268 269 270 271 272

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

Evan Prodromou's avatar
Evan Prodromou committed
273 274 275
        $rsvps = array(RSVP::POSITIVE => array(),
                       RSVP::NEGATIVE => array(),
                       RSVP::POSSIBLE => array());
Evan Prodromou's avatar
Evan Prodromou committed
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;
Evan Prodromou's avatar
Evan Prodromou committed
282 283 284 285 286
            }
        }

        return $rsvps;
    }
Evan Prodromou's avatar
Evan Prodromou committed
287 288 289

    function getProfile()
    {
290
        return Profile::getByID($this->profile_id);
Evan Prodromou's avatar
Evan Prodromou committed
291 292 293 294
    }

    function getEvent()
    {
295
        return Happening::getByKeys(['uri' => $this->getEventUri()]);
Evan Prodromou's avatar
Evan Prodromou committed
296 297 298 299 300
    }

    function asHTML()
    {
        return self::toHTML($this->getProfile(),
301
                            $this->getEvent(),
Evan Prodromou's avatar
Evan Prodromou committed
302 303 304 305 306 307
                            $this->response);
    }

    function asString()
    {
        return self::toString($this->getProfile(),
308
                              $this->getEvent(),
Evan Prodromou's avatar
Evan Prodromou committed
309 310 311
                              $this->response);
    }

312
    static function toHTML(Profile $profile, Happening $event, $response)
Evan Prodromou's avatar
Evan Prodromou committed
313 314 315 316 317
    {
        $fmt = null;

        switch ($response) {
        case 'Y':
318 319 320
            // 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.
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>");
Evan Prodromou's avatar
Evan Prodromou committed
322 323
            break;
        case 'N':
324 325 326
            // 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.
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>");
Evan Prodromou's avatar
Evan Prodromou committed
328 329
            break;
        case '?':
330 331 332
            // 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.
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>");
Evan Prodromou's avatar
Evan Prodromou committed
334 335
            break;
        default:
336 337
            // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
            // TRANS: %s is the non-existing response code.
338
            throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
Evan Prodromou's avatar
Evan Prodromou committed
339 340
        }

341 342
        if (empty($event)) {
            $eventUrl = '#';
343 344
            // TRANS: Used as event title when not event title is available.
            // 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 349 350
            $eventTitle = $event->title;
        }

Evan Prodromou's avatar
Evan Prodromou committed
351
        return sprintf($fmt,
352
                       htmlspecialchars($profile->getUrl()),
Evan Prodromou's avatar
Evan Prodromou committed
353
                       htmlspecialchars($profile->getBestName()),
354 355
                       htmlspecialchars($eventUrl),
                       htmlspecialchars($eventTitle));
Evan Prodromou's avatar
Evan Prodromou committed
356 357 358 359 360 361 362 363
    }

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

        switch ($response) {
        case 'Y':
364 365
            // 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.
366
            $fmt = _m('%1$s is attending %2$s.');
Evan Prodromou's avatar
Evan Prodromou committed
367 368
            break;
        case 'N':
369 370
            // 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.
371
            $fmt = _m('%1$s is not attending %2$s.');
Evan Prodromou's avatar
Evan Prodromou committed
372 373
            break;
        case '?':
374 375
            // 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.
376
            $fmt = _m('%1$s might attend %2$s.');
Evan Prodromou's avatar
Evan Prodromou committed
377 378
            break;
        default:
379 380
            // TRANS: Exception thrown when requesting a user's RSVP status for a non-existing response code.
            // TRANS: %s is the non-existing response code.
381
            throw new Exception(sprintf(_m('Unknown response code %s.'),$response));
Evan Prodromou's avatar
Evan Prodromou committed
382 383 384
            break;
        }

385
        if (empty($event)) {
386 387
            // TRANS: Used as event title when not event title is available.
            // TRANS: Used as: Username [is [not ] attending|might attend] an unknown event.
388
            $eventTitle = _m('an unknown event');
389 390 391 392
        } else {
            $eventTitle = $event->title;
        }

Evan Prodromou's avatar
Evan Prodromou committed
393 394
        return sprintf($fmt,
                       $profile->getBestName(),
395
                       $eventTitle);
Evan Prodromou's avatar
Evan Prodromou committed
396
    }
397

398
    public function delete($useWhere=false)
399
    {
mattl's avatar
mattl committed
400
        self::blow('rsvp:for-event:%s', $this->id);
401
        return parent::delete($useWhere);
402
    }
403 404 405 406 407 408 409 410 411 412

    public function insert()
    {
        $result = parent::insert();
        if ($result === false) {
            common_log_db_error($this, 'INSERT', __FILE__);
            throw new ServerException(_('Failed to insert '._ve(get_called_class()).' into database'));
        }
        return $result;
    }
Evan Prodromou's avatar
Evan Prodromou committed
413
}