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 = array();
97 public function getUser()
99 if (!isset($this->_user[$this->id])) {
100 $user = User::getKV('id', $this->id);
101 if (!$user instanceof User) {
102 throw new NoSuchUserException(array('id'=>$this->id));
104 $this->_user[$this->id] = $user;
106 return $this->_user[$this->id];
109 protected $_group = array();
111 public function getGroup()
113 if (!isset($this->_group[$this->id])) {
114 $group = User_group::getKV('profile_id', $this->id);
115 if (!$group instanceof User_group) {
116 throw new NoSuchGroupException(array('profile_id'=>$this->id));
118 $this->_group[$this->id] = $group;
120 return $this->_group[$this->id];
123 public function isGroup()
128 } catch (NoSuchGroupException $e) {
133 public function isLocal()
137 } catch (NoSuchUserException $e) {
143 public function getAvatar($width, $height=null)
145 return Avatar::byProfile($this, $width, $height);
148 public function setOriginal($filename)
150 $imagefile = new ImageFile($this->id, Avatar::path($filename));
152 $avatar = new Avatar();
153 $avatar->profile_id = $this->id;
154 $avatar->width = $imagefile->width;
155 $avatar->height = $imagefile->height;
156 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
157 $avatar->filename = $filename;
158 $avatar->original = true;
159 $avatar->url = Avatar::url($filename);
160 $avatar->created = common_sql_now();
162 // XXX: start a transaction here
163 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
164 // If we can't delete the old avatars, let's abort right here.
165 @unlink(Avatar::path($filename));
173 * Gets either the full name (if filled) or the nickname.
177 function getBestName()
179 return ($this->fullname) ? $this->fullname : $this->nickname;
183 * Takes the currently scoped profile into account to give a name
184 * to list in notice streams. Preferences may differ between profiles.
186 function getStreamName()
188 $user = common_current_user();
189 if ($user instanceof User && $user->streamNicknames()) {
190 return $this->nickname;
193 return $this->getBestName();
197 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
198 * if no fullname is provided.
202 function getFancyName()
204 if ($this->fullname) {
205 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
206 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
208 return $this->nickname;
213 * Get the most recent notice posted by this user, if any.
215 * @return mixed Notice or null
217 function getCurrentNotice()
219 $notice = $this->getNotices(0, 1);
221 if ($notice->fetch()) {
222 if ($notice instanceof ArrayWrapper) {
223 // hack for things trying to work with single notices
224 return $notice->_items[0];
232 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
234 $stream = new TaggedProfileNoticeStream($this, $tag);
236 return $stream->getNotices($offset, $limit, $since_id, $max_id);
239 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
241 $stream = new ProfileNoticeStream($this, $scoped);
243 return $stream->getNotices($offset, $limit, $since_id, $max_id);
246 function isMember(User_group $group)
248 $groups = $this->getGroups(0, null);
249 while ($groups instanceof User_group && $groups->fetch()) {
250 if ($groups->id == $group->id) {
257 function isAdmin(User_group $group)
259 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
260 'group_id' => $group->id));
261 return (!empty($gm) && $gm->is_admin);
264 function isPendingMember($group)
266 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
267 'group_id' => $group->id));
268 return !empty($request);
271 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
275 $keypart = sprintf('profile:groups:%d', $this->id);
277 $idstring = self::cacheGet($keypart);
279 if ($idstring !== false) {
280 $ids = explode(',', $idstring);
282 $gm = new Group_member();
284 $gm->profile_id = $this->id;
287 while ($gm->fetch()) {
288 $ids[] = $gm->group_id;
292 self::cacheSet($keypart, implode(',', $ids));
295 if (!is_null($offset) && !is_null($limit)) {
296 $ids = array_slice($ids, $offset, $limit);
300 return User_group::listFind('id', $ids);
301 } catch (NoResultException $e) {
302 return null; // throw exception when we handle it everywhere
306 function getGroupCount() {
307 $groups = $this->getGroups(0, null);
308 return $groups instanceof User_group
313 function isTagged($peopletag)
315 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
316 'tagged' => $this->id,
317 'tag' => $peopletag->tag));
321 function canTag($tagged)
323 if (empty($tagged)) {
327 if ($tagged->id == $this->id) {
331 $all = common_config('peopletag', 'allow_tagging', 'all');
332 $local = common_config('peopletag', 'allow_tagging', 'local');
333 $remote = common_config('peopletag', 'allow_tagging', 'remote');
334 $subs = common_config('peopletag', 'allow_tagging', 'subs');
340 $tagged_user = $tagged->getUser();
341 if (!empty($tagged_user)) {
346 return (Subscription::exists($this, $tagged) ||
347 Subscription::exists($tagged, $this));
348 } else if ($remote) {
354 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
358 $keypart = sprintf('profile:lists:%d', $this->id);
360 $idstr = self::cacheGet($keypart);
362 if ($idstr !== false) {
363 $ids = explode(',', $idstr);
365 $list = new Profile_list();
367 $list->selectAdd('id');
368 $list->tagger = $this->id;
369 $list->selectAdd('id as "cursor"');
372 $list->whereAdd('id > '.$since_id);
376 $list->whereAdd('id <= '.$max_id);
379 if($offset>=0 && !is_null($limit)) {
380 $list->limit($offset, $limit);
383 $list->orderBy('id DESC');
386 while ($list->fetch()) {
391 self::cacheSet($keypart, implode(',', $ids));
394 $showPrivate = (($auth_user instanceof User ||
395 $auth_user instanceof Profile) &&
396 $auth_user->id === $this->id);
400 foreach ($ids as $id) {
401 $list = Profile_list::getKV('id', $id);
403 ($showPrivate || !$list->private)) {
405 if (!isset($list->cursor)) {
406 $list->cursor = $list->id;
413 return new ArrayWrapper($lists);
417 * Get tags that other people put on this profile, in reverse-chron order
419 * @param (Profile|User) $auth_user Authorized user (used for privacy)
420 * @param int $offset Offset from latest
421 * @param int $limit Max number to get
422 * @param datetime $since_id max date
423 * @param datetime $max_id min date
425 * @return Profile_list resulting lists
428 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
430 $list = new Profile_list();
432 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
433 'from profile_tag join profile_list '.
434 'on (profile_tag.tagger = profile_list.tagger ' .
435 ' and profile_tag.tag = profile_list.tag) ' .
436 'where profile_tag.tagged = %d ',
440 if ($auth_user instanceof User || $auth_user instanceof Profile) {
441 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
442 'OR ( profile_list.tagger = %d AND ' .
443 'profile_list.private = true ) )',
446 $qry .= 'AND profile_list.private = 0 ';
450 $qry .= sprintf('AND (cursor > %d) ', $since_id);
454 $qry .= sprintf('AND (cursor < %d) ', $max_id);
457 $qry .= 'ORDER BY profile_tag.modified DESC ';
459 if ($offset >= 0 && !is_null($limit)) {
460 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
467 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
469 $tags = new Profile_list();
470 $tags->private = true;
471 $tags->tagger = $this->id;
474 $tags->whereAdd('id > '.$since_id);
478 $tags->whereAdd('id <= '.$max_id);
481 if($offset>=0 && !is_null($limit)) {
482 $tags->limit($offset, $limit);
485 $tags->orderBy('id DESC');
491 function hasLocalTags()
493 $tags = new Profile_tag();
495 $tags->joinAdd(array('tagger', 'user:id'));
496 $tags->whereAdd('tagged = '.$this->id);
497 $tags->whereAdd('tagger != '.$this->id);
502 return ($tags->N == 0) ? false : true;
505 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
507 $lists = new Profile_list();
508 $subs = new Profile_tag_subscription();
510 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
512 #@fixme: postgres (round(date_part('epoch', my_date)))
513 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
515 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
518 $lists->whereAdd('cursor > '.$since_id);
522 $lists->whereAdd('cursor <= '.$max_id);
525 if($offset>=0 && !is_null($limit)) {
526 $lists->limit($offset, $limit);
529 $lists->orderBy('"cursor" DESC');
536 * Request to join the given group.
537 * May throw exceptions on failure.
539 * @param User_group $group
540 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
542 function joinGroup(User_group $group)
545 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
546 $join = Group_join_queue::saveNew($this, $group);
548 if (Event::handle('StartJoinGroup', array($group, $this))) {
549 $join = Group_member::join($group->id, $this->id);
550 self::blow('profile:groups:%d', $this->id);
551 self::blow('group:member_ids:%d', $group->id);
552 self::blow('group:member_count:%d', $group->id);
553 Event::handle('EndJoinGroup', array($group, $this));
557 // Send any applicable notifications...
564 * Leave a group that this profile is a member of.
566 * @param User_group $group
568 function leaveGroup(User_group $group)
570 if (Event::handle('StartLeaveGroup', array($group, $this))) {
571 Group_member::leave($group->id, $this->id);
572 self::blow('profile:groups:%d', $this->id);
573 self::blow('group:member_ids:%d', $group->id);
574 self::blow('group:member_count:%d', $group->id);
575 Event::handle('EndLeaveGroup', array($group, $this));
579 function avatarUrl($size=AVATAR_PROFILE_SIZE)
581 return Avatar::urlByProfile($this, $size);
584 function getSubscribed($offset=0, $limit=null)
586 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
588 $profiles = Profile::listFind('id', $subs);
589 } catch (NoResultException $e) {
595 function getSubscribers($offset=0, $limit=null)
597 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
599 $profiles = Profile::listFind('id', $subs);
600 } catch (NoResultException $e) {
606 function getTaggedSubscribers($tag, $offset=0, $limit=null)
609 'SELECT profile.* ' .
610 'FROM profile JOIN subscription ' .
611 'ON profile.id = subscription.subscriber ' .
612 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
613 'AND profile_tag.tagger = subscription.subscribed) ' .
614 'WHERE subscription.subscribed = %d ' .
615 "AND profile_tag.tag = '%s' " .
616 'AND subscription.subscribed != subscription.subscriber ' .
617 'ORDER BY subscription.created DESC ';
620 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
623 $profile = new Profile();
625 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
630 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
633 'SELECT profile.* ' .
634 'FROM profile JOIN subscription ' .
635 'ON profile.id = subscription.subscribed ' .
636 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
637 'AND profile_tag.tagger = subscription.subscriber) ' .
638 'WHERE subscription.subscriber = %d ' .
639 "AND profile_tag.tag = '%s' " .
640 'AND subscription.subscribed != subscription.subscriber ' .
641 'ORDER BY subscription.created DESC ';
643 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
645 $profile = new Profile();
647 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
653 * Get pending subscribers, who have not yet been approved.
659 function getRequests($offset=0, $limit=null)
662 'SELECT profile.* ' .
663 'FROM profile JOIN subscription_queue '.
664 'ON profile.id = subscription_queue.subscriber ' .
665 'WHERE subscription_queue.subscribed = %d ' .
666 'ORDER BY subscription_queue.created DESC ';
668 if ($limit != null) {
669 if (common_config('db','type') == 'pgsql') {
670 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
672 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
676 $members = new Profile();
678 $members->query(sprintf($qry, $this->id));
682 function subscriptionCount()
684 $c = Cache::instance();
687 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
688 if (is_integer($cnt)) {
693 $sub = new Subscription();
694 $sub->subscriber = $this->id;
696 $cnt = (int) $sub->count('distinct subscribed');
698 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
701 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
707 function subscriberCount()
709 $c = Cache::instance();
711 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
712 if (is_integer($cnt)) {
717 $sub = new Subscription();
718 $sub->subscribed = $this->id;
719 $sub->whereAdd('subscriber != subscribed');
720 $cnt = (int) $sub->count('distinct subscriber');
723 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
730 * Is this profile subscribed to another profile?
732 * @param Profile $other
735 function isSubscribed(Profile $other)
737 return Subscription::exists($this, $other);
741 * Check if a pending subscription request is outstanding for this...
743 * @param Profile $other
746 function hasPendingSubscription(Profile $other)
748 return Subscription_queue::exists($this, $other);
752 * Are these two profiles subscribed to each other?
754 * @param Profile $other
757 function mutuallySubscribed(Profile $other)
759 return $this->isSubscribed($other) &&
760 $other->isSubscribed($this);
763 function noticeCount()
765 $c = Cache::instance();
768 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
769 if (is_integer($cnt)) {
774 $notices = new Notice();
775 $notices->profile_id = $this->id;
776 $cnt = (int) $notices->count('distinct id');
779 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
785 function blowSubscriberCount()
787 $c = Cache::instance();
789 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
793 function blowSubscriptionCount()
795 $c = Cache::instance();
797 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
801 function blowNoticeCount()
803 $c = Cache::instance();
805 $c->delete(Cache::key('profile:notice_count:'.$this->id));
809 static function maxBio()
811 $biolimit = common_config('profile', 'biolimit');
812 // null => use global limit (distinct from 0!)
813 if (is_null($biolimit)) {
814 $biolimit = common_config('site', 'textlimit');
819 static function bioTooLong($bio)
821 $biolimit = self::maxBio();
822 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
825 function update($dataObject=false)
827 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
829 $local = $this->getUser();
830 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
831 $origuser = clone($local);
832 $local->nickname = $this->nickname;
833 $result = $local->updateKeys($origuser);
834 if ($result === false) {
835 common_log_db_error($local, 'UPDATE', __FILE__);
836 // TRANS: Server error thrown when user profile settings could not be updated.
837 throw new ServerException(_('Could not update user nickname.'));
840 // Clear the site owner, in case nickname changed
841 if ($local->hasRole(Profile_role::OWNER)) {
842 User::blow('user:site_owner');
844 } catch (NoSuchUserException $e) {
849 return parent::update($dataObject);
852 function delete($useWhere=false)
854 $this->_deleteNotices();
855 $this->_deleteSubscriptions();
856 $this->_deleteMessages();
857 $this->_deleteTags();
858 $this->_deleteBlocks();
859 $this->_deleteAttentions();
860 Avatar::deleteFromProfile($this, true);
862 // Warning: delete() will run on the batch objects,
863 // not on individual objects.
864 $related = array('Reply',
867 Event::handle('ProfileDeleteRelated', array($this, &$related));
869 foreach ($related as $cls) {
871 $inst->profile_id = $this->id;
875 return parent::delete($useWhere);
878 function _deleteNotices()
880 $notice = new Notice();
881 $notice->profile_id = $this->id;
883 if ($notice->find()) {
884 while ($notice->fetch()) {
885 $other = clone($notice);
891 function _deleteSubscriptions()
893 $sub = new Subscription();
894 $sub->subscriber = $this->id;
898 while ($sub->fetch()) {
899 $other = Profile::getKV('id', $sub->subscribed);
903 if ($other->id == $this->id) {
906 Subscription::cancel($this, $other);
909 $subd = new Subscription();
910 $subd->subscribed = $this->id;
913 while ($subd->fetch()) {
914 $other = Profile::getKV('id', $subd->subscriber);
918 if ($other->id == $this->id) {
921 Subscription::cancel($other, $this);
924 $self = new Subscription();
926 $self->subscriber = $this->id;
927 $self->subscribed = $this->id;
932 function _deleteMessages()
934 $msg = new Message();
935 $msg->from_profile = $this->id;
938 $msg = new Message();
939 $msg->to_profile = $this->id;
943 function _deleteTags()
945 $tag = new Profile_tag();
946 $tag->tagged = $this->id;
950 function _deleteBlocks()
952 $block = new Profile_block();
953 $block->blocked = $this->id;
956 $block = new Group_block();
957 $block->blocked = $this->id;
961 function _deleteAttentions()
963 $att = new Attention();
964 $att->profile_id = $this->getID();
967 while ($att->fetch()) {
968 // Can't do delete() on the object directly since it won't remove all of it
969 $other = clone($att);
975 // XXX: identical to Notice::getLocation.
977 public function getLocation()
981 if (!empty($this->location_id) && !empty($this->location_ns)) {
982 $location = Location::fromId($this->location_id, $this->location_ns);
985 if (is_null($location)) { // no ID, or Location::fromId() failed
986 if (!empty($this->lat) && !empty($this->lon)) {
987 $location = Location::fromLatLon($this->lat, $this->lon);
991 if (is_null($location)) { // still haven't found it!
992 if (!empty($this->location)) {
993 $location = Location::fromName($this->location);
1000 public function shareLocation()
1002 $cfg = common_config('location', 'share');
1004 if ($cfg == 'always') {
1006 } else if ($cfg == 'never') {
1009 $share = common_config('location', 'sharedefault');
1011 // Check if user has a personal setting for this
1012 $prefs = User_location_prefs::getKV('user_id', $this->id);
1014 if (!empty($prefs)) {
1015 $share = $prefs->share_location;
1023 function hasRole($name)
1026 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1027 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1029 $has_role = !empty($role);
1030 Event::handle('EndHasRole', array($this, $name, $has_role));
1035 function grantRole($name)
1037 if (Event::handle('StartGrantRole', array($this, $name))) {
1039 $role = new Profile_role();
1041 $role->profile_id = $this->id;
1042 $role->role = $name;
1043 $role->created = common_sql_now();
1045 $result = $role->insert();
1048 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1051 if ($name == 'owner') {
1052 User::blow('user:site_owner');
1055 Event::handle('EndGrantRole', array($this, $name));
1061 function revokeRole($name)
1063 if (Event::handle('StartRevokeRole', array($this, $name))) {
1065 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1069 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1070 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1071 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1074 $result = $role->delete();
1077 common_log_db_error($role, 'DELETE', __FILE__);
1078 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1079 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1080 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1083 if ($name == 'owner') {
1084 User::blow('user:site_owner');
1087 Event::handle('EndRevokeRole', array($this, $name));
1093 function isSandboxed()
1095 return $this->hasRole(Profile_role::SANDBOXED);
1098 function isSilenced()
1100 return $this->hasRole(Profile_role::SILENCED);
1105 $this->grantRole(Profile_role::SANDBOXED);
1108 function unsandbox()
1110 $this->revokeRole(Profile_role::SANDBOXED);
1115 $this->grantRole(Profile_role::SILENCED);
1116 if (common_config('notice', 'hidespam')) {
1117 $this->flushVisibility();
1121 function unsilence()
1123 $this->revokeRole(Profile_role::SILENCED);
1124 if (common_config('notice', 'hidespam')) {
1125 $this->flushVisibility();
1129 function flushVisibility()
1132 $stream = new ProfileNoticeStream($this, $this);
1133 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1134 foreach ($ids as $id) {
1135 self::blow('notice:in-scope-for:%d:null', $id);
1140 * Does this user have the right to do X?
1142 * With our role-based authorization, this is merely a lookup for whether the user
1143 * has a particular role. The implementation currently uses a switch statement
1144 * to determine if the user has the pre-defined role to exercise the right. Future
1145 * implementations may allow per-site roles, and different mappings of roles to rights.
1147 * @param $right string Name of the right, usually a constant in class Right
1148 * @return boolean whether the user has the right in question
1150 public function hasRight($right)
1154 if ($this->hasRole(Profile_role::DELETED)) {
1158 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1161 case Right::DELETEOTHERSNOTICE:
1162 case Right::MAKEGROUPADMIN:
1163 case Right::SANDBOXUSER:
1164 case Right::SILENCEUSER:
1165 case Right::DELETEUSER:
1166 case Right::DELETEGROUP:
1167 case Right::TRAINSPAM:
1168 case Right::REVIEWSPAM:
1169 $result = $this->hasRole(Profile_role::MODERATOR);
1171 case Right::CONFIGURESITE:
1172 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1174 case Right::GRANTROLE:
1175 case Right::REVOKEROLE:
1176 $result = $this->hasRole(Profile_role::OWNER);
1178 case Right::NEWNOTICE:
1179 case Right::NEWMESSAGE:
1180 case Right::SUBSCRIBE:
1181 case Right::CREATEGROUP:
1182 $result = !$this->isSilenced();
1184 case Right::PUBLICNOTICE:
1185 case Right::EMAILONREPLY:
1186 case Right::EMAILONSUBSCRIBE:
1187 case Right::EMAILONFAVE:
1188 $result = !$this->isSandboxed();
1190 case Right::WEBLOGIN:
1191 $result = !$this->isSilenced();
1194 $result = !$this->isSilenced();
1196 case Right::BACKUPACCOUNT:
1197 $result = common_config('profile', 'backup');
1199 case Right::RESTOREACCOUNT:
1200 $result = common_config('profile', 'restore');
1202 case Right::DELETEACCOUNT:
1203 $result = common_config('profile', 'delete');
1205 case Right::MOVEACCOUNT:
1206 $result = common_config('profile', 'move');
1216 // FIXME: Can't put Notice typing here due to ArrayWrapper
1217 public function hasRepeated($notice)
1219 // XXX: not really a pkey, but should work
1221 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1222 'repeat_of' => $notice->id));
1224 return !empty($notice);
1228 * Returns an XML string fragment with limited profile information
1229 * as an Atom <author> element.
1231 * Assumes that Atom has been previously set up as the base namespace.
1233 * @param Profile $cur the current authenticated user
1237 function asAtomAuthor($cur = null)
1239 $xs = new XMLStringer(true);
1241 $xs->elementStart('author');
1242 $xs->element('name', null, $this->nickname);
1243 $xs->element('uri', null, $this->getUri());
1246 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1247 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1248 $xs->element('statusnet:profile_info', $attrs, null);
1250 $xs->elementEnd('author');
1252 return $xs->getString();
1256 * Extra profile info for atom entries
1258 * Clients use some extra profile info in the atom stream.
1259 * This gives it to them.
1261 * @param User $cur Current user
1263 * @return array representation of <statusnet:profile_info> element or null
1266 function profileInfo($cur)
1268 $profileInfoAttr = array('local_id' => $this->id);
1271 // Whether the current user is a subscribed to this profile
1272 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1273 // Whether the current user is has blocked this profile
1274 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1277 return array('statusnet:profile_info', $profileInfoAttr, null);
1281 * Returns an XML string fragment with profile information as an
1282 * Activity Streams <activity:actor> element.
1284 * Assumes that 'activity' namespace has been previously defined.
1288 function asActivityActor()
1290 return $this->asActivityNoun('actor');
1294 * Returns an XML string fragment with profile information as an
1295 * Activity Streams noun object with the given element type.
1297 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1298 * previously defined.
1300 * @param string $element one of 'actor', 'subject', 'object', 'target'
1304 function asActivityNoun($element)
1306 $noun = ActivityObject::fromProfile($this);
1307 return $noun->asString('activity:' . $element);
1311 * Returns the profile's canonical url, not necessarily a uri/unique id
1313 * @return string $profileurl
1315 public function getUrl()
1317 if (empty($this->profileurl) ||
1318 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1319 throw new InvalidUrlException($this->profileurl);
1321 return $this->profileurl;
1324 public function getNickname()
1326 return $this->nickname;
1330 * Returns the best URI for a profile. Plugins may override.
1332 * @return string $uri
1334 public function getUri()
1338 // give plugins a chance to set the URI
1339 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1341 // check for a local user first
1342 $user = User::getKV('id', $this->id);
1343 if ($user instanceof User) {
1344 $uri = $user->getUri();
1347 Event::handle('EndGetProfileUri', array($this, &$uri));
1354 * Returns an assumed acct: URI for a profile. Plugins are required.
1356 * @return string $uri
1358 public function getAcctUri()
1362 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1363 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1366 if ($acct === null) {
1367 throw new ProfileNoAcctUriException($this);
1373 function hasBlocked($other)
1375 $block = Profile_block::exists($this, $other);
1376 return !empty($block);
1379 function getAtomFeed()
1383 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1384 $user = User::getKV('id', $this->id);
1385 if (!empty($user)) {
1386 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1387 'format' => 'atom'));
1389 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1396 * Get a Profile object by URI. Will call external plugins for help
1397 * using the event StartGetProfileFromURI.
1399 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1401 static function fromUri($uri)
1405 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1406 // Get a local user when plugin lookup (like OStatus) fails
1407 $user = User::getKV('uri', $uri);
1408 if ($user instanceof User) {
1409 $profile = $user->getProfile();
1411 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1414 if (!$profile instanceof Profile) {
1415 throw new UnknownUriException($uri);
1421 function canRead(Notice $notice)
1423 if ($notice->scope & Notice::SITE_SCOPE) {
1424 $user = $this->getUser();
1430 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1431 $replies = $notice->getReplies();
1433 if (!in_array($this->id, $replies)) {
1434 $groups = $notice->getGroups();
1438 foreach ($groups as $group) {
1439 if ($this->isMember($group)) {
1451 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1452 $author = $notice->getProfile();
1453 if (!Subscription::exists($this, $author)) {
1461 static function current()
1463 $user = common_current_user();
1467 $profile = $user->getProfile();
1473 * Magic function called at serialize() time.
1475 * We use this to drop a couple process-specific references
1476 * from DB_DataObject which can cause trouble in future
1479 * @return array of variable names to include in serialization.
1484 $vars = parent::__sleep();
1485 $skip = array('_user', '_group');
1486 return array_diff($vars, $skip);
1489 public function getProfile()
1495 * This will perform shortenLinks with the connected User object.
1497 * Won't work on remote profiles or groups, so expect a
1498 * NoSuchUserException if you don't know it's a local User.
1500 * @param string $text String to shorten
1501 * @param boolean $always Disrespect minimum length etc.
1503 * @return string link-shortened $text
1505 public function shortenLinks($text, $always=false)
1507 return $this->getUser()->shortenLinks($text, $always);