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