3 * StatusNet - the distributed open-source microblogging tool
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.
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.
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/>.
20 * @author Shashi Gowda <connect2shashi@gmail.com>
21 * @license GNU Affero General Public License http://www.gnu.org/licenses/
24 if (!defined('STATUSNET') && !defined('LACONICA')) {
29 * Table Definition for profile_list
31 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
33 class Profile_list extends Memcached_DataObject
36 /* the code below is auto generated do not remove the above tag */
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
52 function staticGet($k,$v=NULL) { return DB_DataObject::staticGet('Profile_list',$k,$v); }
54 /* the code above is auto generated do not remove the tag below */
58 * return a profile_list record, given its tag and tagger.
60 * @param array $kv ideally array('tag' => $tag, 'tagger' => $tagger)
62 * @return Profile_list a Profile_list object with the given tag and tagger.
67 return Memcached_DataObject::pkeyGet('Profile_list', $kv);
71 * get the tagger of this profile_list object
73 * @return Profile the tagger
78 return Profile::staticGet('id', $this->tagger);
82 * return a string to identify this
83 * profile_list in the user interface etc.
88 function getBestName()
94 * return a uri string for this profile_list
102 if (Event::handle('StartProfiletagGetUri', array($this, &$uri))) {
103 if (!empty($this->uri)) {
106 $uri = common_local_url('profiletagbyid',
107 array('id' => $this->id, 'tagger_id' => $this->tagger));
110 Event::handle('EndProfiletagGetUri', array($this, &$uri));
115 * return a url to the homepage of this item
117 * @return String home url
123 if (Event::handle('StartUserPeopletagHomeUrl', array($this, &$url))) {
124 // normally stored in mainpage, but older ones may be null
125 if (!empty($this->mainpage)) {
126 $url = $this->mainpage;
128 $url = common_local_url('showprofiletag',
129 array('tagger' => $this->getTagger()->nickname,
130 'tag' => $this->tag));
133 Event::handle('EndUserPeopletagHomeUrl', array($this, &$url));
138 * return an immutable url for this object
140 * @return String permalink
146 if (Event::handle('StartProfiletagPermalink', array($this, &$url))) {
147 $url = common_local_url('profiletagbyid',
148 array('id' => $this->id));
150 Event::handle('EndProfiletagPermalink', array($this, &$url));
155 * Query notices by users associated with this tag,
156 * but first check the cache before hitting the DB.
158 * @param integer $offset offset
159 * @param integer $limit maximum no of results
160 * @param integer $since_id=null since this id
161 * @param integer $max_id=null maximum id in result
163 * @return Notice the query
166 function getNotices($offset, $limit, $since_id=null, $max_id=null)
168 $stream = new PeopletagNoticeStream($this);
170 return $stream->getNotices($offset, $limit, $since_id, $max_id);
174 * Get subscribers (local and remote) to this people tag
175 * Order by reverse chronology
177 * @param integer $offset offset
178 * @param integer $limit maximum no of results
179 * @param integer $since_id=null since unix timestamp
180 * @param integer $upto=null maximum unix timestamp when subscription was made
182 * @return Profile results
185 function getSubscribers($offset=0, $limit=null, $since=0, $upto=0)
187 $subs = new Profile();
188 $sub = new Profile_tag_subscription();
189 $sub->profile_tag_id = $this->id;
191 $subs->joinAdd($sub);
192 $subs->selectAdd('unix_timestamp(profile_tag_subscription.' .
193 'created) as "cursor"');
196 $subs->whereAdd('cursor > ' . $since);
200 $subs->whereAdd('cursor <= ' . $upto);
203 if ($limit != null) {
204 $subs->limit($offset, $limit);
207 $subs->orderBy('profile_tag_subscription.created DESC');
214 * Get all and only local subscribers to this people tag
215 * used for distributing notices to user inboxes.
217 * @return array ids of users
220 function getUserSubscribers()
225 if(common_config('db','quote_identifiers'))
226 $user_table = '"user"';
227 else $user_table = 'user';
231 'FROM '. $user_table .' JOIN profile_tag_subscription '.
232 'ON '. $user_table .'.id = profile_tag_subscription.profile_id ' .
233 'WHERE profile_tag_subscription.profile_tag_id = %d ';
235 $user->query(sprintf($qry, $this->id));
239 while ($user->fetch()) {
249 * Check to see if a given profile has
250 * subscribed to this people tag's timeline
252 * @param mixed $id User or Profile object or integer id
254 * @return boolean subscription status
257 function hasSubscriber($id)
259 if (!is_numeric($id)) {
263 $sub = Profile_tag_subscription::pkeyGet(array('profile_tag_id' => $this->id,
264 'profile_id' => $id));
269 * Get profiles tagged with this people tag,
270 * include modified timestamp as a "cursor" field
271 * order by descending order of modified time
273 * @param integer $offset offset
274 * @param integer $limit maximum no of results
275 * @param integer $since_id=null since unix timestamp
276 * @param integer $upto=null maximum unix timestamp when subscription was made
278 * @return Profile results
281 function getTagged($offset=0, $limit=null, $since=0, $upto=0)
283 $tagged = new Profile();
284 $tagged->joinAdd(array('id', 'profile_tag:tagged'));
287 $tagged->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
288 $tagged->whereAdd('profile_tag.tagger = '.$this->tagger);
289 $tagged->whereAdd("profile_tag.tag = '{$this->tag}'");
292 $tagged->whereAdd('cursor > ' . $since);
296 $tagged->whereAdd('cursor <= ' . $upto);
299 if ($limit != null) {
300 $tagged->limit($offset, $limit);
303 $tagged->orderBy('profile_tag.modified DESC');
310 * Gracefully delete one or many people tags
311 * along with their members and subscriptions data
313 * @return boolean success
318 // force delete one item at a time.
319 if (empty($this->id)) {
321 while ($this->fetch()) {
326 Profile_tag::cleanup($this);
327 Profile_tag_subscription::cleanup($this);
329 return parent::delete();
333 * Update a people tag gracefully
334 * also change "tag" fields in profile_tag table
336 * @param Profile_list $orig Object's original form
338 * @return boolean success
341 function update($orig=null)
345 if (!is_object($orig) && !$orig instanceof Profile_list) {
346 parent::update($orig);
349 // if original tag was different
350 // check to see if the new tag already exists
351 // if not, rename the tag correctly
352 if($orig->tag != $this->tag || $orig->tagger != $this->tagger) {
353 $existing = Profile_list::getByTaggerAndTag($this->tagger, $this->tag);
354 if(!empty($existing)) {
355 // TRANS: Server exception.
356 throw new ServerException(_('The tag you are trying to rename ' .
357 'to already exists.'));
360 // XXX: allow OStatus plugin to send out profile tag
361 $result = Profile_tag::moveTag($orig, $this);
363 parent::update($orig);
368 * return an xml string representing this people tag
369 * as the author of an atom feed
371 * @return string atom author element
374 function asAtomAuthor()
376 $xs = new XMLStringer(true);
378 $tagger = $this->getTagger();
379 $xs->elementStart('author');
380 $xs->element('name', null, '@' . $tagger->nickname . '/' . $this->tag);
381 $xs->element('uri', null, $this->permalink());
382 $xs->elementEnd('author');
384 return $xs->getString();
388 * return an xml string to represent this people tag
389 * as the subject of an activitystreams feed.
391 * @return string activitystreams subject
394 function asActivitySubject()
396 return $this->asActivityNoun('subject');
400 * return an xml string to represent this people tag
401 * as a noun in an activitystreams feed.
403 * @param string $element the xml tag
405 * @return string activitystreams noun
408 function asActivityNoun($element)
410 $noun = ActivityObject::fromPeopletag($this);
411 return $noun->asString('activity:' . $element);
415 * get the cached number of profiles tagged with this
416 * people tag, re-count if the argument is true.
418 * @param boolean $recount whether to ignore cache
420 * @return integer count
423 function taggedCount($recount=false)
425 $keypart = sprintf('profile_list:tagged_count:%d:%s',
429 $count = self::cacheGet($keypart);
431 if ($count === false) {
432 $tags = new Profile_tag();
434 $tags->tag = $this->tag;
435 $tags->tagger = $this->tagger;
437 $count = $tags->count('distinct tagged');
439 self::cacheSet($keypart, $count);
446 * get the cached number of profiles subscribed to this
447 * people tag, re-count if the argument is true.
449 * @param boolean $recount whether to ignore cache
451 * @return integer count
454 function subscriberCount($recount=false)
456 $keypart = sprintf('profile_list:subscriber_count:%d',
459 $count = self::cacheGet($keypart);
461 if ($count === false) {
463 $sub = new Profile_tag_subscription();
464 $sub->profile_tag_id = $this->id;
465 $count = (int) $sub->count('distinct profile_id');
467 self::cacheSet($keypart, $count);
474 * get the cached number of profiles subscribed to this
475 * people tag, re-count if the argument is true.
477 * @param boolean $recount whether to ignore cache
479 * @return integer count
482 function blowNoticeStreamCache($all=false)
484 self::blow('profile_list:notice_ids:%d', $this->id);
486 self::blow('profile_list:notice_ids:%d;last', $this->id);
491 * get the Profile_list object by the
492 * given tagger and with given tag
494 * @param integer $tagger the id of the creator profile
495 * @param integer $tag the tag
497 * @return integer count
500 static function getByTaggerAndTag($tagger, $tag)
502 $ptag = Profile_list::pkeyGet(array('tagger' => $tagger, 'tag' => $tag));
507 * create a profile_list record for a tag, tagger pair
508 * if it doesn't exist, return it.
510 * @param integer $tagger the tagger
511 * @param string $tag the tag
512 * @param string $description description
513 * @param boolean $private protected or not
515 * @return Profile_list the people tag object
518 static function ensureTag($tagger, $tag, $description=null, $private=false)
520 $ptag = Profile_list::getByTaggerAndTag($tagger, $tag);
522 if(empty($ptag->id)) {
526 'description' => $description,
527 'private' => $private
530 $new_tag = Profile_list::saveNew($args);
538 * get the maximum number of characters
539 * that can be used in the description of
542 * determined by $config['peopletag']['desclimit']
543 * if not set, falls back to $config['site']['textlimit']
545 * @return integer maximum number of characters
548 static function maxDescription()
550 $desclimit = common_config('peopletag', 'desclimit');
551 // null => use global limit (distinct from 0!)
552 if (is_null($desclimit)) {
553 $desclimit = common_config('site', 'textlimit');
559 * check if the length of given text exceeds
562 * @param string $desc the description
564 * @return boolean is the descripition too long?
567 static function descriptionTooLong($desc)
569 $desclimit = self::maxDescription();
570 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
574 * save a new people tag, this should be always used
575 * since it makes uri, homeurl, created and modified
576 * timestamps and performs checks.
578 * @param array $fields an array with fields and their values
580 * @return mixed Profile_list on success, false on fail
582 static function saveNew($fields) {
585 $ptag = new Profile_list();
587 $ptag->query('BEGIN');
589 if (empty($tagger)) {
590 // TRANS: Server exception saving new tag without having a tagger specified.
591 throw new Exception(_('No tagger specified.'));
595 // TRANS: Server exception saving new tag without having a tag specified.
596 throw new Exception(_('No tag specified.'));
599 if (empty($mainpage)) {
608 if (empty($mainpage)) {
612 if (empty($description)) {
616 if (empty($private)) {
620 $ptag->tagger = $tagger;
622 $ptag->description = $description;
623 $ptag->private = $private;
625 $ptag->mainpage = $mainpage;
626 $ptag->created = common_sql_now();
627 $ptag->modified = common_sql_now();
629 $result = $ptag->insert();
632 common_log_db_error($ptag, 'INSERT', __FILE__);
633 // TRANS: Server exception saving new tag.
634 throw new ServerException(_('Could not create profile tag.'));
637 if (!isset($uri) || empty($uri)) {
638 $orig = clone($ptag);
639 $ptag->uri = common_local_url('profiletagbyid', array('id' => $ptag->id, 'tagger_id' => $ptag->tagger));
640 $result = $ptag->update($orig);
642 common_log_db_error($ptag, 'UPDATE', __FILE__);
643 // TRANS: Server exception saving new tag.
644 throw new ServerException(_('Could not set profile tag URI.'));
648 if (!isset($mainpage) || empty($mainpage)) {
649 $orig = clone($ptag);
650 $user = User::staticGet('id', $ptag->tagger);
652 $ptag->mainpage = common_local_url('showprofiletag', array('tag' => $ptag->tag, 'tagger' => $user->nickname));
654 $ptag->mainpage = $uri; // assume this is a remote peopletag and the uri works
657 $result = $ptag->update($orig);
659 common_log_db_error($ptag, 'UPDATE', __FILE__);
660 // TRANS: Server exception saving new tag.
661 throw new ServerException(_('Could not set profile tag mainpage.'));
668 * get all items at given cursor position for api
670 * @param callback $fn a function that takes the following arguments in order:
671 * $offset, $limit, $since_id, $max_id
672 * and returns a Profile_list object after making the DB query
673 * @param array $args arguments required for $fn
674 * @param integer $cursor the cursor
675 * @param integer $count max. number of results
678 * - if cursor is 0, return empty list
679 * - if cursor is -1, get first 21 items, next_cursor = 20th prev_cursor = 0
680 * - if cursor is +ve get 22 consecutive items before starting at cursor
681 * - return items[1..20] if items[0] == cursor else return items[0..21]
682 * - prev_cursor = items[1]
683 * - next_cursor = id of the last item being returned
685 * - if cursor is -ve get 22 consecutive items after cursor starting at cursor
686 * - return items[1..20]
688 * @returns array (array (mixed items), int next_cursor, int previous_cursor)
691 // XXX: This should be in Memcached_DataObject... eventually.
693 static function getAtCursor($fn, $args, $cursor, $count=20)
703 // if cursor is +ve fetch $count+2 items before cursor starting at cursor
705 $fn_args = array_merge($args, array(0, $count+2, 0, $max_id));
706 $list = call_user_func_array($fn, $fn_args);
707 while($list->fetch()) {
708 $items[] = clone($list);
711 if ((isset($items[0]->cursor) && $items[0]->cursor == $cursor) ||
712 $items[0]->id == $cursor) {
714 $prev_cursor = isset($items[0]->cursor) ?
715 -$items[0]->cursor : -$items[0]->id;
717 if (count($items) > $count+1) {
720 // this means the cursor item has been deleted, check to see if there are more
721 $fn_args = array_merge($args, array(0, 1, $cursor));
722 $more = call_user_func($fn, $fn_args);
723 if (!$more->fetch() || empty($more)) {
727 $prev_cursor = isset($items[0]->cursor) ?
728 -$items[0]->cursor : -$items[0]->id;
732 if (count($items)==$count+1) {
733 // this means there is a next page.
734 $next = array_pop($items);
735 $next_cursor = isset($next->cursor) ?
736 $items[$count-1]->cursor : $items[$count-1]->id;
739 } else if($cursor < -1) {
740 // if cursor is -ve fetch $count+2 items created after -$cursor-1
741 $cursor = abs($cursor);
742 $since_id = $cursor-1;
744 $fn_args = array_merge($args, array(0, $count+2, $since_id));
745 $list = call_user_func_array($fn, $fn_args);
746 while($list->fetch()) {
747 $items[] = clone($list);
750 $end = count($items)-1;
751 if ((isset($items[$end]->cursor) && $items[$end]->cursor == $cursor) ||
752 $items[$end]->id == $cursor) {
754 $next_cursor = isset($items[$end-1]->cursor) ?
755 $items[$end-1]->cursor : $items[$end-1]->id;
757 $next_cursor = isset($items[$end]->cursor) ?
758 $items[$end]->cursor : $items[$end]->id;
759 if ($end > $count) array_pop($items); // excess item.
761 // check if there are more items for next page
762 $fn_args = array_merge($args, array(0, 1, 0, $cursor));
763 $more = call_user_func_array($fn, $fn_args);
764 if (!$more->fetch() || empty($more)) {
769 if (count($items) == $count+1) {
770 // this means there is a previous page.
771 $prev = array_shift($items);
772 $prev_cursor = isset($prev->cursor) ?
773 -$items[0]->cursor : -$items[0]->id;
775 } else if($cursor == -1) {
776 $fn_args = array_merge($args, array(0, $count+1));
777 $list = call_user_func_array($fn, $fn_args);
779 while($list->fetch()) {
780 $items[] = clone($list);
783 if (count($items)==$count+1) {
784 $next = array_pop($items);
785 if(isset($next->cursor)) {
786 $next_cursor = $items[$count-1]->cursor;
788 $next_cursor = $items[$count-1]->id;
793 return array($items, $next_cursor, $prev_cursor);
797 * save a collection of people tags into the cache
799 * @param string $ckey cache key
800 * @param Profile_list &$tag the results to store
801 * @param integer $offset offset for slicing results
802 * @param integer $limit maximum number of results
804 * @return boolean success
807 static function setCache($ckey, &$tag, $offset=0, $limit=null) {
808 $cache = Cache::instance();
814 while ($tag->fetch()) {
815 $str .= $tag->tagger . ':' . $tag->tag . ';';
816 $tags[] = clone($tag);
818 $str = substr($str, 0, -1);
819 if ($offset>=0 && !is_null($limit)) {
820 $tags = array_slice($tags, $offset, $limit);
823 $tag = new ArrayWrapper($tags);
825 return self::cacheSet($ckey, $str);
829 * get people tags from the cache
831 * @param string $ckey cache key
832 * @param integer $offset offset for slicing
833 * @param integer $limit limit
835 * @return Profile_list results
838 static function getCached($ckey, $offset=0, $limit=null) {
840 $keys_str = self::cacheGet($ckey);
841 if ($keys_str === false) {
845 $pairs = explode(';', $keys_str);
847 foreach ($pairs as $pair) {
848 $keys[] = explode(':', $pair);
851 if ($offset>=0 && !is_null($limit)) {
852 $keys = array_slice($keys, $offset, $limit);
854 return self::getByKeys($keys);
858 * get Profile_list objects from the database
859 * given their (tag, tagger) key pairs.
861 * @param array $keys array of array(tagger, tag)
863 * @return Profile_list results
866 static function getByKeys($keys) {
867 $cache = Cache::instance();
869 if (!empty($cache)) {
872 foreach ($keys as $key) {
873 $t = Profile_list::getByTaggerAndTag($key[0], $key[1]);
878 return new ArrayWrapper($tags);
880 $tag = new Profile_list();
882 //if no IDs requested, just return the tag object
887 foreach ($keys as $key) {
888 $pairs[] = '(' . $key[0] . ', "' . $key[1] . '")';
891 $tag->whereAdd('(tagger, tag) in (' . implode(', ', $pairs) . ')');
897 while ($tag->fetch()) {
898 $temp[$tag->tagger.'-'.$tag->tag] = clone($tag);
903 foreach ($keys as $key) {
904 $id = $key[0].'-'.$key[1];
905 if (array_key_exists($id, $temp)) {
906 $wrapped[] = $temp[$id];
910 return new ArrayWrapper($wrapped);