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 Managed_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 Memcached_DataObject::staticGet('Profile_list',$k,$v); }
54 /* the code above is auto generated do not remove the tag below */
57 public static function schemaDef()
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'),
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'),
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'),
75 'primary key' => array('tagger', 'tag'),
76 'unique keys' => array(
77 'profile_list_id_key' => array('id')
79 'foreign keys' => array(
80 'profile_list_tagger_fkey' => array('profile', array('tagger' => 'id')),
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'),
93 * return a profile_list record, given its tag and tagger.
95 * @param array $kv ideally array('tag' => $tag, 'tagger' => $tagger)
97 * @return Profile_list a Profile_list object with the given tag and tagger.
100 function pkeyGet($kv)
102 return Memcached_DataObject::pkeyGet('Profile_list', $kv);
106 * get the tagger of this profile_list object
108 * @return Profile the tagger
113 return Profile::staticGet('id', $this->tagger);
117 * return a string to identify this
118 * profile_list in the user interface etc.
123 function getBestName()
129 * return a uri string for this profile_list
137 if (Event::handle('StartProfiletagGetUri', array($this, &$uri))) {
138 if (!empty($this->uri)) {
141 $uri = common_local_url('profiletagbyid',
142 array('id' => $this->id, 'tagger_id' => $this->tagger));
145 Event::handle('EndProfiletagGetUri', array($this, &$uri));
150 * return a url to the homepage of this item
152 * @return String home url
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;
163 $url = common_local_url('showprofiletag',
164 array('tagger' => $this->getTagger()->nickname,
165 'tag' => $this->tag));
168 Event::handle('EndUserPeopletagHomeUrl', array($this, &$url));
173 * return an immutable url for this object
175 * @return String permalink
181 if (Event::handle('StartProfiletagPermalink', array($this, &$url))) {
182 $url = common_local_url('profiletagbyid',
183 array('id' => $this->id));
185 Event::handle('EndProfiletagPermalink', array($this, &$url));
190 * Query notices by users associated with this tag,
191 * but first check the cache before hitting the DB.
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
198 * @return Notice the query
201 function getNotices($offset, $limit, $since_id=null, $max_id=null)
203 $stream = new PeopletagNoticeStream($this);
205 return $stream->getNotices($offset, $limit, $since_id, $max_id);
209 * Get subscribers (local and remote) to this people tag
210 * Order by reverse chronology
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
217 * @return Profile results
220 function getSubscribers($offset=0, $limit=null, $since=0, $upto=0)
222 $subs = new Profile();
225 array('id', 'profile_tag_subscription:profile_id')
227 $subs->whereAdd('profile_tag_subscription.profile_tag_id = ' . $this->id);
229 $subs->selectAdd('unix_timestamp(profile_tag_subscription.' .
230 'created) as "cursor"');
233 $subs->whereAdd('cursor > ' . $since);
237 $subs->whereAdd('cursor <= ' . $upto);
240 if ($limit != null) {
241 $subs->limit($offset, $limit);
244 $subs->orderBy('profile_tag_subscription.created DESC');
251 * Get all and only local subscribers to this people tag
252 * used for distributing notices to user inboxes.
254 * @return array ids of users
257 function getUserSubscribers()
262 if(common_config('db','quote_identifiers'))
263 $user_table = '"user"';
264 else $user_table = 'user';
268 'FROM '. $user_table .' JOIN profile_tag_subscription '.
269 'ON '. $user_table .'.id = profile_tag_subscription.profile_id ' .
270 'WHERE profile_tag_subscription.profile_tag_id = %d ';
272 $user->query(sprintf($qry, $this->id));
276 while ($user->fetch()) {
286 * Check to see if a given profile has
287 * subscribed to this people tag's timeline
289 * @param mixed $id User or Profile object or integer id
291 * @return boolean subscription status
294 function hasSubscriber($id)
296 if (!is_numeric($id)) {
300 $sub = Profile_tag_subscription::pkeyGet(array('profile_tag_id' => $this->id,
301 'profile_id' => $id));
306 * Get profiles tagged with this people tag,
307 * include modified timestamp as a "cursor" field
308 * order by descending order of modified time
310 * @param integer $offset offset
311 * @param integer $limit maximum no of results
312 * @param integer $since_id=null since unix timestamp
313 * @param integer $upto=null maximum unix timestamp when subscription was made
315 * @return Profile results
318 function getTagged($offset=0, $limit=null, $since=0, $upto=0)
320 $tagged = new Profile();
321 $tagged->joinAdd(array('id', 'profile_tag:tagged'));
324 $tagged->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
325 $tagged->whereAdd('profile_tag.tagger = '.$this->tagger);
326 $tagged->whereAdd("profile_tag.tag = '{$this->tag}'");
329 $tagged->whereAdd('cursor > ' . $since);
333 $tagged->whereAdd('cursor <= ' . $upto);
336 if ($limit != null) {
337 $tagged->limit($offset, $limit);
340 $tagged->orderBy('profile_tag.modified DESC');
347 * Gracefully delete one or many people tags
348 * along with their members and subscriptions data
350 * @return boolean success
355 // force delete one item at a time.
356 if (empty($this->id)) {
358 while ($this->fetch()) {
363 Profile_tag::cleanup($this);
364 Profile_tag_subscription::cleanup($this);
366 self::blow('profile:lists:%d', $this->tagger);
368 return parent::delete();
372 * Update a people tag gracefully
373 * also change "tag" fields in profile_tag table
375 * @param Profile_list $orig Object's original form
377 * @return boolean success
380 function update($orig=null)
384 if (!is_object($orig) && !$orig instanceof Profile_list) {
385 parent::update($orig);
388 // if original tag was different
389 // check to see if the new tag already exists
390 // if not, rename the tag correctly
391 if($orig->tag != $this->tag || $orig->tagger != $this->tagger) {
392 $existing = Profile_list::getByTaggerAndTag($this->tagger, $this->tag);
393 if(!empty($existing)) {
394 // TRANS: Server exception.
395 throw new ServerException(_('The tag you are trying to rename ' .
396 'to already exists.'));
399 // XXX: allow OStatus plugin to send out profile tag
400 $result = Profile_tag::moveTag($orig, $this);
402 parent::update($orig);
407 * return an xml string representing this people tag
408 * as the author of an atom feed
410 * @return string atom author element
413 function asAtomAuthor()
415 $xs = new XMLStringer(true);
417 $tagger = $this->getTagger();
418 $xs->elementStart('author');
419 $xs->element('name', null, '@' . $tagger->nickname . '/' . $this->tag);
420 $xs->element('uri', null, $this->permalink());
421 $xs->elementEnd('author');
423 return $xs->getString();
427 * return an xml string to represent this people tag
428 * as the subject of an activitystreams feed.
430 * @return string activitystreams subject
433 function asActivitySubject()
435 return $this->asActivityNoun('subject');
439 * return an xml string to represent this people tag
440 * as a noun in an activitystreams feed.
442 * @param string $element the xml tag
444 * @return string activitystreams noun
447 function asActivityNoun($element)
449 $noun = ActivityObject::fromPeopletag($this);
450 return $noun->asString('activity:' . $element);
454 * get the cached number of profiles tagged with this
455 * people tag, re-count if the argument is true.
457 * @param boolean $recount whether to ignore cache
459 * @return integer count
462 function taggedCount($recount=false)
464 $keypart = sprintf('profile_list:tagged_count:%d:%s',
468 $count = self::cacheGet($keypart);
470 if ($count === false) {
471 $tags = new Profile_tag();
473 $tags->tag = $this->tag;
474 $tags->tagger = $this->tagger;
476 $count = $tags->count('distinct tagged');
478 self::cacheSet($keypart, $count);
485 * get the cached number of profiles subscribed to this
486 * people tag, re-count if the argument is true.
488 * @param boolean $recount whether to ignore cache
490 * @return integer count
493 function subscriberCount($recount=false)
495 $keypart = sprintf('profile_list:subscriber_count:%d',
498 $count = self::cacheGet($keypart);
500 if ($count === false) {
502 $sub = new Profile_tag_subscription();
503 $sub->profile_tag_id = $this->id;
504 $count = (int) $sub->count('distinct profile_id');
506 self::cacheSet($keypart, $count);
513 * get the cached number of profiles subscribed to this
514 * people tag, re-count if the argument is true.
516 * @param boolean $recount whether to ignore cache
518 * @return integer count
521 function blowNoticeStreamCache($all=false)
523 self::blow('profile_list:notice_ids:%d', $this->id);
525 self::blow('profile_list:notice_ids:%d;last', $this->id);
530 * get the Profile_list object by the
531 * given tagger and with given tag
533 * @param integer $tagger the id of the creator profile
534 * @param integer $tag the tag
536 * @return integer count
539 static function getByTaggerAndTag($tagger, $tag)
541 $ptag = Profile_list::pkeyGet(array('tagger' => $tagger, 'tag' => $tag));
546 * create a profile_list record for a tag, tagger pair
547 * if it doesn't exist, return it.
549 * @param integer $tagger the tagger
550 * @param string $tag the tag
551 * @param string $description description
552 * @param boolean $private protected or not
554 * @return Profile_list the people tag object
557 static function ensureTag($tagger, $tag, $description=null, $private=false)
559 $ptag = Profile_list::getByTaggerAndTag($tagger, $tag);
561 if(empty($ptag->id)) {
565 'description' => $description,
566 'private' => $private
569 $new_tag = Profile_list::saveNew($args);
577 * get the maximum number of characters
578 * that can be used in the description of
581 * determined by $config['peopletag']['desclimit']
582 * if not set, falls back to $config['site']['textlimit']
584 * @return integer maximum number of characters
587 static function maxDescription()
589 $desclimit = common_config('peopletag', 'desclimit');
590 // null => use global limit (distinct from 0!)
591 if (is_null($desclimit)) {
592 $desclimit = common_config('site', 'textlimit');
598 * check if the length of given text exceeds
601 * @param string $desc the description
603 * @return boolean is the descripition too long?
606 static function descriptionTooLong($desc)
608 $desclimit = self::maxDescription();
609 return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
613 * save a new people tag, this should be always used
614 * since it makes uri, homeurl, created and modified
615 * timestamps and performs checks.
617 * @param array $fields an array with fields and their values
619 * @return mixed Profile_list on success, false on fail
621 static function saveNew($fields) {
624 $ptag = new Profile_list();
626 $ptag->query('BEGIN');
628 if (empty($tagger)) {
629 // TRANS: Server exception saving new tag without having a tagger specified.
630 throw new Exception(_('No tagger specified.'));
634 // TRANS: Server exception saving new tag without having a tag specified.
635 throw new Exception(_('No tag specified.'));
638 if (empty($mainpage)) {
647 if (empty($mainpage)) {
651 if (empty($description)) {
655 if (empty($private)) {
659 $ptag->tagger = $tagger;
661 $ptag->description = $description;
662 $ptag->private = $private;
664 $ptag->mainpage = $mainpage;
665 $ptag->created = common_sql_now();
666 $ptag->modified = common_sql_now();
668 $result = $ptag->insert();
671 common_log_db_error($ptag, 'INSERT', __FILE__);
672 // TRANS: Server exception saving new tag.
673 throw new ServerException(_('Could not create profile tag.'));
676 if (!isset($uri) || empty($uri)) {
677 $orig = clone($ptag);
678 $ptag->uri = common_local_url('profiletagbyid', array('id' => $ptag->id, 'tagger_id' => $ptag->tagger));
679 $result = $ptag->update($orig);
681 common_log_db_error($ptag, 'UPDATE', __FILE__);
682 // TRANS: Server exception saving new tag.
683 throw new ServerException(_('Could not set profile tag URI.'));
687 if (!isset($mainpage) || empty($mainpage)) {
688 $orig = clone($ptag);
689 $user = User::staticGet('id', $ptag->tagger);
691 $ptag->mainpage = common_local_url('showprofiletag', array('tag' => $ptag->tag, 'tagger' => $user->nickname));
693 $ptag->mainpage = $uri; // assume this is a remote peopletag and the uri works
696 $result = $ptag->update($orig);
698 common_log_db_error($ptag, 'UPDATE', __FILE__);
699 // TRANS: Server exception saving new tag.
700 throw new ServerException(_('Could not set profile tag mainpage.'));
707 * get all items at given cursor position for api
709 * @param callback $fn a function that takes the following arguments in order:
710 * $offset, $limit, $since_id, $max_id
711 * and returns a Profile_list object after making the DB query
712 * @param array $args arguments required for $fn
713 * @param integer $cursor the cursor
714 * @param integer $count max. number of results
717 * - if cursor is 0, return empty list
718 * - if cursor is -1, get first 21 items, next_cursor = 20th prev_cursor = 0
719 * - if cursor is +ve get 22 consecutive items before starting at cursor
720 * - return items[1..20] if items[0] == cursor else return items[0..21]
721 * - prev_cursor = items[1]
722 * - next_cursor = id of the last item being returned
724 * - if cursor is -ve get 22 consecutive items after cursor starting at cursor
725 * - return items[1..20]
727 * @returns array (array (mixed items), int next_cursor, int previous_cursor)
730 // XXX: This should be in Memcached_DataObject... eventually.
732 static function getAtCursor($fn, $args, $cursor, $count=20)
742 // if cursor is +ve fetch $count+2 items before cursor starting at cursor
744 $fn_args = array_merge($args, array(0, $count+2, 0, $max_id));
745 $list = call_user_func_array($fn, $fn_args);
746 while($list->fetch()) {
747 $items[] = clone($list);
750 if ((isset($items[0]->cursor) && $items[0]->cursor == $cursor) ||
751 $items[0]->id == $cursor) {
753 $prev_cursor = isset($items[0]->cursor) ?
754 -$items[0]->cursor : -$items[0]->id;
756 if (count($items) > $count+1) {
759 // this means the cursor item has been deleted, check to see if there are more
760 $fn_args = array_merge($args, array(0, 1, $cursor));
761 $more = call_user_func($fn, $fn_args);
762 if (!$more->fetch() || empty($more)) {
766 $prev_cursor = isset($items[0]->cursor) ?
767 -$items[0]->cursor : -$items[0]->id;
771 if (count($items)==$count+1) {
772 // this means there is a next page.
773 $next = array_pop($items);
774 $next_cursor = isset($next->cursor) ?
775 $items[$count-1]->cursor : $items[$count-1]->id;
778 } else if($cursor < -1) {
779 // if cursor is -ve fetch $count+2 items created after -$cursor-1
780 $cursor = abs($cursor);
781 $since_id = $cursor-1;
783 $fn_args = array_merge($args, array(0, $count+2, $since_id));
784 $list = call_user_func_array($fn, $fn_args);
785 while($list->fetch()) {
786 $items[] = clone($list);
789 $end = count($items)-1;
790 if ((isset($items[$end]->cursor) && $items[$end]->cursor == $cursor) ||
791 $items[$end]->id == $cursor) {
793 $next_cursor = isset($items[$end-1]->cursor) ?
794 $items[$end-1]->cursor : $items[$end-1]->id;
796 $next_cursor = isset($items[$end]->cursor) ?
797 $items[$end]->cursor : $items[$end]->id;
798 if ($end > $count) array_pop($items); // excess item.
800 // check if there are more items for next page
801 $fn_args = array_merge($args, array(0, 1, 0, $cursor));
802 $more = call_user_func_array($fn, $fn_args);
803 if (!$more->fetch() || empty($more)) {
808 if (count($items) == $count+1) {
809 // this means there is a previous page.
810 $prev = array_shift($items);
811 $prev_cursor = isset($prev->cursor) ?
812 -$items[0]->cursor : -$items[0]->id;
814 } else if($cursor == -1) {
815 $fn_args = array_merge($args, array(0, $count+1));
816 $list = call_user_func_array($fn, $fn_args);
818 while($list->fetch()) {
819 $items[] = clone($list);
822 if (count($items)==$count+1) {
823 $next = array_pop($items);
824 if(isset($next->cursor)) {
825 $next_cursor = $items[$count-1]->cursor;
827 $next_cursor = $items[$count-1]->id;
832 return array($items, $next_cursor, $prev_cursor);
836 * save a collection of people tags into the cache
838 * @param string $ckey cache key
839 * @param Profile_list &$tag the results to store
840 * @param integer $offset offset for slicing results
841 * @param integer $limit maximum number of results
843 * @return boolean success
846 static function setCache($ckey, &$tag, $offset=0, $limit=null) {
847 $cache = Cache::instance();
853 while ($tag->fetch()) {
854 $str .= $tag->tagger . ':' . $tag->tag . ';';
855 $tags[] = clone($tag);
857 $str = substr($str, 0, -1);
858 if ($offset>=0 && !is_null($limit)) {
859 $tags = array_slice($tags, $offset, $limit);
862 $tag = new ArrayWrapper($tags);
864 return self::cacheSet($ckey, $str);
868 * get people tags from the cache
870 * @param string $ckey cache key
871 * @param integer $offset offset for slicing
872 * @param integer $limit limit
874 * @return Profile_list results
877 static function getCached($ckey, $offset=0, $limit=null) {
879 $keys_str = self::cacheGet($ckey);
880 if ($keys_str === false) {
884 $pairs = explode(';', $keys_str);
886 foreach ($pairs as $pair) {
887 $keys[] = explode(':', $pair);
890 if ($offset>=0 && !is_null($limit)) {
891 $keys = array_slice($keys, $offset, $limit);
893 return self::getByKeys($keys);
897 * get Profile_list objects from the database
898 * given their (tag, tagger) key pairs.
900 * @param array $keys array of array(tagger, tag)
902 * @return Profile_list results
905 static function getByKeys($keys) {
906 $cache = Cache::instance();
908 if (!empty($cache)) {
911 foreach ($keys as $key) {
912 $t = Profile_list::getByTaggerAndTag($key[0], $key[1]);
917 return new ArrayWrapper($tags);
919 $tag = new Profile_list();
921 //if no IDs requested, just return the tag object
926 foreach ($keys as $key) {
927 $pairs[] = '(' . $key[0] . ', "' . $key[1] . '")';
930 $tag->whereAdd('(tagger, tag) in (' . implode(', ', $pairs) . ')');
936 while ($tag->fetch()) {
937 $temp[$tag->tagger.'-'.$tag->tag] = clone($tag);
942 foreach ($keys as $key) {
943 $id = $key[0].'-'.$key[1];
944 if (array_key_exists($id, $temp)) {
945 $wrapped[] = $temp[$id];
949 return new ArrayWrapper($wrapped);
955 $result = parent::insert();
957 self::blow('profile:lists:%d', $this->tagger);