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('GNUSOCIAL')) { exit(1); }
26 class Profile_list extends Managed_DataObject
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
41 public static function schemaDef()
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'),
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'),
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'),
59 'primary key' => array('tagger', 'tag'),
60 'unique keys' => array(
61 'profile_list_id_key' => array('id')
63 'foreign keys' => array(
64 'profile_list_tagger_fkey' => array('profile', array('tagger' => 'id')),
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'),
77 * get the tagger of this profile_list object
79 * @return Profile the tagger
84 return Profile::getByID($this->tagger);
88 * return a string to identify this
89 * profile_list in the user interface etc.
94 function getBestName()
100 * return a uri string for this profile_list
108 if (Event::handle('StartProfiletagGetUri', array($this, &$uri))) {
109 if (!empty($this->uri)) {
112 $uri = common_local_url('profiletagbyid',
113 array('id' => $this->id, 'tagger_id' => $this->tagger));
116 Event::handle('EndProfiletagGetUri', array($this, &$uri));
121 * return a url to the homepage of this item
123 * @return String home url
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;
134 $url = common_local_url('showprofiletag',
135 array('nickname' => $this->getTagger()->nickname,
136 'tag' => $this->tag));
139 Event::handle('EndUserPeopletagHomeUrl', array($this, &$url));
144 * return an immutable url for this object
146 * @return String permalink
152 if (Event::handle('StartProfiletagPermalink', array($this, &$url))) {
153 $url = common_local_url('profiletagbyid',
154 array('id' => $this->id));
156 Event::handle('EndProfiletagPermalink', array($this, &$url));
161 * Query notices by users associated with this tag,
162 * but first check the cache before hitting the DB.
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
169 * @return Notice the query
172 function getNotices($offset, $limit, $since_id=null, $max_id=null)
174 $stream = new PeopletagNoticeStream($this);
176 return $stream->getNotices($offset, $limit, $since_id, $max_id);
180 * Get subscribers (local and remote) to this people tag
181 * Order by reverse chronology
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
188 * @return Profile results
191 function getSubscribers($offset=0, $limit=null, $since=0, $upto=0)
193 $subs = new Profile();
196 array('id', 'profile_tag_subscription:profile_id')
198 $subs->whereAdd('profile_tag_subscription.profile_tag_id = ' . $this->id);
200 $subs->selectAdd('unix_timestamp(profile_tag_subscription.' .
201 'created) as "cursor"');
204 $subs->whereAdd('cursor > ' . $since);
208 $subs->whereAdd('cursor <= ' . $upto);
211 if ($limit != null) {
212 $subs->limit($offset, $limit);
215 $subs->orderBy('profile_tag_subscription.created DESC');
222 * Get all and only local subscribers to this people tag
223 * used for distributing notices to user inboxes.
225 * @return array ids of users
228 function getUserSubscribers()
233 if(common_config('db','quote_identifiers'))
234 $user_table = '"user"';
235 else $user_table = 'user';
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 ';
243 $user->query(sprintf($qry, $this->id));
247 while ($user->fetch()) {
257 * Check to see if a given profile has
258 * subscribed to this people tag's timeline
260 * @param mixed $id User or Profile object or integer id
262 * @return boolean subscription status
265 function hasSubscriber($id)
267 if (!is_numeric($id)) {
271 $sub = Profile_tag_subscription::pkeyGet(array('profile_tag_id' => $this->id,
272 'profile_id' => $id));
277 * Get profiles tagged with this people tag,
278 * include modified timestamp as a "cursor" field
279 * order by descending order of modified time
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
286 * @return Profile results
289 function getTagged($offset=0, $limit=null, $since=0, $upto=0)
291 $tagged = new Profile();
292 $tagged->joinAdd(array('id', 'profile_tag:tagged'));
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}'");
300 $tagged->whereAdd('cursor > ' . $since);
304 $tagged->whereAdd('cursor <= ' . $upto);
307 if ($limit != null) {
308 $tagged->limit($offset, $limit);
311 $tagged->orderBy('profile_tag.modified DESC');
318 * Gracefully delete one or many people tags
319 * along with their members and subscriptions data
321 * @return boolean success
324 function delete($useWhere=false)
326 // force delete one item at a time.
327 if (empty($this->id)) {
329 while ($this->fetch()) {
334 Profile_tag::cleanup($this);
335 Profile_tag_subscription::cleanup($this);
337 self::blow('profile:lists:%d', $this->tagger);
339 return parent::delete($useWhere);
343 * Update a people tag gracefully
344 * also change "tag" fields in profile_tag table
346 * @param Profile_list $dataObject Object's original form
348 * @return boolean success
351 function update($dataObject=false)
353 if (!is_object($dataObject) && !$dataObject instanceof Profile_list) {
354 return parent::update($dataObject);
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.'));
370 // XXX: allow OStatus plugin to send out profile tag
371 $result = Profile_tag::moveTag($dataObject, $this);
373 return parent::update($dataObject);
377 * return an xml string representing this people tag
378 * as the author of an atom feed
380 * @return string atom author element
383 function asAtomAuthor()
385 $xs = new XMLStringer(true);
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');
393 return $xs->getString();
397 * return an xml string to represent this people tag
398 * as a noun in an activitystreams feed.
400 * @param string $element the xml tag
402 * @return string activitystreams noun
405 function asActivityNoun($element)
407 $noun = ActivityObject::fromPeopletag($this);
408 return $noun->asString('activity:' . $element);
412 * get the cached number of profiles tagged with this
413 * people tag, re-count if the argument is true.
415 * @param boolean $recount whether to ignore cache
417 * @return integer count
420 function taggedCount($recount=false)
422 $keypart = sprintf('profile_list:tagged_count:%d:%s',
426 $count = self::cacheGet($keypart);
428 if ($count === false) {
429 $tags = new Profile_tag();
431 $tags->tag = $this->tag;
432 $tags->tagger = $this->tagger;
434 $count = $tags->count('distinct tagged');
436 self::cacheSet($keypart, $count);
443 * get the cached number of profiles subscribed to this
444 * people tag, re-count if the argument is true.
446 * @param boolean $recount whether to ignore cache
448 * @return integer count
451 function subscriberCount($recount=false)
453 $keypart = sprintf('profile_list:subscriber_count:%d',
456 $count = self::cacheGet($keypart);
458 if ($count === false) {
460 $sub = new Profile_tag_subscription();
461 $sub->profile_tag_id = $this->id;
462 $count = (int) $sub->count('distinct profile_id');
464 self::cacheSet($keypart, $count);
471 * get the cached number of profiles subscribed to this
472 * people tag, re-count if the argument is true.
474 * @param boolean $recount whether to ignore cache
476 * @return integer count
479 function blowNoticeStreamCache($all=false)
481 self::blow('profile_list:notice_ids:%d', $this->id);
483 self::blow('profile_list:notice_ids:%d;last', $this->id);
488 * get the Profile_list object by the
489 * given tagger and with given tag
491 * @param integer $tagger the id of the creator profile
492 * @param integer $tag the tag
494 * @return integer count
497 static function getByTaggerAndTag($tagger, $tag)
499 $ptag = Profile_list::pkeyGet(array('tagger' => $tagger, 'tag' => $tag));
504 * create a profile_list record for a tag, tagger pair
505 * if it doesn't exist, return it.
507 * @param integer $tagger the tagger
508 * @param string $tag the tag
509 * @param string $description description
510 * @param boolean $private protected or not
512 * @return Profile_list the people tag object
515 static function ensureTag($tagger, $tag, $description=null, $private=false)
517 $ptag = Profile_list::getByTaggerAndTag($tagger, $tag);
519 if(empty($ptag->id)) {
523 'description' => $description,
524 'private' => $private
527 $new_tag = Profile_list::saveNew($args);
535 * get the maximum number of characters
536 * that can be used in the description of
539 * determined by $config['peopletag']['desclimit']
540 * if not set, falls back to $config['site']['textlimit']
542 * @return integer maximum number of characters
545 static function maxDescription()
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');
556 * check if the length of given text exceeds
559 * @param string $desc the description
561 * @return boolean is the descripition too long?
564 static function descriptionTooLong($desc)
566 $desclimit = self::maxDescription();
567 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
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.
575 * @param array $fields an array with fields and their values
577 * @return mixed Profile_list on success, false on fail
579 static function saveNew(array $fields) {
582 $ptag = new Profile_list();
584 $ptag->query('BEGIN');
586 if (empty($tagger)) {
587 // TRANS: Server exception saving new tag without having a tagger specified.
588 throw new Exception(_('No tagger specified.'));
592 // TRANS: Server exception saving new tag without having a tag specified.
593 throw new Exception(_('No tag specified.'));
596 if (empty($mainpage)) {
605 if (empty($mainpage)) {
609 if (empty($description)) {
613 if (empty($private)) {
617 $ptag->tagger = $tagger;
619 $ptag->description = $description;
620 $ptag->private = $private;
622 $ptag->mainpage = $mainpage;
623 $ptag->created = common_sql_now();
624 $ptag->modified = common_sql_now();
626 $result = $ptag->insert();
629 common_log_db_error($ptag, 'INSERT', __FILE__);
630 // TRANS: Server exception saving new tag.
631 throw new ServerException(_('Could not create profile tag.'));
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);
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.'));
645 if (!isset($mainpage) || empty($mainpage)) {
646 $orig = clone($ptag);
647 $user = User::getKV('id', $ptag->tagger);
649 $ptag->mainpage = common_local_url('showprofiletag', array('tag' => $ptag->tag, 'nickname' => $user->getNickname()));
651 $ptag->mainpage = $uri; // assume this is a remote peopletag and the uri works
654 $result = $ptag->update($orig);
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.'));
665 * get all items at given cursor position for api
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
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
682 * - if cursor is -ve get 22 consecutive items after cursor starting at cursor
683 * - return items[1..20]
685 * @returns array (array (mixed items), int next_cursor, int previous_cursor)
688 // XXX: This should be in Memcached_DataObject... eventually.
690 static function getAtCursor($fn, array $args, $cursor, $count=20)
700 // if cursor is +ve fetch $count+2 items before cursor starting at 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);
708 if ((isset($items[0]->cursor) && $items[0]->cursor == $cursor) ||
709 $items[0]->id == $cursor) {
711 $prev_cursor = isset($items[0]->cursor) ?
712 -$items[0]->cursor : -$items[0]->id;
714 if (count($items) > $count+1) {
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)) {
724 $prev_cursor = isset($items[0]->cursor) ?
725 -$items[0]->cursor : -$items[0]->id;
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;
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;
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);
747 $end = count($items)-1;
748 if ((isset($items[$end]->cursor) && $items[$end]->cursor == $cursor) ||
749 $items[$end]->id == $cursor) {
751 $next_cursor = isset($items[$end-1]->cursor) ?
752 $items[$end-1]->cursor : $items[$end-1]->id;
754 $next_cursor = isset($items[$end]->cursor) ?
755 $items[$end]->cursor : $items[$end]->id;
756 if ($end > $count) array_pop($items); // excess item.
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)) {
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;
772 } else if($cursor == -1) {
773 $fn_args = array_merge($args, array(0, $count+1));
774 $list = call_user_func_array($fn, $fn_args);
776 while($list->fetch()) {
777 $items[] = clone($list);
780 if (count($items)==$count+1) {
781 $next = array_pop($items);
782 if(isset($next->cursor)) {
783 $next_cursor = $items[$count-1]->cursor;
785 $next_cursor = $items[$count-1]->id;
790 return array($items, $next_cursor, $prev_cursor);
794 * save a collection of people tags into the cache
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
801 * @return boolean success
804 static function setCache($ckey, &$tag, $offset=0, $limit=null) {
805 $cache = Cache::instance();
811 while ($tag->fetch()) {
812 $str .= $tag->tagger . ':' . $tag->tag . ';';
813 $tags[] = clone($tag);
815 $str = substr($str, 0, -1);
816 if ($offset>=0 && !is_null($limit)) {
817 $tags = array_slice($tags, $offset, $limit);
820 $tag = new ArrayWrapper($tags);
822 return self::cacheSet($ckey, $str);
826 * get people tags from the cache
828 * @param string $ckey cache key
829 * @param integer $offset offset for slicing
830 * @param integer $limit limit
832 * @return Profile_list results
835 static function getCached($ckey, $offset=0, $limit=null) {
837 $keys_str = self::cacheGet($ckey);
838 if ($keys_str === false) {
842 $pairs = explode(';', $keys_str);
844 foreach ($pairs as $pair) {
845 $keys[] = explode(':', $pair);
848 if ($offset>=0 && !is_null($limit)) {
849 $keys = array_slice($keys, $offset, $limit);
851 return self::getByKeys($keys);
855 * get Profile_list objects from the database
856 * given their (tag, tagger) key pairs.
858 * @param array $keys array of array(tagger, tag)
860 * @return Profile_list results
863 static function getByKeys(array $keys) {
864 $cache = Cache::instance();
866 if (!empty($cache)) {
869 foreach ($keys as $key) {
870 $t = Profile_list::getByTaggerAndTag($key[0], $key[1]);
875 return new ArrayWrapper($tags);
877 $tag = new Profile_list();
879 //if no IDs requested, just return the tag object
884 foreach ($keys as $key) {
885 $pairs[] = '(' . $key[0] . ', "' . $key[1] . '")';
888 $tag->whereAdd('(tagger, tag) in (' . implode(', ', $pairs) . ')');
894 while ($tag->fetch()) {
895 $temp[$tag->tagger.'-'.$tag->tag] = clone($tag);
900 foreach ($keys as $key) {
901 $id = $key[0].'-'.$key[1];
902 if (array_key_exists($id, $temp)) {
903 $wrapped[] = $temp[$id];
907 return new ArrayWrapper($wrapped);
913 $result = parent::insert();
915 self::blow('profile:lists:%d', $this->tagger);