Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/site/app/models/collection.php
blob: 59e0d13a53ed40dbc74f5f674bdba3f1ae26fa5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
<?php
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is addons.mozilla.org site.
 *
 * The Initial Developer of the Original Code is
 * The Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Ryan Doherty <rdoherty@mozilla.com>
 *   l.m.orchard <lorchard@mozilla.com>
 *   Frederic Wenzel <fwenzel@mozilla.com>
 *   Wil Clouser <wclouser@mozilla.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

class Collection extends AppModel
{
    var $name = "Collection";

    var $hasAndBelongsToMany = array(
        'Addon' => array(
            'className' => 'Addon',
            'joinTable' => 'addons_collections',
            'foreignKey' => 'collection_id',
            'associationForeignKey' => 'addon_id'
        ),
        'Subscriptions' => array(
            'className' => 'User',
            'joinTable' => 'collection_subscriptions',
            'foreignKey' => 'collection_id',
            'associationForeignKey' => 'user_id'
        ),
        'Users' => array(
            'className' => 'User',
            'joinTable' => 'collections_users',
            'foreignKey' => 'collection_id',
            'associationForeignKey' => 'user_id'
        )
    );
    
    var $hasAndBelongsToMany_full = array(
        'Tag' => array(
            'className'  => 'Tag',
            'joinTable'  => 'collections_tags',
            'foreignKey' => 'collection_id',
            'associationForeignKey'=> 'tag_id'
        ),
        'Addon' => array(
            'className' => 'Addon',
            'joinTable' => 'addons_collections',
            'foreignKey' => 'collection_id',
            'associationForeignKey' => 'addon_id'
        ),
        'Subscriptions' => array(
            'className' => 'User',
            'joinTable' => 'collection_subscriptions',
            'foreignKey' => 'collection_id',
            'associationForeignKey' => 'user_id'
        ),
        'Users' => array(
            'className' => 'User',
            'joinTable' => 'collections_users',
            'foreignKey' => 'collection_id',
            'associationForeignKey' => 'user_id'
        )
    );

    var $hasMany_full = array(
                         'Promo' =>
                         array('className'   => 'CollectionPromo',
                               'conditions'  => '',
                               'order'       => '',
                               'limit'       => '',
                               'foreignKey'  => 'collection_id',
                               'dependent'   => true,
                               'exclusive'   => false,
                               'finderSql'   => ''
                         )
                    );


    var $validate = array(
        'name'        => VALID_NOT_EMPTY,
        'description' => VALID_NOT_EMPTY
    );
    
    var $translated_fields = array(
        'name',
        'description',
    );

    /**
     * validate name field
     */
    function clean_name($input) {
        $msg = sprintf(___('collection_name_limit'), Collection::MAX_NAME_LENGTH);
        $this->maxLength('name', $input, Collection::MAX_NAME_LENGTH, $msg);
    }

    /**
     * validate description field
     */
    function clean_description($input) {
        $msg = sprintf(___('collection_description_limit'), Collection::MAX_DESC_LENGTH);
        $this->maxLength('description', $input, Collection::MAX_DESC_LENGTH, $msg);
    }

    /**
     * validate nickname field
     */
    function clean_nickname($input) {
        if (preg_match(INVALID_COLLECTION_NICKNAME_CHARS, $input)
            || $this->isNicknameTaken($input)) {
            $this->invalidate('nickname');
        }
    }

    const COLLECTION_TYPE_NORMAL = 0;
    const COLLECTION_TYPE_AUTOPUBLISHER = 1;
    const COLLECTION_TYPE_EDITORSPICK = 2;

    const MAX_NAME_LENGTH = 50;
    const MAX_DESC_LENGTH = 200;

    /**
     * Generates a pseudo-random UUID.
     * Slightly modified version of a function submitted to php.net:
     * http://us2.php.net/manual/en/function.com-create-guid.php#52354
     *
     * @access public
     */
    function uuid() {
        mt_srand((double)microtime()*10000);
        $charid = md5(uniqid(rand(), true));
        $hyphen = chr(45);// "-"
        $uuid = substr($charid, 0, 8).$hyphen
              . substr($charid, 8, 4).$hyphen
              . substr($charid,12, 4).$hyphen
              . substr($charid,16, 4).$hyphen
              . substr($charid,20,12);

        return $uuid;
    } 

