3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
23 * Table Definition for profile
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
27 class Profile extends Managed_DataObject
30 /* the code below is auto generated do not remove the above tag */
32 public $__table = 'profile'; // table name
33 public $id; // int(4) primary_key not_null
34 public $nickname; // varchar(64) multiple_key not_null
35 public $fullname; // varchar(255) multiple_key
36 public $profileurl; // varchar(255)
37 public $homepage; // varchar(255) multiple_key
38 public $bio; // text() multiple_key
39 public $location; // varchar(255) multiple_key
40 public $lat; // decimal(10,7)
41 public $lon; // decimal(10,7)
42 public $location_id; // int(4)
43 public $location_ns; // int(4)
44 public $created; // datetime() not_null
45 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
47 public static function schemaDef()
50 'description' => 'local and remote users have profiles',
52 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
53 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
54 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
55 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
56 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
57 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
58 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
59 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
60 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
61 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
62 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
64 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
65 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
67 'primary key' => array('id'),
69 'profile_nickname_idx' => array('nickname'),
73 // Add a fulltext index
75 if (common_config('search', 'type') == 'fulltext') {
76 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
82 /* the code above is auto generated do not remove the tag below */
85 public static function getByEmail($email)
87 // in the future, profiles should have emails stored...
88 $user = User::getKV('email', $email);
89 if (!($user instanceof User)) {
90 throw new NoSuchUserException(array('email'=>$email));
92 return $user->getProfile();
95 protected $_user = -1; // Uninitialized value distinct from null
97 public function getUser()
99 if ($this->_user === -1) {
100 $this->_user = User::getKV('id', $this->id);
102 if (!($this->_user instanceof User)) {
103 throw new NoSuchUserException(array('id'=>$this->id));
109 public function isLocal()
113 } catch (NoSuchUserException $e) {
119 protected $_avatars = array();
121 public function getAvatar($width, $height=null)
123 return Avatar::byProfile($this, $width, $height);
126 public function setOriginal($filename)
128 $imagefile = new ImageFile($this->id, Avatar::path($filename));
130 $avatar = new Avatar();
131 $avatar->profile_id = $this->id;
132 $avatar->width = $imagefile->width;
133 $avatar->height = $imagefile->height;
134 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
135 $avatar->filename = $filename;
136 $avatar->original = true;
137 $avatar->url = Avatar::url($filename);
138 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
140 // XXX: start a transaction here
141 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
142 // If we can't delete the old avatars, let's abort right here.
143 @unlink(Avatar::path($filename));
147 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
148 // We don't do a scaled one if original is our scaled size
149 if (!($avatar->width == $size && $avatar->height == $size)) {
151 Avatar::newSize($this, $size);
152 } catch (Exception $e) {
153 // should we abort the generation and live without smaller avatars?
162 * Gets either the full name (if filled) or the nickname.
166 function getBestName()
168 return ($this->fullname) ? $this->fullname : $this->nickname;
172 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
173 * if no fullname is provided.
177 function getFancyName()
179 if ($this->fullname) {
180 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
181 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
183 return $this->nickname;
188 * Get the most recent notice posted by this user, if any.
190 * @return mixed Notice or null
192 function getCurrentNotice()
194 $notice = $this->getNotices(0, 1);
196 if ($notice->fetch()) {
197 if ($notice instanceof ArrayWrapper) {
198 // hack for things trying to work with single notices
199 return $notice->_items[0];
207 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
209 $stream = new TaggedProfileNoticeStream($this, $tag);
211 return $stream->getNotices($offset, $limit, $since_id, $max_id);
214 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
216 $stream = new ProfileNoticeStream($this, $scoped);
218 return $stream->getNotices($offset, $limit, $since_id, $max_id);
221 function isMember($group)
223 $groups = $this->getGroups(0, null);
224 $gs = $groups->fetchAll();
225 foreach ($gs as $g) {
226 if ($group->id == $g->id) {
233 function isAdmin($group)
235 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
236 'group_id' => $group->id));
237 return (!empty($gm) && $gm->is_admin);
240 function isPendingMember($group)
242 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
243 'group_id' => $group->id));
244 return !empty($request);
247 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
251 $keypart = sprintf('profile:groups:%d', $this->id);
253 $idstring = self::cacheGet($keypart);
255 if ($idstring !== false) {
256 $ids = explode(',', $idstring);
258 $gm = new Group_member();
260 $gm->profile_id = $this->id;
263 while ($gm->fetch()) {
264 $ids[] = $gm->group_id;
268 self::cacheSet($keypart, implode(',', $ids));
271 if (!is_null($offset) && !is_null($limit)) {
272 $ids = array_slice($ids, $offset, $limit);
275 return User_group::multiGet('id', $ids);
278 function isTagged($peopletag)
280 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
281 'tagged' => $this->id,
282 'tag' => $peopletag->tag));
286 function canTag($tagged)
288 if (empty($tagged)) {
292 if ($tagged->id == $this->id) {
296 $all = common_config('peopletag', 'allow_tagging', 'all');
297 $local = common_config('peopletag', 'allow_tagging', 'local');
298 $remote = common_config('peopletag', 'allow_tagging', 'remote');
299 $subs = common_config('peopletag', 'allow_tagging', 'subs');
305 $tagged_user = $tagged->getUser();
306 if (!empty($tagged_user)) {
311 return (Subscription::exists($this, $tagged) ||
312 Subscription::exists($tagged, $this));
313 } else if ($remote) {
319 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
323 $keypart = sprintf('profile:lists:%d', $this->id);
325 $idstr = self::cacheGet($keypart);
327 if ($idstr !== false) {
328 $ids = explode(',', $idstr);
330 $list = new Profile_list();
332 $list->selectAdd('id');
333 $list->tagger = $this->id;
334 $list->selectAdd('id as "cursor"');
337 $list->whereAdd('id > '.$since_id);
341 $list->whereAdd('id <= '.$max_id);
344 if($offset>=0 && !is_null($limit)) {
345 $list->limit($offset, $limit);
348 $list->orderBy('id DESC');
351 while ($list->fetch()) {
356 self::cacheSet($keypart, implode(',', $ids));
359 $showPrivate = (($auth_user instanceof User ||
360 $auth_user instanceof Profile) &&
361 $auth_user->id === $this->id);
365 foreach ($ids as $id) {
366 $list = Profile_list::getKV('id', $id);
368 ($showPrivate || !$list->private)) {
370 if (!isset($list->cursor)) {
371 $list->cursor = $list->id;
378 return new ArrayWrapper($lists);
382 * Get tags that other people put on this profile, in reverse-chron order
384 * @param (Profile|User) $auth_user Authorized user (used for privacy)
385 * @param int $offset Offset from latest
386 * @param int $limit Max number to get
387 * @param datetime $since_id max date
388 * @param datetime $max_id min date
390 * @return Profile_list resulting lists
393 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
395 $list = new Profile_list();
397 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
398 'from profile_tag join profile_list '.
399 'on (profile_tag.tagger = profile_list.tagger ' .
400 ' and profile_tag.tag = profile_list.tag) ' .
401 'where profile_tag.tagged = %d ',
405 if ($auth_user instanceof User || $auth_user instanceof Profile) {
406 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
407 'OR ( profile_list.tagger = %d AND ' .
408 'profile_list.private = true ) )',
411 $qry .= 'AND profile_list.private = 0 ';
415 $qry .= sprintf('AND (cursor > %d) ', $since_id);
419 $qry .= sprintf('AND (cursor < %d) ', $max_id);
422 $qry .= 'ORDER BY profile_tag.modified DESC ';
424 if ($offset >= 0 && !is_null($limit)) {
425 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
432 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
434 $tags = new Profile_list();
435 $tags->private = true;
436 $tags->tagger = $this->id;
439 $tags->whereAdd('id > '.$since_id);
443 $tags->whereAdd('id <= '.$max_id);
446 if($offset>=0 && !is_null($limit)) {
447 $tags->limit($offset, $limit);
450 $tags->orderBy('id DESC');
456 function hasLocalTags()
458 $tags = new Profile_tag();
460 $tags->joinAdd(array('tagger', 'user:id'));
461 $tags->whereAdd('tagged = '.$this->id);
462 $tags->whereAdd('tagger != '.$this->id);
467 return ($tags->N == 0) ? false : true;
470 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
472 $lists = new Profile_list();
473 $subs = new Profile_tag_subscription();
475 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
477 #@fixme: postgres (round(date_part('epoch', my_date)))
478 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
480 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
483 $lists->whereAdd('cursor > '.$since_id);
487 $lists->whereAdd('cursor <= '.$max_id);
490 if($offset>=0 && !is_null($limit)) {
491 $lists->limit($offset, $limit);
494 $lists->orderBy('"cursor" DESC');
501 * Request to join the given group.
502 * May throw exceptions on failure.
504 * @param User_group $group
505 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
507 function joinGroup(User_group $group)
510 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
511 $join = Group_join_queue::saveNew($this, $group);
513 if (Event::handle('StartJoinGroup', array($group, $this))) {
514 $join = Group_member::join($group->id, $this->id);
515 self::blow('profile:groups:%d', $this->id);
516 self::blow('group:member_ids:%d', $group->id);
517 self::blow('group:member_count:%d', $group->id);
518 Event::handle('EndJoinGroup', array($group, $this));
522 // Send any applicable notifications...
529 * Leave a group that this profile is a member of.
531 * @param User_group $group
533 function leaveGroup(User_group $group)
535 if (Event::handle('StartLeaveGroup', array($group, $this))) {
536 Group_member::leave($group->id, $this->id);
537 self::blow('profile:groups:%d', $this->id);
538 self::blow('group:member_ids:%d', $group->id);
539 self::blow('group:member_count:%d', $group->id);
540 Event::handle('EndLeaveGroup', array($group, $this));
544 function avatarUrl($size=AVATAR_PROFILE_SIZE)
546 return Avatar::urlByProfile($this, $size);
549 function getSubscribed($offset=0, $limit=null)
551 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
553 $profiles = Profile::listFind('id', $subs);
554 } catch (NoResultException $e) {
560 function getSubscribers($offset=0, $limit=null)
562 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
564 $profiles = Profile::listFind('id', $subs);
565 } catch (NoResultException $e) {
571 function getTaggedSubscribers($tag)
574 'SELECT profile.* ' .
575 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
576 'ON profile.id = subscription.subscriber ' .
577 'AND profile.id = profile_tag.tagged ' .
578 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
579 'WHERE subscription.subscribed = %d ' .
580 'AND subscription.subscribed != subscription.subscriber ' .
581 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
582 'AND profile_list.private = false ' .
583 'ORDER BY subscription.created DESC';
585 $profile = new Profile();
588 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
590 while ($profile->fetch()) {
591 $tagged[] = clone($profile);
597 * Get pending subscribers, who have not yet been approved.
603 function getRequests($offset=0, $limit=null)
606 'SELECT profile.* ' .
607 'FROM profile JOIN subscription_queue '.
608 'ON profile.id = subscription_queue.subscriber ' .
609 'WHERE subscription_queue.subscribed = %d ' .
610 'ORDER BY subscription_queue.created DESC ';
612 if ($limit != null) {
613 if (common_config('db','type') == 'pgsql') {
614 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
616 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
620 $members = new Profile();
622 $members->query(sprintf($qry, $this->id));
626 function subscriptionCount()
628 $c = Cache::instance();
631 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
632 if (is_integer($cnt)) {
637 $sub = new Subscription();
638 $sub->subscriber = $this->id;
640 $cnt = (int) $sub->count('distinct subscribed');
642 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
645 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
651 function subscriberCount()
653 $c = Cache::instance();
655 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
656 if (is_integer($cnt)) {
661 $sub = new Subscription();
662 $sub->subscribed = $this->id;
663 $sub->whereAdd('subscriber != subscribed');
664 $cnt = (int) $sub->count('distinct subscriber');
667 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
674 * Is this profile subscribed to another profile?
676 * @param Profile $other
679 function isSubscribed($other)
681 return Subscription::exists($this, $other);
685 * Check if a pending subscription request is outstanding for this...
687 * @param Profile $other
690 function hasPendingSubscription($other)
692 return Subscription_queue::exists($this, $other);
696 * Are these two profiles subscribed to each other?
698 * @param Profile $other
701 function mutuallySubscribed($other)
703 return $this->isSubscribed($other) &&
704 $other->isSubscribed($this);
707 function hasFave($notice)
709 $fave = Fave::pkeyGet(array('user_id' => $this->id,
710 'notice_id' => $notice->id));
711 return ((is_null($fave)) ? false : true);
716 $c = Cache::instance();
718 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
719 if (is_integer($cnt)) {
725 $faves->user_id = $this->id;
726 $cnt = (int) $faves->count('notice_id');
729 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
735 function noticeCount()
737 $c = Cache::instance();
740 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
741 if (is_integer($cnt)) {
746 $notices = new Notice();
747 $notices->profile_id = $this->id;
748 $cnt = (int) $notices->count('distinct id');
751 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
757 function blowFavesCache()
759 $cache = Cache::instance();
761 // Faves don't happen chronologically, so we need to blow
763 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
764 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
765 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
766 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
768 $this->blowFaveCount();
771 function blowSubscriberCount()
773 $c = Cache::instance();
775 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
779 function blowSubscriptionCount()
781 $c = Cache::instance();
783 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
787 function blowFaveCount()
789 $c = Cache::instance();
791 $c->delete(Cache::key('profile:fave_count:'.$this->id));
795 function blowNoticeCount()
797 $c = Cache::instance();
799 $c->delete(Cache::key('profile:notice_count:'.$this->id));
803 static function maxBio()
805 $biolimit = common_config('profile', 'biolimit');
806 // null => use global limit (distinct from 0!)
807 if (is_null($biolimit)) {
808 $biolimit = common_config('site', 'textlimit');
813 static function bioTooLong($bio)
815 $biolimit = self::maxBio();
816 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
821 $this->_deleteNotices();
822 $this->_deleteSubscriptions();
823 $this->_deleteMessages();
824 $this->_deleteTags();
825 $this->_deleteBlocks();
826 Avatar::deleteFromProfile($this, true);
828 // Warning: delete() will run on the batch objects,
829 // not on individual objects.
830 $related = array('Reply',
833 Event::handle('ProfileDeleteRelated', array($this, &$related));
835 foreach ($related as $cls) {
837 $inst->profile_id = $this->id;
844 function _deleteNotices()
846 $notice = new Notice();
847 $notice->profile_id = $this->id;
849 if ($notice->find()) {
850 while ($notice->fetch()) {
851 $other = clone($notice);
857 function _deleteSubscriptions()
859 $sub = new Subscription();
860 $sub->subscriber = $this->id;
864 while ($sub->fetch()) {
865 $other = Profile::getKV('id', $sub->subscribed);
869 if ($other->id == $this->id) {
872 Subscription::cancel($this, $other);
875 $subd = new Subscription();
876 $subd->subscribed = $this->id;
879 while ($subd->fetch()) {
880 $other = Profile::getKV('id', $subd->subscriber);
884 if ($other->id == $this->id) {
887 Subscription::cancel($other, $this);
890 $self = new Subscription();
892 $self->subscriber = $this->id;
893 $self->subscribed = $this->id;
898 function _deleteMessages()
900 $msg = new Message();
901 $msg->from_profile = $this->id;
904 $msg = new Message();
905 $msg->to_profile = $this->id;
909 function _deleteTags()
911 $tag = new Profile_tag();
912 $tag->tagged = $this->id;
916 function _deleteBlocks()
918 $block = new Profile_block();
919 $block->blocked = $this->id;
922 $block = new Group_block();
923 $block->blocked = $this->id;
927 // XXX: identical to Notice::getLocation.
929 public function getLocation()
933 if (!empty($this->location_id) && !empty($this->location_ns)) {
934 $location = Location::fromId($this->location_id, $this->location_ns);
937 if (is_null($location)) { // no ID, or Location::fromId() failed
938 if (!empty($this->lat) && !empty($this->lon)) {
939 $location = Location::fromLatLon($this->lat, $this->lon);
943 if (is_null($location)) { // still haven't found it!
944 if (!empty($this->location)) {
945 $location = Location::fromName($this->location);
952 public function shareLocation()
954 $cfg = common_config('location', 'share');
956 if ($cfg == 'always') {
958 } else if ($cfg == 'never') {
961 $share = common_config('location', 'sharedefault');
963 // Check if user has a personal setting for this
964 $prefs = User_location_prefs::getKV('user_id', $this->id);
966 if (!empty($prefs)) {
967 $share = $prefs->share_location;
975 function hasRole($name)
978 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
979 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
981 $has_role = !empty($role);
982 Event::handle('EndHasRole', array($this, $name, $has_role));
987 function grantRole($name)
989 if (Event::handle('StartGrantRole', array($this, $name))) {
991 $role = new Profile_role();
993 $role->profile_id = $this->id;
995 $role->created = common_sql_now();
997 $result = $role->insert();
1000 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1003 if ($name == 'owner') {
1004 User::blow('user:site_owner');
1007 Event::handle('EndGrantRole', array($this, $name));
1013 function revokeRole($name)
1015 if (Event::handle('StartRevokeRole', array($this, $name))) {
1017 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1021 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1022 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1023 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1026 $result = $role->delete();
1029 common_log_db_error($role, 'DELETE', __FILE__);
1030 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1031 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1032 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1035 if ($name == 'owner') {
1036 User::blow('user:site_owner');
1039 Event::handle('EndRevokeRole', array($this, $name));
1045 function isSandboxed()
1047 return $this->hasRole(Profile_role::SANDBOXED);
1050 function isSilenced()
1052 return $this->hasRole(Profile_role::SILENCED);
1057 $this->grantRole(Profile_role::SANDBOXED);
1060 function unsandbox()
1062 $this->revokeRole(Profile_role::SANDBOXED);
1067 $this->grantRole(Profile_role::SILENCED);
1068 if (common_config('notice', 'hidespam')) {
1069 $this->flushVisibility();
1073 function unsilence()
1075 $this->revokeRole(Profile_role::SILENCED);
1076 if (common_config('notice', 'hidespam')) {
1077 $this->flushVisibility();
1081 function flushVisibility()
1084 $stream = new ProfileNoticeStream($this, $this);
1085 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1086 foreach ($ids as $id) {
1087 self::blow('notice:in-scope-for:%d:null', $id);
1092 * Does this user have the right to do X?
1094 * With our role-based authorization, this is merely a lookup for whether the user
1095 * has a particular role. The implementation currently uses a switch statement
1096 * to determine if the user has the pre-defined role to exercise the right. Future
1097 * implementations may allow per-site roles, and different mappings of roles to rights.
1099 * @param $right string Name of the right, usually a constant in class Right
1100 * @return boolean whether the user has the right in question
1102 function hasRight($right)
1106 if ($this->hasRole(Profile_role::DELETED)) {
1110 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1113 case Right::DELETEOTHERSNOTICE:
1114 case Right::MAKEGROUPADMIN:
1115 case Right::SANDBOXUSER:
1116 case Right::SILENCEUSER:
1117 case Right::DELETEUSER:
1118 case Right::DELETEGROUP:
1119 case Right::TRAINSPAM:
1120 case Right::REVIEWSPAM:
1121 $result = $this->hasRole(Profile_role::MODERATOR);
1123 case Right::CONFIGURESITE:
1124 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1126 case Right::GRANTROLE:
1127 case Right::REVOKEROLE:
1128 $result = $this->hasRole(Profile_role::OWNER);
1130 case Right::NEWNOTICE:
1131 case Right::NEWMESSAGE:
1132 case Right::SUBSCRIBE:
1133 case Right::CREATEGROUP:
1134 $result = !$this->isSilenced();
1136 case Right::PUBLICNOTICE:
1137 case Right::EMAILONREPLY:
1138 case Right::EMAILONSUBSCRIBE:
1139 case Right::EMAILONFAVE:
1140 $result = !$this->isSandboxed();
1142 case Right::WEBLOGIN:
1143 $result = !$this->isSilenced();
1146 $result = !$this->isSilenced();
1148 case Right::BACKUPACCOUNT:
1149 $result = common_config('profile', 'backup');
1151 case Right::RESTOREACCOUNT:
1152 $result = common_config('profile', 'restore');
1154 case Right::DELETEACCOUNT:
1155 $result = common_config('profile', 'delete');
1157 case Right::MOVEACCOUNT:
1158 $result = common_config('profile', 'move');
1168 // FIXME: Can't put Notice typing here due to ArrayWrapper
1169 public function hasRepeated($notice)
1171 // XXX: not really a pkey, but should work
1173 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1174 'repeat_of' => $notice->id));
1176 return !empty($notice);
1180 * Returns an XML string fragment with limited profile information
1181 * as an Atom <author> element.
1183 * Assumes that Atom has been previously set up as the base namespace.
1185 * @param Profile $cur the current authenticated user
1189 function asAtomAuthor($cur = null)
1191 $xs = new XMLStringer(true);
1193 $xs->elementStart('author');
1194 $xs->element('name', null, $this->nickname);
1195 $xs->element('uri', null, $this->getUri());
1198 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1199 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1200 $xs->element('statusnet:profile_info', $attrs, null);
1202 $xs->elementEnd('author');
1204 return $xs->getString();
1208 * Extra profile info for atom entries
1210 * Clients use some extra profile info in the atom stream.
1211 * This gives it to them.
1213 * @param User $cur Current user
1215 * @return array representation of <statusnet:profile_info> element or null
1218 function profileInfo($cur)
1220 $profileInfoAttr = array('local_id' => $this->id);
1223 // Whether the current user is a subscribed to this profile
1224 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1225 // Whether the current user is has blocked this profile
1226 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1229 return array('statusnet:profile_info', $profileInfoAttr, null);
1233 * Returns an XML string fragment with profile information as an
1234 * Activity Streams <activity:actor> element.
1236 * Assumes that 'activity' namespace has been previously defined.
1240 function asActivityActor()
1242 return $this->asActivityNoun('actor');
1246 * Returns an XML string fragment with profile information as an
1247 * Activity Streams noun object with the given element type.
1249 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1250 * previously defined.
1252 * @param string $element one of 'actor', 'subject', 'object', 'target'
1256 function asActivityNoun($element)
1258 $noun = ActivityObject::fromProfile($this);
1259 return $noun->asString('activity:' . $element);
1263 * Returns the profile's canonical url, not necessarily a uri/unique id
1265 * @return string $profileurl
1267 public function getUrl()
1269 if (empty($this->profileurl) ||
1270 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1271 throw new InvalidUrlException($this->profileurl);
1273 return $this->profileurl;
1277 * Returns the best URI for a profile. Plugins may override.
1279 * @return string $uri
1281 public function getUri()
1285 // give plugins a chance to set the URI
1286 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1288 // check for a local user first
1289 $user = User::getKV('id', $this->id);
1291 if (!empty($user)) {
1295 Event::handle('EndGetProfileUri', array($this, &$uri));
1301 function hasBlocked($other)
1303 $block = Profile_block::exists($this, $other);
1304 return !empty($block);
1307 function getAtomFeed()
1311 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1312 $user = User::getKV('id', $this->id);
1313 if (!empty($user)) {
1314 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1315 'format' => 'atom'));
1317 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1323 static function fromURI($uri)
1327 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1328 // Get a local user or remote (OMB 0.1) profile
1329 $user = User::getKV('uri', $uri);
1330 if (!empty($user)) {
1331 $profile = $user->getProfile();
1333 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1339 function canRead(Notice $notice)
1341 if ($notice->scope & Notice::SITE_SCOPE) {
1342 $user = $this->getUser();
1348 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1349 $replies = $notice->getReplies();
1351 if (!in_array($this->id, $replies)) {
1352 $groups = $notice->getGroups();
1356 foreach ($groups as $group) {
1357 if ($this->isMember($group)) {
1369 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1370 $author = $notice->getProfile();
1371 if (!Subscription::exists($this, $author)) {
1379 static function current()
1381 $user = common_current_user();
1385 $profile = $user->getProfile();
1391 * Magic function called at serialize() time.
1393 * We use this to drop a couple process-specific references
1394 * from DB_DataObject which can cause trouble in future
1397 * @return array of variable names to include in serialization.
1402 $vars = parent::__sleep();
1403 $skip = array('_user', '_avatars');
1404 return array_diff($vars, $skip);
1407 public function getProfile()