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 $width = (int) floor($width);
125 if (is_null($height)) {
129 if (isset($this->_avatars[$width])) {
130 return $this->_avatars[$width];
133 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
134 $avatar = Avatar::pkeyGet(
136 'profile_id' => $this->id,
141 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
144 if (is_null($avatar)) {
145 // Obviously we can't find an avatar, so let's resize the original!
146 $avatar = Avatar::newSize($this, $width);
147 } elseif (!($avatar instanceof Avatar)) {
148 throw new Exception('Bad Avatar retrieved');
151 // cache the avatar for future use
152 $this->_avatars[$width] = $avatar;
157 public function setOriginal($filename)
159 $imagefile = new ImageFile($this->id, Avatar::path($filename));
161 $avatar = new Avatar();
162 $avatar->profile_id = $this->id;
163 $avatar->width = $imagefile->width;
164 $avatar->height = $imagefile->height;
165 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
166 $avatar->filename = $filename;
167 $avatar->original = true;
168 $avatar->url = Avatar::url($filename);
169 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
171 // XXX: start a transaction here
172 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
173 // If we can't delete the old avatars, let's abort right here.
174 @unlink(Avatar::path($filename));
178 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
179 // We don't do a scaled one if original is our scaled size
180 if (!($avatar->width == $size && $avatar->height == $size)) {
182 Avatar::newSize($this, $size);
183 } catch (Exception $e) {
184 // should we abort the generation and live without smaller avatars?
193 * Gets either the full name (if filled) or the nickname.
197 function getBestName()
199 return ($this->fullname) ? $this->fullname : $this->nickname;
203 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
204 * if no fullname is provided.
208 function getFancyName()
210 if ($this->fullname) {
211 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
212 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
214 return $this->nickname;
219 * Get the most recent notice posted by this user, if any.
221 * @return mixed Notice or null
223 function getCurrentNotice()
225 $notice = $this->getNotices(0, 1);
227 if ($notice->fetch()) {
228 if ($notice instanceof ArrayWrapper) {
229 // hack for things trying to work with single notices
230 return $notice->_items[0];
238 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
240 $stream = new TaggedProfileNoticeStream($this, $tag);
242 return $stream->getNotices($offset, $limit, $since_id, $max_id);
245 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
247 $stream = new ProfileNoticeStream($this);
249 return $stream->getNotices($offset, $limit, $since_id, $max_id);
252 function isMember($group)
254 $groups = $this->getGroups(0, null);
255 $gs = $groups->fetchAll();
256 foreach ($gs as $g) {
257 if ($group->id == $g->id) {
264 function isAdmin($group)
266 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
267 'group_id' => $group->id));
268 return (!empty($gm) && $gm->is_admin);
271 function isPendingMember($group)
273 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
274 'group_id' => $group->id));
275 return !empty($request);
278 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
282 $keypart = sprintf('profile:groups:%d', $this->id);
284 $idstring = self::cacheGet($keypart);
286 if ($idstring !== false) {
287 $ids = explode(',', $idstring);
289 $gm = new Group_member();
291 $gm->profile_id = $this->id;
294 while ($gm->fetch()) {
295 $ids[] = $gm->group_id;
299 self::cacheSet($keypart, implode(',', $ids));
302 if (!is_null($offset) && !is_null($limit)) {
303 $ids = array_slice($ids, $offset, $limit);
306 return User_group::multiGet('id', $ids);
309 function isTagged($peopletag)
311 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
312 'tagged' => $this->id,
313 'tag' => $peopletag->tag));
317 function canTag($tagged)
319 if (empty($tagged)) {
323 if ($tagged->id == $this->id) {
327 $all = common_config('peopletag', 'allow_tagging', 'all');
328 $local = common_config('peopletag', 'allow_tagging', 'local');
329 $remote = common_config('peopletag', 'allow_tagging', 'remote');
330 $subs = common_config('peopletag', 'allow_tagging', 'subs');
336 $tagged_user = $tagged->getUser();
337 if (!empty($tagged_user)) {
342 return (Subscription::exists($this, $tagged) ||
343 Subscription::exists($tagged, $this));
344 } else if ($remote) {
350 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
354 $keypart = sprintf('profile:lists:%d', $this->id);
356 $idstr = self::cacheGet($keypart);
358 if ($idstr !== false) {
359 $ids = explode(',', $idstr);
361 $list = new Profile_list();
363 $list->selectAdd('id');
364 $list->tagger = $this->id;
365 $list->selectAdd('id as "cursor"');
368 $list->whereAdd('id > '.$since_id);
372 $list->whereAdd('id <= '.$max_id);
375 if($offset>=0 && !is_null($limit)) {
376 $list->limit($offset, $limit);
379 $list->orderBy('id DESC');
382 while ($list->fetch()) {
387 self::cacheSet($keypart, implode(',', $ids));
390 $showPrivate = (($auth_user instanceof User ||
391 $auth_user instanceof Profile) &&
392 $auth_user->id === $this->id);
396 foreach ($ids as $id) {
397 $list = Profile_list::getKV('id', $id);
399 ($showPrivate || !$list->private)) {
401 if (!isset($list->cursor)) {
402 $list->cursor = $list->id;
409 return new ArrayWrapper($lists);
413 * Get tags that other people put on this profile, in reverse-chron order
415 * @param (Profile|User) $auth_user Authorized user (used for privacy)
416 * @param int $offset Offset from latest
417 * @param int $limit Max number to get
418 * @param datetime $since_id max date
419 * @param datetime $max_id min date
421 * @return Profile_list resulting lists
424 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
426 $list = new Profile_list();
428 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
429 'from profile_tag join profile_list '.
430 'on (profile_tag.tagger = profile_list.tagger ' .
431 ' and profile_tag.tag = profile_list.tag) ' .
432 'where profile_tag.tagged = %d ',
436 if ($auth_user instanceof User || $auth_user instanceof Profile) {
437 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
438 'OR ( profile_list.tagger = %d AND ' .
439 'profile_list.private = true ) )',
442 $qry .= 'AND profile_list.private = 0 ';
446 $qry .= sprintf('AND (cursor > %d) ', $since_id);
450 $qry .= sprintf('AND (cursor < %d) ', $max_id);
453 $qry .= 'ORDER BY profile_tag.modified DESC ';
455 if ($offset >= 0 && !is_null($limit)) {
456 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
463 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
465 $tags = new Profile_list();
466 $tags->private = true;
467 $tags->tagger = $this->id;
470 $tags->whereAdd('id > '.$since_id);
474 $tags->whereAdd('id <= '.$max_id);
477 if($offset>=0 && !is_null($limit)) {
478 $tags->limit($offset, $limit);
481 $tags->orderBy('id DESC');
487 function hasLocalTags()
489 $tags = new Profile_tag();
491 $tags->joinAdd(array('tagger', 'user:id'));
492 $tags->whereAdd('tagged = '.$this->id);
493 $tags->whereAdd('tagger != '.$this->id);
498 return ($tags->N == 0) ? false : true;
501 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
503 $lists = new Profile_list();
504 $subs = new Profile_tag_subscription();
506 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
508 #@fixme: postgres (round(date_part('epoch', my_date)))
509 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
511 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
514 $lists->whereAdd('cursor > '.$since_id);
518 $lists->whereAdd('cursor <= '.$max_id);
521 if($offset>=0 && !is_null($limit)) {
522 $lists->limit($offset, $limit);
525 $lists->orderBy('"cursor" DESC');
532 * Request to join the given group.
533 * May throw exceptions on failure.
535 * @param User_group $group
536 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
538 function joinGroup(User_group $group)
541 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
542 $join = Group_join_queue::saveNew($this, $group);
544 if (Event::handle('StartJoinGroup', array($group, $this))) {
545 $join = Group_member::join($group->id, $this->id);
546 self::blow('profile:groups:%d', $this->id);
547 self::blow('group:member_ids:%d', $group->id);
548 self::blow('group:member_count:%d', $group->id);
549 Event::handle('EndJoinGroup', array($group, $this));
553 // Send any applicable notifications...
560 * Leave a group that this profile is a member of.
562 * @param User_group $group
564 function leaveGroup(User_group $group)
566 if (Event::handle('StartLeaveGroup', array($group, $this))) {
567 Group_member::leave($group->id, $this->id);
568 self::blow('profile:groups:%d', $this->id);
569 self::blow('group:member_ids:%d', $group->id);
570 self::blow('group:member_count:%d', $group->id);
571 Event::handle('EndLeaveGroup', array($group, $this));
575 function avatarUrl($size=AVATAR_PROFILE_SIZE)
577 $size = floor($size);
579 $avatar = $this->getAvatar($size);
580 return $avatar->displayUrl();
581 } catch (Exception $e) {
582 return Avatar::defaultImage($size);
586 function getSubscribed($offset=0, $limit=null)
588 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
589 $profiles = Profile::listFind('id', $subs);
593 function getSubscribers($offset=0, $limit=null)
595 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
596 $profiles = Profile::listFind('id', $subs);
600 function getTaggedSubscribers($tag)
603 'SELECT profile.* ' .
604 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
605 'ON profile.id = subscription.subscriber ' .
606 'AND profile.id = profile_tag.tagged ' .
607 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
608 'WHERE subscription.subscribed = %d ' .
609 'AND subscription.subscribed != subscription.subscriber ' .
610 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
611 'AND profile_list.private = false ' .
612 'ORDER BY subscription.created DESC';
614 $profile = new Profile();
617 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
619 while ($profile->fetch()) {
620 $tagged[] = clone($profile);
626 * Get pending subscribers, who have not yet been approved.
632 function getRequests($offset=0, $limit=null)
635 'SELECT profile.* ' .
636 'FROM profile JOIN subscription_queue '.
637 'ON profile.id = subscription_queue.subscriber ' .
638 'WHERE subscription_queue.subscribed = %d ' .
639 'ORDER BY subscription_queue.created DESC ';
641 if ($limit != null) {
642 if (common_config('db','type') == 'pgsql') {
643 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
645 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
649 $members = new Profile();
651 $members->query(sprintf($qry, $this->id));
655 function subscriptionCount()
657 $c = Cache::instance();
660 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
661 if (is_integer($cnt)) {
666 $sub = new Subscription();
667 $sub->subscriber = $this->id;
669 $cnt = (int) $sub->count('distinct subscribed');
671 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
674 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
680 function subscriberCount()
682 $c = Cache::instance();
684 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
685 if (is_integer($cnt)) {
690 $sub = new Subscription();
691 $sub->subscribed = $this->id;
692 $sub->whereAdd('subscriber != subscribed');
693 $cnt = (int) $sub->count('distinct subscriber');
696 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
703 * Is this profile subscribed to another profile?
705 * @param Profile $other
708 function isSubscribed($other)
710 return Subscription::exists($this, $other);
714 * Check if a pending subscription request is outstanding for this...
716 * @param Profile $other
719 function hasPendingSubscription($other)
721 return Subscription_queue::exists($this, $other);
725 * Are these two profiles subscribed to each other?
727 * @param Profile $other
730 function mutuallySubscribed($other)
732 return $this->isSubscribed($other) &&
733 $other->isSubscribed($this);
736 function hasFave($notice)
738 $fave = Fave::pkeyGet(array('user_id' => $this->id,
739 'notice_id' => $notice->id));
740 return ((is_null($fave)) ? false : true);
745 $c = Cache::instance();
747 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
748 if (is_integer($cnt)) {
754 $faves->user_id = $this->id;
755 $cnt = (int) $faves->count('notice_id');
758 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
764 function noticeCount()
766 $c = Cache::instance();
769 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
770 if (is_integer($cnt)) {
775 $notices = new Notice();
776 $notices->profile_id = $this->id;
777 $cnt = (int) $notices->count('distinct id');
780 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
786 function blowFavesCache()
788 $cache = Cache::instance();
790 // Faves don't happen chronologically, so we need to blow
792 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
793 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
794 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
795 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
797 $this->blowFaveCount();
800 function blowSubscriberCount()
802 $c = Cache::instance();
804 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
808 function blowSubscriptionCount()
810 $c = Cache::instance();
812 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
816 function blowFaveCount()
818 $c = Cache::instance();
820 $c->delete(Cache::key('profile:fave_count:'.$this->id));
824 function blowNoticeCount()
826 $c = Cache::instance();
828 $c->delete(Cache::key('profile:notice_count:'.$this->id));
832 static function maxBio()
834 $biolimit = common_config('profile', 'biolimit');
835 // null => use global limit (distinct from 0!)
836 if (is_null($biolimit)) {
837 $biolimit = common_config('site', 'textlimit');
842 static function bioTooLong($bio)
844 $biolimit = self::maxBio();
845 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
850 $this->_deleteNotices();
851 $this->_deleteSubscriptions();
852 $this->_deleteMessages();
853 $this->_deleteTags();
854 $this->_deleteBlocks();
855 Avatar::deleteFromProfile($this, true);
857 // Warning: delete() will run on the batch objects,
858 // not on individual objects.
859 $related = array('Reply',
862 Event::handle('ProfileDeleteRelated', array($this, &$related));
864 foreach ($related as $cls) {
866 $inst->profile_id = $this->id;
873 function _deleteNotices()
875 $notice = new Notice();
876 $notice->profile_id = $this->id;
878 if ($notice->find()) {
879 while ($notice->fetch()) {
880 $other = clone($notice);
886 function _deleteSubscriptions()
888 $sub = new Subscription();
889 $sub->subscriber = $this->id;
893 while ($sub->fetch()) {
894 $other = Profile::getKV('id', $sub->subscribed);
898 if ($other->id == $this->id) {
901 Subscription::cancel($this, $other);
904 $subd = new Subscription();
905 $subd->subscribed = $this->id;
908 while ($subd->fetch()) {
909 $other = Profile::getKV('id', $subd->subscriber);
913 if ($other->id == $this->id) {
916 Subscription::cancel($other, $this);
919 $self = new Subscription();
921 $self->subscriber = $this->id;
922 $self->subscribed = $this->id;
927 function _deleteMessages()
929 $msg = new Message();
930 $msg->from_profile = $this->id;
933 $msg = new Message();
934 $msg->to_profile = $this->id;
938 function _deleteTags()
940 $tag = new Profile_tag();
941 $tag->tagged = $this->id;
945 function _deleteBlocks()
947 $block = new Profile_block();
948 $block->blocked = $this->id;
951 $block = new Group_block();
952 $block->blocked = $this->id;
956 // XXX: identical to Notice::getLocation.
958 public function getLocation()
962 if (!empty($this->location_id) && !empty($this->location_ns)) {
963 $location = Location::fromId($this->location_id, $this->location_ns);
966 if (is_null($location)) { // no ID, or Location::fromId() failed
967 if (!empty($this->lat) && !empty($this->lon)) {
968 $location = Location::fromLatLon($this->lat, $this->lon);
972 if (is_null($location)) { // still haven't found it!
973 if (!empty($this->location)) {
974 $location = Location::fromName($this->location);
981 public function shareLocation()
983 $cfg = common_config('location', 'share');
985 if ($cfg == 'always') {
987 } else if ($cfg == 'never') {
990 $share = common_config('location', 'sharedefault');
992 // Check if user has a personal setting for this
993 $prefs = User_location_prefs::getKV('user_id', $this->id);
995 if (!empty($prefs)) {
996 $share = $prefs->share_location;
1004 function hasRole($name)
1007 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1008 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1010 $has_role = !empty($role);
1011 Event::handle('EndHasRole', array($this, $name, $has_role));
1016 function grantRole($name)
1018 if (Event::handle('StartGrantRole', array($this, $name))) {
1020 $role = new Profile_role();
1022 $role->profile_id = $this->id;
1023 $role->role = $name;
1024 $role->created = common_sql_now();
1026 $result = $role->insert();
1029 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1032 if ($name == 'owner') {
1033 User::blow('user:site_owner');
1036 Event::handle('EndGrantRole', array($this, $name));
1042 function revokeRole($name)
1044 if (Event::handle('StartRevokeRole', array($this, $name))) {
1046 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1050 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1051 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1052 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1055 $result = $role->delete();
1058 common_log_db_error($role, 'DELETE', __FILE__);
1059 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1060 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1061 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1064 if ($name == 'owner') {
1065 User::blow('user:site_owner');
1068 Event::handle('EndRevokeRole', array($this, $name));
1074 function isSandboxed()
1076 return $this->hasRole(Profile_role::SANDBOXED);
1079 function isSilenced()
1081 return $this->hasRole(Profile_role::SILENCED);
1086 $this->grantRole(Profile_role::SANDBOXED);
1089 function unsandbox()
1091 $this->revokeRole(Profile_role::SANDBOXED);
1096 $this->grantRole(Profile_role::SILENCED);
1097 if (common_config('notice', 'hidespam')) {
1098 $this->flushVisibility();
1102 function unsilence()
1104 $this->revokeRole(Profile_role::SILENCED);
1105 if (common_config('notice', 'hidespam')) {
1106 $this->flushVisibility();
1110 function flushVisibility()
1113 $stream = new ProfileNoticeStream($this, $this);
1114 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1115 foreach ($ids as $id) {
1116 self::blow('notice:in-scope-for:%d:null', $id);
1121 * Does this user have the right to do X?
1123 * With our role-based authorization, this is merely a lookup for whether the user
1124 * has a particular role. The implementation currently uses a switch statement
1125 * to determine if the user has the pre-defined role to exercise the right. Future
1126 * implementations may allow per-site roles, and different mappings of roles to rights.
1128 * @param $right string Name of the right, usually a constant in class Right
1129 * @return boolean whether the user has the right in question
1131 function hasRight($right)
1135 if ($this->hasRole(Profile_role::DELETED)) {
1139 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1142 case Right::DELETEOTHERSNOTICE:
1143 case Right::MAKEGROUPADMIN:
1144 case Right::SANDBOXUSER:
1145 case Right::SILENCEUSER:
1146 case Right::DELETEUSER:
1147 case Right::DELETEGROUP:
1148 case Right::TRAINSPAM:
1149 case Right::REVIEWSPAM:
1150 $result = $this->hasRole(Profile_role::MODERATOR);
1152 case Right::CONFIGURESITE:
1153 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1155 case Right::GRANTROLE:
1156 case Right::REVOKEROLE:
1157 $result = $this->hasRole(Profile_role::OWNER);
1159 case Right::NEWNOTICE:
1160 case Right::NEWMESSAGE:
1161 case Right::SUBSCRIBE:
1162 case Right::CREATEGROUP:
1163 $result = !$this->isSilenced();
1165 case Right::PUBLICNOTICE:
1166 case Right::EMAILONREPLY:
1167 case Right::EMAILONSUBSCRIBE:
1168 case Right::EMAILONFAVE:
1169 $result = !$this->isSandboxed();
1171 case Right::WEBLOGIN:
1172 $result = !$this->isSilenced();
1175 $result = !$this->isSilenced();
1177 case Right::BACKUPACCOUNT:
1178 $result = common_config('profile', 'backup');
1180 case Right::RESTOREACCOUNT:
1181 $result = common_config('profile', 'restore');
1183 case Right::DELETEACCOUNT:
1184 $result = common_config('profile', 'delete');
1186 case Right::MOVEACCOUNT:
1187 $result = common_config('profile', 'move');
1197 function hasRepeated($notice_id)
1199 // XXX: not really a pkey, but should work
1201 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1202 'repeat_of' => $notice_id));
1204 return !empty($notice);
1208 * Returns an XML string fragment with limited profile information
1209 * as an Atom <author> element.
1211 * Assumes that Atom has been previously set up as the base namespace.
1213 * @param Profile $cur the current authenticated user
1217 function asAtomAuthor($cur = null)
1219 $xs = new XMLStringer(true);
1221 $xs->elementStart('author');
1222 $xs->element('name', null, $this->nickname);
1223 $xs->element('uri', null, $this->getUri());
1226 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1227 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1228 $xs->element('statusnet:profile_info', $attrs, null);
1230 $xs->elementEnd('author');
1232 return $xs->getString();
1236 * Extra profile info for atom entries
1238 * Clients use some extra profile info in the atom stream.
1239 * This gives it to them.
1241 * @param User $cur Current user
1243 * @return array representation of <statusnet:profile_info> element or null
1246 function profileInfo($cur)
1248 $profileInfoAttr = array('local_id' => $this->id);
1251 // Whether the current user is a subscribed to this profile
1252 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1253 // Whether the current user is has blocked this profile
1254 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1257 return array('statusnet:profile_info', $profileInfoAttr, null);
1261 * Returns an XML string fragment with profile information as an
1262 * Activity Streams <activity:actor> element.
1264 * Assumes that 'activity' namespace has been previously defined.
1268 function asActivityActor()
1270 return $this->asActivityNoun('actor');
1274 * Returns an XML string fragment with profile information as an
1275 * Activity Streams noun object with the given element type.
1277 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1278 * previously defined.
1280 * @param string $element one of 'actor', 'subject', 'object', 'target'
1284 function asActivityNoun($element)
1286 $noun = ActivityObject::fromProfile($this);
1287 return $noun->asString('activity:' . $element);
1291 * Returns the profile's canonical url, not necessarily a uri/unique id
1293 * @return string $profileurl
1295 public function getUrl()
1297 if (empty($this->profileurl) ||
1298 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1299 throw new InvalidUrlException($this->profileurl);
1301 return $this->profileurl;
1305 * Returns the best URI for a profile. Plugins may override.
1307 * @return string $uri
1309 public function getUri()
1313 // give plugins a chance to set the URI
1314 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1316 // check for a local user first
1317 $user = User::getKV('id', $this->id);
1319 if (!empty($user)) {
1323 Event::handle('EndGetProfileUri', array($this, &$uri));
1329 function hasBlocked($other)
1331 $block = Profile_block::exists($this, $other);
1332 return !empty($block);
1335 function getAtomFeed()
1339 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1340 $user = User::getKV('id', $this->id);
1341 if (!empty($user)) {
1342 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1343 'format' => 'atom'));
1345 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1351 static function fromURI($uri)
1355 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1356 // Get a local user or remote (OMB 0.1) profile
1357 $user = User::getKV('uri', $uri);
1358 if (!empty($user)) {
1359 $profile = $user->getProfile();
1361 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1367 function canRead(Notice $notice)
1369 if ($notice->scope & Notice::SITE_SCOPE) {
1370 $user = $this->getUser();
1376 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1377 $replies = $notice->getReplies();
1379 if (!in_array($this->id, $replies)) {
1380 $groups = $notice->getGroups();
1384 foreach ($groups as $group) {
1385 if ($this->isMember($group)) {
1397 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1398 $author = $notice->getProfile();
1399 if (!Subscription::exists($this, $author)) {
1407 static function current()
1409 $user = common_current_user();
1413 $profile = $user->getProfile();
1419 * Magic function called at serialize() time.
1421 * We use this to drop a couple process-specific references
1422 * from DB_DataObject which can cause trouble in future
1425 * @return array of variable names to include in serialization.
1430 $vars = parent::__sleep();
1431 $skip = array('_user', '_avatars');
1432 return array_diff($vars, $skip);
1435 public function getProfile()