    /**
     * Verifies a UUID's structure (not that it actually exists in our database).
     *
     * @param string uuid
     * @return boolean
     */
    function isValidUUID($uuid) {
        if (preg_match(VALID_UUID_REQ, $uuid) > 0) {
            return true;
        }
        return false;
    } 

    /**
     * Before saving, set a UUID if none yet set.
     */
    function beforeSave() {
        if (empty($this->id) && empty($this->data[$this->name]['id'])) {
            // If no ID set yet, assume this is a new record and give it a UUID
            $this->data[$this->name]['uuid'] = $this->uuid();
        }

        // if nickname is set, make sure it's unique
        if (!empty($this->data[$this->name]['nickname'])) {
            if ($this->isNicknameTaken($this->data[$this->name]['nickname'])) {
                $this->invalidate('nickname');
                return false;
            }
        } else {
            $this->data[$this->name]['nickname'] = null;
        }

        return parent::beforeSave();
    }

    /**
     * Subscribes a user to a collection
     *
     * @param int $id - the id of the collection
     * @param int $userId - the id of the user
     * @return bool success
     */
    function subscribe($id, $userId) {
        // Perform SQL escaping.
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $e_id     = $db->value($id); 
        $e_userId = $db->value($userId);

        $this->execute("
            INSERT IGNORE INTO collection_subscriptions
            (collection_id, user_id, created, modified)
            VALUES 
            ({$e_id}, {$e_userId}, NOW(), NOW())
        ");
        return ($this->getAffectedRows() > 0);
    }
    
    /**
     * Unsubscribe a user to a collection
     *
     * @param int $id - id of the collection
     * @param int $userId - id of user
     * @return bool success
     */
    function unsubscribe($id, $userId) {
        // Perform SQL escaping.
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $e_id     = $db->value($id); 
        $e_userId = $db->value($userId);

        $this->execute("
            DELETE FROM collection_subscriptions 
            WHERE 
                user_id = {$e_userId} AND
                collection_id = {$e_id}
        ");
        return ($this->getAffectedRows() > 0);
    }
    
    /**
     * Update the subscribers count for a collection.
     *
     * @param int $id - id of the collection
     */
    function _updateSubscribersCount($e_id) {
        return $this->execute("
            UPDATE collections 
            SET subscribers=(
                SELECT count(collection_id) 
                FROM collection_subscriptions 
                WHERE collection_id={$e_id}
            ) 
            WHERE id={$e_id}
        ");
    }
    
    /**
     * Add an add-on to a collection
     *
     * @param int $collectionId - collection id
     * @param int $addonId - add-on id
     */
    function addAddonToCollection($collection_id, $user_id, $addon_id) {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        
        $collection_id = $db->value($collection_id);
        $user_id = $db->value($user_id);
        $addon_id = $db->value($addon_id);

        $ret = $this->execute("
            INSERT INTO addons_collections 
            (addon_id, user_id, collection_id, added) 
            VALUES 
            ({$addon_id}, {$user_id}, {$collection_id}, NOW())
        ");
        return $ret;
    }

    /* Update the addon count for collection $id. */
    function _updateAddonCount($id) {
        return $this->execute("
            UPDATE collections
            SET addonCount=(SELECT COUNT(*)
                            FROM addons_collections
                            WHERE collection_id={$id})
            WHERE id=${id}");
    }

    /**
     * Adds a user to a collection so they can edit it
     *
     * @param int $collectionId - id of the collection
     * @param int $userId - id of the user
     * @param int $role - role type
     */
    function addUser($collectionId, $userId, $role) {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);

        $collectionId = $db->value($collectionId);
        $userId = $db->value($userId);
        $role = $db->value($role);

        return $this->execute("INSERT INTO collections_users (collection_id, user_id, role) VALUES ({$collectionId}, {$userId}, {$role})");
    }
    
    /**
     * Remove a user
     *
     * @param int $collectionId - id of the collection
     * @param int $userId - id of the user
     */
    function removeUser($collectionId, $userId) {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);

        $collectionId = $db->value($collectionId);
        $userId = $db->value($userId);

        return $this->execute("DELETE FROM collections_users WHERE user_id = {$userId} AND collection_id={$collectionId}");
    }

    /**
     * Remove all user rights from a collection, by role
     * Warning: do not do this with OWNER unless you know what you are doing.
     *
     * @param int $collection_id
     * @param int $role user role to remove, for example COLLECTION_ROLE_ADMIN
     */
    function removeAllUsersByRole($collection_id, $role) {
        return $this->execute("DELETE FROM collections_users WHERE collection_id={$collection_id} AND role={$role};");
    }

    /**
     * Deletes a collection
     *
     * @param int $id - collection id
     */
    function delete($id) {
        $this->execute("DELETE FROM collections_users WHERE collection_id = {$id}");
        $this->execute("DELETE FROM addons_collections WHERE collection_id = {$id}");
        $this->execute("DELETE FROM collections_tags WHERE collection_id = {$id}");
        $this->execute("DELETE FROM collection_subscriptions WHERE collection_id = {$id}");
        $this->execute("DELETE FROM collection_promos WHERE collection_id = {$id}");
        $this->execute("DELETE FROM collections WHERE id = {$id}");
        return true;
    }

    /**
     * returns the ids of all collections owned or managed by a given user
     * @param int $userid
     * @param mixed $roles (optional) array of allowed roles, defaults to "any role"
     * @return array collection ids, false on error
     */
    function getCollectionsByUser($userid, $roles = null) {
        if (!is_numeric($userid)) return false;

        $role_sql = '';
        if (!empty($role)) {
            if (is_scalar($roles)) $roles = array($roles);
            foreach ($roles as &$role) if (!is_numeric($role)) return false;
            $role_sql = ' AND role IN ('.implode(',', $roles).')';
        }

        $res = $this->query("SELECT collection_id FROM collections_users WHERE user_id = {$userid}{$role_sql}");
        if (empty($res)) return array();

        $ids = array();
        foreach ($res as &$row) $ids[] = $row['collections_users']['collection_id'];
        return $ids;
    }

    /**
     * returns the ids of all collections subscribed to by a given user
     * @param int $userid
     * @return array collection ids, false on error
     */
    function getSubscriptionsByUser($userid) {
        if (!is_numeric($userid)) return false;

        $res = $this->query("SELECT collection_id FROM collection_subscriptions WHERE user_id = {$userid}");
        if (empty($res)) return array();

        $ids = array();
        foreach ($res as &$row) $ids[] = $row['collection_subscriptions']['collection_id'];
        return $ids;
    }

    /**
     * Get a list of users and roles
     * 
     * @param int id of the collection
     * @param array (optional) list of roles for which users should be fetched
     */
    function getUsers($collectionId, $roles=null) {
        if (!is_numeric($collectionId)) return null;
        
        // Build SQL to look up user IDs and roles for collection
        $sql = "
            SELECT user_id, role 
            FROM collections_users 
            WHERE collection_id={$collectionId}
        ";

        // Add an IN clause if roles supplied.
        if (null !== $roles && is_array($roles)) {
            $s_roles = array();
            foreach ($roles as $role) if (is_numeric($role)) 
                $s_roles[] = $role;
            $sql .= " AND role IN ( ". join(',', $s_roles) . " )";
        }

        // Fetch the rows and map them to user IDs.
        $rows = $this->execute($sql);
        $user_map = array();
        foreach ($rows as $row) {
            $user_map[$row['collections_users']['user_id']] = 
                $row['collections_users'];
        }

        // Look up users with user IDs, merge the role info into each found.
        $users = $this->User->findAllById(array_keys($user_map));
        for ($i=0; $i<count($users); $i++) {
            // HACK: CollectionUser used in lieu of an actual model class.
            $users[$i]['CollectionUser'] =
                $user_map[$users[$i]['User']['id']];
        }

        return $users;
    }

    /**
     * Decide whether or not a given collection is writable by a user.
     * 
     * @param int id of the collection
     * @param int id of the user
     */
    function isWritableByUser($collection_id, $user_id) {
        if (!is_numeric($collection_id)) return null;
        if (!is_numeric($user_id)) return null;

        $role = $this->getUserRole($collection_id, $user_id);
        if ($role === false) return false; // no access rights
        return in_array($role, array(
            COLLECTION_ROLE_OWNER, 
            COLLECTION_ROLE_ADMIN, 
            COLLECTION_ROLE_PUBLISHER 
        ));
    }

    /**
     * Determine a user's role for a collection (admin, owner, subscriber...).
     *
     * @param int $collection_id
     * @param int $user_id
     * @return role ID, false if none
     */
    function getUserRole($collection_id, $user_id) {
        if (!is_numeric($collection_id)) return null;
        if (!is_numeric($user_id)) return null;

        $rows = $this->execute("
            SELECT role
            FROM collections_users 
            WHERE 
                collection_id={$collection_id} AND
                user_id={$user_id}
        ");
        if (empty($rows)) return false;
        return (int)$rows[0]['collections_users']['role'];
    }

    /**
     * Look up the ID for a collection by UUID, less expensive than a full 
     * fetch.
     *
     * @param   string Collection UUID
     * @return  string Collection ID
     */
    function getIdForUuid($uuid) {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $uuid = $db->value($uuid);
        $rows = $this->execute("
            SELECT id
            FROM collections
            WHERE uuid={$uuid}
        ");
        $id = null;
        if (!empty($rows[0])) {
            $id = $rows[0]['Collection']['id'];
        }
        return $id;
    }

    /**
     * Look up ID for a UUID or nickname.
     *
     * @param string UUID or nickname
     * @return int collection ID
     */
    function getIdForUuidOrNickname($uuid_or_nickname) {
        $id = null;
        if (strlen($uuid_or_nickname) == 36) { // possibly a UUID
            $id = $this->getIdForUuid($uuid_or_nickname);
        }
        if (is_null($id)) { // try nickname
            $db =& ConnectionManager::getDataSource($this->useDbConfig);
            $uuid_or_nickname = $db->value($uuid_or_nickname);
            $rows = $this->execute("
                SELECT id
                FROM collections
                WHERE nickname={$uuid_or_nickname}
            ");
            if (!empty($rows[0])) {
                $id = $rows[0]['Collection']['id'];
            }
        }
        return $id;
    }

    /**
     * Determine the last modified time for a collection, found either by
     * ID or UUID.  If a UUID is supplied, it's converted to an ID via 
     * query first.
     *
     * @param   string Collection ID
     * @param   string Collection UUID, replaces ID if supplied
     * @return  string Last modified date for collection and addons
     */
    function getLastModifiedForCollection($id=null, $uuid=null) {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);

        if (null !== $uuid) {
            $id = $this->getIdForUUID($uuid);
        }

        $id = $db->value($id);

        $dates = array();

        $rows = $this->execute("
            SELECT added, modified
            FROM addons_collections
            WHERE collection_id={$id}
            ORDER BY added DESC
            LIMIT 1
        ");
        foreach ($rows as $row) {
            $dates[] = $row['addons_collections']['added'];
            $dates[] = $row['addons_collections']['modified'];
        }
            
        $rows = $this->execute("
            SELECT modified
            FROM collections
            WHERE id={$id} 
        ");
        foreach ($rows as $row) {
            $dates[] = $row['Collection']['modified'];
        }

        if (empty($dates)) return null;
        rsort($dates);
        return strtotime($dates[0]);
    }

    /**
     * is collection nickname taken yet?
     * @param string $nickname proposed nickname
     * @return bool true if nickname is occupied already, false otherwise
     */
    function isNicknameTaken($nickname) {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $nickname = $db->value($nickname);
        $res = $this->query("SELECT id FROM collections WHERE nickname = {$nickname}");
        if (empty($res)) return false;
        if (empty($this->id))
            return (!empty($res));
        else
            return ($this->id != $res[0]['collections']['id']);
    }

    function isSubscribed($collection_id, $user_id) {
        $res = $this->execute("SELECT user_id FROM collection_subscriptions
                               WHERE user_id={$user_id}
                                 AND collection_id={$collection_id}");
        return !empty($res);
    }

    function getNickname($collection) {
        $c = $collection['Collection'];
        return isset($c['nickname']) ? $c['nickname'] : $c['uuid'];
    }

    function getDetailUrl($collection) {
        return '/collection/' .  $this->getNickname($collection);
    }

    function getSubscribeUrl($ajax=false) {
        return '/collections/subscribe/' . ($ajax === true ? 'ajax' : '');
    }

    function getUnsubscribeUrl($ajax=false) {
        return '/collections/unsubscribe/' . ($ajax === true ? 'ajax' : '');
    }

    /**
     * Get editor's picks for the current application.
     *
     * @param limit the number you want
     * @return array of collections
     */
    function getEditorPicks($limit=null) {
        $conditions = array(
            'Collection.collection_type' => Collection::COLLECTION_TYPE_EDITORSPICK,
            'Collection.application_id'  => APP_ID
        );
        $this->unbindFully();
        $collections = $this->findAll($conditions,null,'Collection.downloads DESC',$limit);
        return $collections;
    }
}