]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile_list.php
Don't abort on too long notices in Notice::saveActivity
[quix0rs-gnu-social.git] / classes / Profile_list.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
17  *
18  * @category Notices
19  * @package  StatusNet
20  * @author   Shashi Gowda <connect2shashi@gmail.com>
21  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
22  */
23
24 if (!defined('GNUSOCIAL')) { exit(1); }
25
26 class Profile_list extends Managed_DataObject
27 {
28     public $__table = 'profile_list';                      // table name
29     public $id;                              // int(4)  primary_key not_null
30     public $tagger;                          // int(4)
31     public $tag;                             // varchar(64)
32     public $description;                     // text
33     public $private;                         // tinyint(1)
34     public $created;                         // datetime   not_null default_0000-00-00%2000%3A00%3A00
35     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
36     public $uri;                             // varchar(191)  unique_key   not 255 because utf8mb4 takes more space
37     public $mainpage;                        // varchar(191)   not 255 because utf8mb4 takes more space
38     public $tagged_count;                    // smallint
39     public $subscriber_count;                // smallint
40
41     public static function schemaDef()
42     {
43         return array(
44             'fields' => array(
45                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
46                 'tagger' => array('type' => 'int', 'not null' => true, 'description' => 'user making the tag'),
47                 'tag' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'people tag'),
48                 'description' => array('type' => 'text', 'description' => 'description of the people tag'),
49                 'private' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'is this tag private'),
50
51                 'created' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date the tag was added'),
52                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date the tag was modified'),
53
54                 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universal identifier'),
55                 'mainpage' => array('type' => 'varchar', 'length' => 191, 'description' => 'page to link to'),
56                 'tagged_count' => array('type' => 'int', 'default' => 0, 'description' => 'number of people tagged with this tag by this user'),
57                 'subscriber_count' => array('type' => 'int', 'default' => 0, 'description' => 'number of subscribers to this tag'),
58             ),
59             'primary key' => array('tagger', 'tag'),
60             'unique keys' => array(
61                 'profile_list_id_key' => array('id')
62             ),
63             'foreign keys' => array(
64                 'profile_list_tagger_fkey' => array('profile', array('tagger' => 'id')),
65             ),
66             'indexes' => array(
67                 'profile_list_modified_idx' => array('modified'),
68                 'profile_list_tag_idx' => array('tag'),
69                 'profile_list_tagger_tag_idx' => array('tagger', 'tag'),
70                 'profile_list_tagged_count_idx' => array('tagged_count'),
71                 'profile_list_subscriber_count_idx' => array('subscriber_count'),
72             ),
73         );
74     }
75
76     /**
77      * get the tagger of this profile_list object
78      *
79      * @return Profile the tagger
80      */
81
82     function getTagger()
83     {
84         return Profile::getByID($this->tagger);
85     }
86
87     /**
88      * return a string to identify this
89      * profile_list in the user interface etc.
90      *
91      * @return String
92      */
93
94     function getBestName()
95     {
96         return $this->tag;
97     }
98
99     /**
100      * return a uri string for this profile_list
101      *
102      * @return String uri
103      */
104
105     function getUri()
106     {
107         $uri = null;
108         if (Event::handle('StartProfiletagGetUri', array($this, &$uri))) {
109             if (!empty($this->uri)) {
110                 $uri = $this->uri;
111             } else {
112                 $uri = common_local_url('profiletagbyid',
113                                         array('id' => $this->id, 'tagger_id' => $this->tagger));
114             }
115         }
116         Event::handle('EndProfiletagGetUri', array($this, &$uri));
117         return $uri;
118     }
119
120     /**
121      * return a url to the homepage of this item
122      *
123      * @return String home url
124      */
125
126     function homeUrl()
127     {
128         $url = null;
129         if (Event::handle('StartUserPeopletagHomeUrl', array($this, &$url))) {
130             // normally stored in mainpage, but older ones may be null
131             if (!empty($this->mainpage)) {
132                 $url = $this->mainpage;
133             } else {
134                 $url = common_local_url('showprofiletag',
135                                         array('nickname' => $this->getTagger()->nickname,
136                                               'tag'    => $this->tag));
137             }
138         }
139         Event::handle('EndUserPeopletagHomeUrl', array($this, &$url));
140         return $url;
141     }
142
143     /**
144      * return an immutable url for this object
145      *
146      * @return String permalink
147      */
148
149     function permalink()
150     {
151         $url = null;
152         if (Event::handle('StartProfiletagPermalink', array($this, &$url))) {
153             $url = common_local_url('profiletagbyid',
154                                     array('id' => $this->id));
155         }
156         Event::handle('EndProfiletagPermalink', array($this, &$url));
157         return $url;
158     }
159
160     /**
161      * Query notices by users associated with this tag,
162      * but first check the cache before hitting the DB.
163      *
164      * @param integer $offset   offset
165      * @param integer $limit    maximum no of results
166      * @param integer $since_id=null    since this id
167      * @param integer $max_id=null  maximum id in result
168      *
169      * @return Notice the query
170      */
171
172     function getNotices($offset, $limit, $since_id=null, $max_id=null)
173     {
174         $stream = new PeopletagNoticeStream($this);
175
176         return $stream->getNotices($offset, $limit, $since_id, $max_id);
177     }
178
179     /**
180      * Get subscribers (local and remote) to this people tag
181      * Order by reverse chronology
182      *
183      * @param integer $offset   offset
184      * @param integer $limit    maximum no of results
185      * @param integer $since_id=null    since unix timestamp
186      * @param integer $upto=null  maximum unix timestamp when subscription was made
187      *
188      * @return Profile results
189      */
190
191     function getSubscribers($offset=0, $limit=null, $since=0, $upto=0)
192     {
193         $subs = new Profile();
194
195         $subs->joinAdd(
196             array('id', 'profile_tag_subscription:profile_id')
197         );
198         $subs->whereAdd('profile_tag_subscription.profile_tag_id = ' . $this->id);
199
200         $subs->selectAdd('unix_timestamp(profile_tag_subscription.' .
201                          'created) as "cursor"');
202
203         if ($since != 0) {
204             $subs->whereAdd('cursor > ' . $since);
205         }
206
207         if ($upto != 0) {
208             $subs->whereAdd('cursor <= ' . $upto);
209         }
210
211         if ($limit != null) {
212             $subs->limit($offset, $limit);
213         }
214
215         $subs->orderBy('profile_tag_subscription.created DESC');
216         $subs->find();
217
218         return $subs;
219     }
220
221     /**
222      * Get all and only local subscribers to this people tag
223      * used for distributing notices to user inboxes.
224      *
225      * @return array ids of users
226      */
227
228     function getUserSubscribers()
229     {
230         // XXX: cache this
231
232         $user = new User();
233         if(common_config('db','quote_identifiers'))
234             $user_table = '"user"';
235         else $user_table = 'user';
236
237         $qry =
238           'SELECT id ' .
239           'FROM '. $user_table .' JOIN profile_tag_subscription '.
240           'ON '. $user_table .'.id = profile_tag_subscription.profile_id ' .
241           'WHERE profile_tag_subscription.profile_tag_id = %d ';
242
243         $user->query(sprintf($qry, $this->id));
244
245         $ids = array();
246
247         while ($user->fetch()) {
248             $ids[] = $user->id;
249         }
250
251         $user->free();
252
253         return $ids;
254     }
255
256     /**
257      * Check to see if a given profile has
258      * subscribed to this people tag's timeline
259      *
260      * @param mixed $id User or Profile object or integer id
261      *
262      * @return boolean subscription status
263      */
264
265     function hasSubscriber($id)
266     {
267         if (!is_numeric($id)) {
268             $id = $id->id;
269         }
270
271         $sub = Profile_tag_subscription::pkeyGet(array('profile_tag_id' => $this->id,
272                                                        'profile_id'     => $id));
273         return !empty($sub);
274     }
275
276     /**
277      * Get profiles tagged with this people tag,
278      * include modified timestamp as a "cursor" field
279      * order by descending order of modified time
280      *
281      * @param integer $offset   offset
282      * @param integer $limit    maximum no of results
283      * @param integer $since_id=null    since unix timestamp
284      * @param integer $upto=null  maximum unix timestamp when subscription was made
285      *
286      * @return Profile results
287      */
288
289     function getTagged($offset=0, $limit=null, $since=0, $upto=0)
290     {
291         $tagged = new Profile();
292         $tagged->joinAdd(array('id', 'profile_tag:tagged'));
293
294         #@fixme: postgres
295         $tagged->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
296         $tagged->whereAdd('profile_tag.tagger = '.$this->tagger);
297         $tagged->whereAdd("profile_tag.tag = '{$this->tag}'");
298
299         if ($since != 0) {
300             $tagged->whereAdd('cursor > ' . $since);
301         }
302
303         if ($upto != 0) {
304             $tagged->whereAdd('cursor <= ' . $upto);
305         }
306
307         if ($limit != null) {
308             $tagged->limit($offset, $limit);
309         }
310
311         $tagged->orderBy('profile_tag.modified DESC');
312         $tagged->find();
313
314         return $tagged;
315     }
316
317     /**
318      * Gracefully delete one or many people tags
319      * along with their members and subscriptions data
320      *
321      * @return boolean success
322      */
323
324     function delete($useWhere=false)
325     {
326         // force delete one item at a time.
327         if (empty($this->id)) {
328             $this->find();
329             while ($this->fetch()) {
330                 $this->delete();
331             }
332         }
333
334         Profile_tag::cleanup($this);
335         Profile_tag_subscription::cleanup($this);
336
337         self::blow('profile:lists:%d', $this->tagger);
338
339         return parent::delete($useWhere);
340     }
341
342     /**
343      * Update a people tag gracefully
344      * also change "tag" fields in profile_tag table
345      *
346      * @param Profile_list $dataObject    Object's original form
347      *
348      * @return boolean success
349      */
350
351     function update($dataObject=false)
352     {
353         if (!is_object($dataObject) && !$dataObject instanceof Profile_list) {
354             return parent::update($dataObject);
355         }
356
357         $result = true;
358
359         // if original tag was different
360         // check to see if the new tag already exists
361         // if not, rename the tag correctly
362         if($dataObject->tag != $this->tag || $dataObject->tagger != $this->tagger) {
363             $existing = Profile_list::getByTaggerAndTag($this->tagger, $this->tag);
364             if(!empty($existing)) {
365                 // TRANS: Server exception.
366                 throw new ServerException(_('The tag you are trying to rename ' .
367                                             'to already exists.'));
368             }
369             // move the tag
370             // XXX: allow OStatus plugin to send out profile tag
371             $result = Profile_tag::moveTag($dataObject, $this);
372         }
373         return parent::update($dataObject);
374     }
375
376     /**
377      * return an xml string representing this people tag
378      * as the author of an atom feed
379      *
380      * @return string atom author element
381      */
382
383     function asAtomAuthor()
384     {
385         $xs = new XMLStringer(true);
386
387         $tagger = $this->getTagger();
388         $xs->elementStart('author');
389         $xs->element('name', null, '@' . $tagger->nickname . '/' . $this->tag);
390         $xs->element('uri', null, $this->permalink());
391         $xs->elementEnd('author');
392
393         return $xs->getString();
394     }
395
396     /**
397      * return an xml string to represent this people tag
398      * as a noun in an activitystreams feed.
399      *
400      * @param string $element the xml tag
401      *
402      * @return string activitystreams noun
403      */
404
405     function asActivityNoun($element)
406     {
407         $noun = ActivityObject::fromPeopletag($this);
408         return $noun->asString('activity:' . $element);
409     }
410
411     /**
412      * get the cached number of profiles tagged with this
413      * people tag, re-count if the argument is true.
414      *
415      * @param boolean $recount  whether to ignore cache
416      *
417      * @return integer count
418      */
419
420     function taggedCount($recount=false)
421     {
422         $keypart = sprintf('profile_list:tagged_count:%d:%s', 
423                            $this->tagger,
424                            $this->tag);
425
426         $count = self::cacheGet($keypart);
427
428         if ($count === false) {
429             $tags = new Profile_tag();
430
431             $tags->tag = $this->tag;
432             $tags->tagger = $this->tagger;
433
434             $count = $tags->count('distinct tagged');
435
436             self::cacheSet($keypart, $count);
437         }
438
439         return $count;
440     }
441
442     /**
443      * get the cached number of profiles subscribed to this
444      * people tag, re-count if the argument is true.
445      *
446      * @param boolean $recount  whether to ignore cache
447      *
448      * @return integer count
449      */
450
451     function subscriberCount($recount=false)
452     {
453         $keypart = sprintf('profile_list:subscriber_count:%d', 
454                            $this->id);
455
456         $count = self::cacheGet($keypart);
457
458         if ($count === false) {
459
460             $sub = new Profile_tag_subscription();
461             $sub->profile_tag_id = $this->id;
462             $count = (int) $sub->count('distinct profile_id');
463
464             self::cacheSet($keypart, $count);
465         }
466
467         return $count;
468     }
469
470     /**
471      * get the cached number of profiles subscribed to this
472      * people tag, re-count if the argument is true.
473      *
474      * @param boolean $recount  whether to ignore cache
475      *
476      * @return integer count
477      */
478
479     function blowNoticeStreamCache($all=false)
480     {
481         self::blow('profile_list:notice_ids:%d', $this->id);
482         if ($all) {
483             self::blow('profile_list:notice_ids:%d;last', $this->id);
484         }
485     }
486
487     /**
488      * get the Profile_list object by the
489      * given tagger and with given tag
490      *
491      * @param integer $tagger   the id of the creator profile
492      * @param integer $tag      the tag
493      *
494      * @return integer count
495      */
496
497     static function getByTaggerAndTag($tagger, $tag)
498     {
499         $ptag = Profile_list::pkeyGet(array('tagger' => $tagger, 'tag' => $tag));
500         return $ptag;
501     }
502
503     /**
504      * create a profile_list record for a tag, tagger pair
505      * if it doesn't exist, return it.
506      *
507      * @param integer $tagger   the tagger
508      * @param string  $tag      the tag
509      * @param string  $description description
510      * @param boolean $private  protected or not
511      *
512      * @return Profile_list the people tag object
513      */
514
515     static function ensureTag($tagger, $tag, $description=null, $private=false)
516     {
517         $ptag = Profile_list::getByTaggerAndTag($tagger, $tag);
518
519         if(empty($ptag->id)) {
520             $args = array(
521                 'tag' => $tag,
522                 'tagger' => $tagger,
523                 'description' => $description,
524                 'private' => $private
525             );
526
527             $new_tag = Profile_list::saveNew($args);
528
529             return $new_tag;
530         }
531         return $ptag;
532     }
533
534     /**
535      * get the maximum number of characters
536      * that can be used in the description of
537      * a people tag.
538      *
539      * determined by $config['peopletag']['desclimit']
540      * if not set, falls back to $config['site']['textlimit']
541      *
542      * @return integer maximum number of characters
543      */
544
545     static function maxDescription()
546     {
547         $desclimit = common_config('peopletag', 'desclimit');
548         // null => use global limit (distinct from 0!)
549         if (is_null($desclimit)) {
550             $desclimit = common_config('site', 'textlimit');
551         }
552         return $desclimit;
553     }
554
555     /**
556      * check if the length of given text exceeds
557      * character limit.
558      *
559      * @param string $desc  the description
560      *
561      * @return boolean is the descripition too long?
562      */
563
564     static function descriptionTooLong($desc)
565     {
566         $desclimit = self::maxDescription();
567         return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
568     }
569
570     /**
571      * save a new people tag, this should be always used
572      * since it makes uri, homeurl, created and modified
573      * timestamps and performs checks.
574      *
575      * @param array $fields an array with fields and their values
576      *
577      * @return mixed Profile_list on success, false on fail
578      */
579     static function saveNew(array $fields) {
580         extract($fields);
581
582         $ptag = new Profile_list();
583
584         $ptag->query('BEGIN');
585
586         if (empty($tagger)) {
587             // TRANS: Server exception saving new tag without having a tagger specified.
588             throw new Exception(_('No tagger specified.'));
589         }
590
591         if (empty($tag)) {
592             // TRANS: Server exception saving new tag without having a tag specified.
593             throw new Exception(_('No tag specified.'));
594         }
595
596         if (empty($mainpage)) {
597             $mainpage = null;
598         }
599
600         if (empty($uri)) {
601             // fill in later...
602             $uri = null;
603         }
604
605         if (empty($mainpage)) {
606             $mainpage = null;
607         }
608
609         if (empty($description)) {
610             $description = null;
611         }
612
613         if (empty($private)) {
614             $private = false;
615         }
616
617         $ptag->tagger      = $tagger;
618         $ptag->tag         = $tag;
619         $ptag->description = $description;
620         $ptag->private     = $private;
621         $ptag->uri         = $uri;
622         $ptag->mainpage    = $mainpage;
623         $ptag->created     = common_sql_now();
624         $ptag->modified    = common_sql_now();
625
626         $result = $ptag->insert();
627
628         if (!$result) {
629             common_log_db_error($ptag, 'INSERT', __FILE__);
630             // TRANS: Server exception saving new tag.
631             throw new ServerException(_('Could not create profile tag.'));
632         }
633
634         if (!isset($uri) || empty($uri)) {
635             $orig = clone($ptag);
636             $ptag->uri = common_local_url('profiletagbyid', array('id' => $ptag->id, 'tagger_id' => $ptag->tagger));
637             $result = $ptag->update($orig);
638             if (!$result) {
639                 common_log_db_error($ptag, 'UPDATE', __FILE__);
640             // TRANS: Server exception saving new tag.
641                 throw new ServerException(_('Could not set profile tag URI.'));
642             }
643         }
644
645         if (!isset($mainpage) || empty($mainpage)) {
646             $orig = clone($ptag);
647             $user = User::getKV('id', $ptag->tagger);
648             if(!empty($user)) {
649                 $ptag->mainpage = common_local_url('showprofiletag', array('tag' => $ptag->tag, 'nickname' => $user->getNickname()));
650             } else {
651                 $ptag->mainpage = $uri; // assume this is a remote peopletag and the uri works
652             }
653
654             $result = $ptag->update($orig);
655             if (!$result) {
656                 common_log_db_error($ptag, 'UPDATE', __FILE__);
657                 // TRANS: Server exception saving new tag.
658                 throw new ServerException(_('Could not set profile tag mainpage.'));
659             }
660         }
661         return $ptag;
662     }
663
664     /**
665      * get all items at given cursor position for api
666      *
667      * @param callback $fn  a function that takes the following arguments in order:
668      *                      $offset, $limit, $since_id, $max_id
669      *                      and returns a Profile_list object after making the DB query
670      * @param array $args   arguments required for $fn
671      * @param integer $cursor   the cursor
672      * @param integer $count    max. number of results
673      *
674      * Algorithm:
675      * - if cursor is 0, return empty list
676      * - if cursor is -1, get first 21 items, next_cursor = 20th prev_cursor = 0
677      * - if cursor is +ve get 22 consecutive items before starting at cursor
678      *   - return items[1..20] if items[0] == cursor else return items[0..21]
679      *   - prev_cursor = items[1]
680      *   - next_cursor = id of the last item being returned
681      *
682      * - if cursor is -ve get 22 consecutive items after cursor starting at cursor
683      *   - return items[1..20]
684      *
685      * @returns array (array (mixed items), int next_cursor, int previous_cursor)
686      */
687
688      // XXX: This should be in Memcached_DataObject... eventually.
689
690     static function getAtCursor($fn, array $args, $cursor, $count=20)
691     {
692         $items = array();
693
694         $since_id = 0;
695         $max_id = 0;
696         $next_cursor = 0;
697         $prev_cursor = 0;
698
699         if($cursor > 0) {
700             // if cursor is +ve fetch $count+2 items before cursor starting at cursor
701             $max_id = $cursor;
702             $fn_args = array_merge($args, array(0, $count+2, 0, $max_id));
703             $list = call_user_func_array($fn, $fn_args);
704             while($list->fetch()) {
705                 $items[] = clone($list);
706             }
707
708             if ((isset($items[0]->cursor) && $items[0]->cursor == $cursor) ||
709                 $items[0]->id == $cursor) {
710                 array_shift($items);
711                 $prev_cursor = isset($items[0]->cursor) ?
712                     -$items[0]->cursor : -$items[0]->id;
713             } else {
714                 if (count($items) > $count+1) {
715                     array_shift($items);
716                 }
717                 // this means the cursor item has been deleted, check to see if there are more
718                 $fn_args = array_merge($args, array(0, 1, $cursor));
719                 $more = call_user_func($fn, $fn_args);
720                 if (!$more->fetch() || empty($more)) {
721                     // no more items.
722                     $prev_cursor = 0;
723                 } else {
724                     $prev_cursor = isset($items[0]->cursor) ?
725                         -$items[0]->cursor : -$items[0]->id;
726                 }
727             }
728
729             if (count($items)==$count+1) {
730                 // this means there is a next page.
731                 $next = array_pop($items);
732                 $next_cursor = isset($next->cursor) ?
733                     $items[$count-1]->cursor : $items[$count-1]->id;
734             }
735
736         } else if($cursor < -1) {
737             // if cursor is -ve fetch $count+2 items created after -$cursor-1
738             $cursor = abs($cursor);
739             $since_id = $cursor-1;
740
741             $fn_args = array_merge($args, array(0, $count+2, $since_id));
742             $list = call_user_func_array($fn, $fn_args);
743             while($list->fetch()) {
744                 $items[] = clone($list);
745             }
746
747             $end = count($items)-1;
748             if ((isset($items[$end]->cursor) && $items[$end]->cursor == $cursor) ||
749                 $items[$end]->id == $cursor) {
750                 array_pop($items);
751                 $next_cursor = isset($items[$end-1]->cursor) ?
752                     $items[$end-1]->cursor : $items[$end-1]->id;
753             } else {
754                 $next_cursor = isset($items[$end]->cursor) ?
755                     $items[$end]->cursor : $items[$end]->id;
756                 if ($end > $count) array_pop($items); // excess item.
757
758                 // check if there are more items for next page
759                 $fn_args = array_merge($args, array(0, 1, 0, $cursor));
760                 $more = call_user_func_array($fn, $fn_args);
761                 if (!$more->fetch() || empty($more)) {
762                     $next_cursor = 0;
763                 }
764             }
765
766             if (count($items) == $count+1) {
767                 // this means there is a previous page.
768                 $prev = array_shift($items);
769                 $prev_cursor = isset($prev->cursor) ?
770                     -$items[0]->cursor : -$items[0]->id;
771             }
772         } else if($cursor == -1) {
773             $fn_args = array_merge($args, array(0, $count+1));
774             $list = call_user_func_array($fn, $fn_args);
775
776             while($list->fetch()) {
777                 $items[] = clone($list);
778             }
779
780             if (count($items)==$count+1) {
781                 $next = array_pop($items);
782                 if(isset($next->cursor)) {
783                     $next_cursor = $items[$count-1]->cursor;
784                 } else {
785                     $next_cursor = $items[$count-1]->id;
786                 }
787             }
788
789         }
790         return array($items, $next_cursor, $prev_cursor);
791     }
792
793     /**
794      * save a collection of people tags into the cache
795      *
796      * @param string $ckey  cache key
797      * @param Profile_list &$tag the results to store
798      * @param integer $offset   offset for slicing results
799      * @param integer $limit    maximum number of results
800      *
801      * @return boolean success
802      */
803
804     static function setCache($ckey, &$tag, $offset=0, $limit=null) {
805         $cache = Cache::instance();
806         if (empty($cache)) {
807             return false;
808         }
809         $str = '';
810         $tags = array();
811         while ($tag->fetch()) {
812             $str .= $tag->tagger . ':' . $tag->tag . ';';
813             $tags[] = clone($tag);
814         }
815         $str = substr($str, 0, -1);
816         if ($offset>=0 && !is_null($limit)) {
817             $tags = array_slice($tags, $offset, $limit);
818         }
819
820         $tag = new ArrayWrapper($tags);
821
822         return self::cacheSet($ckey, $str);
823     }
824
825     /**
826      * get people tags from the cache
827      *
828      * @param string $ckey  cache key
829      * @param integer $offset   offset for slicing
830      * @param integer $limit    limit
831      *
832      * @return Profile_list results
833      */
834
835     static function getCached($ckey, $offset=0, $limit=null) {
836
837         $keys_str = self::cacheGet($ckey);
838         if ($keys_str === false) {
839             return false;
840         }
841
842         $pairs = explode(';', $keys_str);
843         $keys = array();
844         foreach ($pairs as $pair) {
845             $keys[] = explode(':', $pair);
846         }
847
848         if ($offset>=0 && !is_null($limit)) {
849             $keys = array_slice($keys, $offset, $limit);
850         }
851         return self::getByKeys($keys);
852     }
853
854     /**
855      * get Profile_list objects from the database
856      * given their (tag, tagger) key pairs.
857      *
858      * @param array $keys   array of array(tagger, tag)
859      *
860      * @return Profile_list results
861      */
862
863     static function getByKeys(array $keys) {
864         $cache = Cache::instance();
865
866         if (!empty($cache)) {
867             $tags = array();
868
869             foreach ($keys as $key) {
870                 $t = Profile_list::getByTaggerAndTag($key[0], $key[1]);
871                 if (!empty($t)) {
872                     $tags[] = $t;
873                 }
874             }
875             return new ArrayWrapper($tags);
876         } else {
877             $tag = new Profile_list();
878             if (empty($keys)) {
879                 //if no IDs requested, just return the tag object
880                 return $tag;
881             }
882
883             $pairs = array();
884             foreach ($keys as $key) {
885                 $pairs[] = '(' . $key[0] . ', "' . $key[1] . '")';
886             }
887
888             $tag->whereAdd('(tagger, tag) in (' . implode(', ', $pairs) . ')');
889
890             $tag->find();
891
892             $temp = array();
893
894             while ($tag->fetch()) {
895                 $temp[$tag->tagger.'-'.$tag->tag] = clone($tag);
896             }
897
898             $wrapped = array();
899
900             foreach ($keys as $key) {
901                 $id = $key[0].'-'.$key[1];
902                 if (array_key_exists($id, $temp)) {
903                     $wrapped[] = $temp[$id];
904                 }
905             }
906
907             return new ArrayWrapper($wrapped);
908         }
909     }
910
911     function insert()
912     {
913         $result = parent::insert();
914         if ($result) {
915             self::blow('profile:lists:%d', $this->tagger);
916         }
917         return $result;
918     }
919 }