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 class Profile extends Managed_DataObject
28 /* the code below is auto generated do not remove the above tag */
30 public $__table = 'profile'; // table name
31 public $id; // int(4) primary_key not_null
32 public $nickname; // varchar(64) multiple_key not_null
33 public $fullname; // varchar(255) multiple_key
34 public $profileurl; // varchar(255)
35 public $homepage; // varchar(255) multiple_key
36 public $bio; // text() multiple_key
37 public $location; // varchar(255) multiple_key
38 public $lat; // decimal(10,7)
39 public $lon; // decimal(10,7)
40 public $location_id; // int(4)
41 public $location_ns; // int(4)
42 public $created; // datetime() not_null
43 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
45 public static function schemaDef()
48 'description' => 'local and remote users have profiles',
50 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
51 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
52 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
53 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
54 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
55 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
56 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
57 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
58 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
59 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
60 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
62 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
63 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
65 'primary key' => array('id'),
67 'profile_nickname_idx' => array('nickname'),
71 // Add a fulltext index
73 if (common_config('search', 'type') == 'fulltext') {
74 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
80 /* the code above is auto generated do not remove the tag below */
83 public static function getByEmail($email)
85 // in the future, profiles should have emails stored...
86 $user = User::getKV('email', $email);
87 if (!($user instanceof User)) {
88 throw new NoSuchUserException(array('email'=>$email));
90 return $user->getProfile();
93 protected $_user = array();
95 public function getUser()
97 if (!isset($this->_user[$this->id])) {
98 $user = User::getKV('id', $this->id);
99 if (!$user instanceof User) {
100 throw new NoSuchUserException(array('id'=>$this->id));
102 $this->_user[$this->id] = $user;
104 return $this->_user[$this->id];
107 protected $_group = array();
109 public function getGroup()
111 if (!isset($this->_group[$this->id])) {
112 $group = User_group::getKV('profile_id', $this->id);
113 if (!$group instanceof User_group) {
114 throw new NoSuchGroupException(array('profile_id'=>$this->id));
116 $this->_group[$this->id] = $group;
118 return $this->_group[$this->id];
121 public function isGroup()
126 } catch (NoSuchGroupException $e) {
131 public function isLocal()
135 } catch (NoSuchUserException $e) {
141 public function getObjectType()
143 // FIXME: More types... like peopletags and whatever
144 if ($this->isGroup()) {
145 return ActivityObject::GROUP;
147 return ActivityObject::PERSON;
151 public function getAvatar($width, $height=null)
153 return Avatar::byProfile($this, $width, $height);
156 public function setOriginal($filename)
158 $imagefile = new ImageFile($this->id, Avatar::path($filename));
160 $avatar = new Avatar();
161 $avatar->profile_id = $this->id;
162 $avatar->width = $imagefile->width;
163 $avatar->height = $imagefile->height;
164 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
165 $avatar->filename = $filename;
166 $avatar->original = true;
167 $avatar->url = Avatar::url($filename);
168 $avatar->created = common_sql_now();
170 // XXX: start a transaction here
171 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
172 // If we can't delete the old avatars, let's abort right here.
173 @unlink(Avatar::path($filename));
181 * Gets either the full name (if filled) or the nickname.
185 function getBestName()
187 return ($this->fullname) ? $this->fullname : $this->nickname;
191 * Takes the currently scoped profile into account to give a name
192 * to list in notice streams. Preferences may differ between profiles.
194 function getStreamName()
196 $user = common_current_user();
197 if ($user instanceof User && $user->streamNicknames()) {
198 return $this->nickname;
201 return $this->getBestName();
205 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
206 * if no fullname is provided.
210 function getFancyName()
212 if ($this->fullname) {
213 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
214 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
216 return $this->nickname;
221 * Get the most recent notice posted by this user, if any.
223 * @return mixed Notice or null
225 function getCurrentNotice()
227 $notice = $this->getNotices(0, 1);
229 if ($notice->fetch()) {
230 if ($notice instanceof ArrayWrapper) {
231 // hack for things trying to work with single notices
232 return $notice->_items[0];
240 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
242 $stream = new TaggedProfileNoticeStream($this, $tag);
244 return $stream->getNotices($offset, $limit, $since_id, $max_id);
247 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
249 $stream = new ProfileNoticeStream($this, $scoped);
251 return $stream->getNotices($offset, $limit, $since_id, $max_id);
254 function isMember(User_group $group)
256 $groups = $this->getGroups(0, null);
257 while ($groups instanceof User_group && $groups->fetch()) {
258 if ($groups->id == $group->id) {
265 function isAdmin(User_group $group)
267 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
268 'group_id' => $group->id));
269 return (!empty($gm) && $gm->is_admin);
272 function isPendingMember($group)
274 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
275 'group_id' => $group->id));
276 return !empty($request);
279 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
283 $keypart = sprintf('profile:groups:%d', $this->id);
285 $idstring = self::cacheGet($keypart);
287 if ($idstring !== false) {
288 $ids = explode(',', $idstring);
290 $gm = new Group_member();
292 $gm->profile_id = $this->id;
295 while ($gm->fetch()) {
296 $ids[] = $gm->group_id;
300 self::cacheSet($keypart, implode(',', $ids));
303 if (!is_null($offset) && !is_null($limit)) {
304 $ids = array_slice($ids, $offset, $limit);
308 return User_group::multiGet('id', $ids);
309 } catch (NoResultException $e) {
310 return null; // throw exception when we handle it everywhere
314 function getGroupCount() {
315 $groups = $this->getGroups(0, null);
316 return $groups instanceof User_group
321 function isTagged($peopletag)
323 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
324 'tagged' => $this->id,
325 'tag' => $peopletag->tag));
329 function canTag($tagged)
331 if (empty($tagged)) {
335 if ($tagged->id == $this->id) {
339 $all = common_config('peopletag', 'allow_tagging', 'all');
340 $local = common_config('peopletag', 'allow_tagging', 'local');
341 $remote = common_config('peopletag', 'allow_tagging', 'remote');
342 $subs = common_config('peopletag', 'allow_tagging', 'subs');
348 $tagged_user = $tagged->getUser();
349 if (!empty($tagged_user)) {
354 return (Subscription::exists($this, $tagged) ||
355 Subscription::exists($tagged, $this));
356 } else if ($remote) {
362 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
366 $keypart = sprintf('profile:lists:%d', $this->id);
368 $idstr = self::cacheGet($keypart);
370 if ($idstr !== false) {
371 $ids = explode(',', $idstr);
373 $list = new Profile_list();
375 $list->selectAdd('id');
376 $list->tagger = $this->id;
377 $list->selectAdd('id as "cursor"');
380 $list->whereAdd('id > '.$since_id);
384 $list->whereAdd('id <= '.$max_id);
387 if($offset>=0 && !is_null($limit)) {
388 $list->limit($offset, $limit);
391 $list->orderBy('id DESC');
394 while ($list->fetch()) {
399 self::cacheSet($keypart, implode(',', $ids));
402 $showPrivate = (($auth_user instanceof User ||
403 $auth_user instanceof Profile) &&
404 $auth_user->id === $this->id);
408 foreach ($ids as $id) {
409 $list = Profile_list::getKV('id', $id);
411 ($showPrivate || !$list->private)) {
413 if (!isset($list->cursor)) {
414 $list->cursor = $list->id;
421 return new ArrayWrapper($lists);
425 * Get tags that other people put on this profile, in reverse-chron order
427 * @param (Profile|User) $auth_user Authorized user (used for privacy)
428 * @param int $offset Offset from latest
429 * @param int $limit Max number to get
430 * @param datetime $since_id max date
431 * @param datetime $max_id min date
433 * @return Profile_list resulting lists
436 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
438 $list = new Profile_list();
440 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
441 'from profile_tag join profile_list '.
442 'on (profile_tag.tagger = profile_list.tagger ' .
443 ' and profile_tag.tag = profile_list.tag) ' .
444 'where profile_tag.tagged = %d ',
448 if ($auth_user instanceof User || $auth_user instanceof Profile) {
449 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
450 'OR ( profile_list.tagger = %d AND ' .
451 'profile_list.private = true ) )',
454 $qry .= 'AND profile_list.private = 0 ';
458 $qry .= sprintf('AND (cursor > %d) ', $since_id);
462 $qry .= sprintf('AND (cursor < %d) ', $max_id);
465 $qry .= 'ORDER BY profile_tag.modified DESC ';
467 if ($offset >= 0 && !is_null($limit)) {
468 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
475 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
477 $tags = new Profile_list();
478 $tags->private = true;
479 $tags->tagger = $this->id;
482 $tags->whereAdd('id > '.$since_id);
486 $tags->whereAdd('id <= '.$max_id);
489 if($offset>=0 && !is_null($limit)) {
490 $tags->limit($offset, $limit);
493 $tags->orderBy('id DESC');
499 function hasLocalTags()
501 $tags = new Profile_tag();
503 $tags->joinAdd(array('tagger', 'user:id'));
504 $tags->whereAdd('tagged = '.$this->id);
505 $tags->whereAdd('tagger != '.$this->id);
510 return ($tags->N == 0) ? false : true;
513 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
515 $lists = new Profile_list();
516 $subs = new Profile_tag_subscription();
518 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
520 #@fixme: postgres (round(date_part('epoch', my_date)))
521 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
523 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
526 $lists->whereAdd('cursor > '.$since_id);
530 $lists->whereAdd('cursor <= '.$max_id);
533 if($offset>=0 && !is_null($limit)) {
534 $lists->limit($offset, $limit);
537 $lists->orderBy('"cursor" DESC');
544 * Request to join the given group.
545 * May throw exceptions on failure.
547 * @param User_group $group
548 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
550 function joinGroup(User_group $group)
553 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
554 $join = Group_join_queue::saveNew($this, $group);
556 if (Event::handle('StartJoinGroup', array($group, $this))) {
557 $join = Group_member::join($group->id, $this->id);
558 self::blow('profile:groups:%d', $this->id);
559 self::blow('group:member_ids:%d', $group->id);
560 self::blow('group:member_count:%d', $group->id);
561 Event::handle('EndJoinGroup', array($group, $this));
565 // Send any applicable notifications...
572 * Leave a group that this profile is a member of.
574 * @param User_group $group
576 function leaveGroup(User_group $group)
578 if (Event::handle('StartLeaveGroup', array($group, $this))) {
579 Group_member::leave($group->id, $this->id);
580 self::blow('profile:groups:%d', $this->id);
581 self::blow('group:member_ids:%d', $group->id);
582 self::blow('group:member_count:%d', $group->id);
583 Event::handle('EndLeaveGroup', array($group, $this));
587 function avatarUrl($size=AVATAR_PROFILE_SIZE)
589 return Avatar::urlByProfile($this, $size);
592 function getSubscribed($offset=0, $limit=null)
594 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
596 $profiles = Profile::multiGet('id', $subs);
597 } catch (NoResultException $e) {
603 function getSubscribers($offset=0, $limit=null)
605 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
607 $profiles = Profile::multiGet('id', $subs);
608 } catch (NoResultException $e) {
614 function getTaggedSubscribers($tag, $offset=0, $limit=null)
617 'SELECT profile.* ' .
618 'FROM profile JOIN subscription ' .
619 'ON profile.id = subscription.subscriber ' .
620 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
621 'AND profile_tag.tagger = subscription.subscribed) ' .
622 'WHERE subscription.subscribed = %d ' .
623 "AND profile_tag.tag = '%s' " .
624 'AND subscription.subscribed != subscription.subscriber ' .
625 'ORDER BY subscription.created DESC ';
628 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
631 $profile = new Profile();
633 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
638 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
641 'SELECT profile.* ' .
642 'FROM profile JOIN subscription ' .
643 'ON profile.id = subscription.subscribed ' .
644 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
645 'AND profile_tag.tagger = subscription.subscriber) ' .
646 'WHERE subscription.subscriber = %d ' .
647 "AND profile_tag.tag = '%s' " .
648 'AND subscription.subscribed != subscription.subscriber ' .
649 'ORDER BY subscription.created DESC ';
651 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
653 $profile = new Profile();
655 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
661 * Get pending subscribers, who have not yet been approved.
667 function getRequests($offset=0, $limit=null)
670 'SELECT profile.* ' .
671 'FROM profile JOIN subscription_queue '.
672 'ON profile.id = subscription_queue.subscriber ' .
673 'WHERE subscription_queue.subscribed = %d ' .
674 'ORDER BY subscription_queue.created DESC ';
676 if ($limit != null) {
677 if (common_config('db','type') == 'pgsql') {
678 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
680 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
684 $members = new Profile();
686 $members->query(sprintf($qry, $this->id));
690 function subscriptionCount()
692 $c = Cache::instance();
695 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
696 if (is_integer($cnt)) {
701 $sub = new Subscription();
702 $sub->subscriber = $this->id;
704 $cnt = (int) $sub->count('distinct subscribed');
706 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
709 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
715 function subscriberCount()
717 $c = Cache::instance();
719 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
720 if (is_integer($cnt)) {
725 $sub = new Subscription();
726 $sub->subscribed = $this->id;
727 $sub->whereAdd('subscriber != subscribed');
728 $cnt = (int) $sub->count('distinct subscriber');
731 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
738 * Is this profile subscribed to another profile?
740 * @param Profile $other
743 function isSubscribed(Profile $other)
745 return Subscription::exists($this, $other);
749 * Check if a pending subscription request is outstanding for this...
751 * @param Profile $other
754 function hasPendingSubscription(Profile $other)
756 return Subscription_queue::exists($this, $other);
760 * Are these two profiles subscribed to each other?
762 * @param Profile $other
765 function mutuallySubscribed(Profile $other)
767 return $this->isSubscribed($other) &&
768 $other->isSubscribed($this);
771 function noticeCount()
773 $c = Cache::instance();
776 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
777 if (is_integer($cnt)) {
782 $notices = new Notice();
783 $notices->profile_id = $this->id;
784 $cnt = (int) $notices->count('distinct id');
787 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
793 function blowSubscriberCount()
795 $c = Cache::instance();
797 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
801 function blowSubscriptionCount()
803 $c = Cache::instance();
805 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
809 function blowNoticeCount()
811 $c = Cache::instance();
813 $c->delete(Cache::key('profile:notice_count:'.$this->id));
817 static function maxBio()
819 $biolimit = common_config('profile', 'biolimit');
820 // null => use global limit (distinct from 0!)
821 if (is_null($biolimit)) {
822 $biolimit = common_config('site', 'textlimit');
827 static function bioTooLong($bio)
829 $biolimit = self::maxBio();
830 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
833 function update($dataObject=false)
835 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
837 $local = $this->getUser();
838 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
839 $origuser = clone($local);
840 $local->nickname = $this->nickname;
841 $result = $local->updateKeys($origuser);
842 if ($result === false) {
843 common_log_db_error($local, 'UPDATE', __FILE__);
844 // TRANS: Server error thrown when user profile settings could not be updated.
845 throw new ServerException(_('Could not update user nickname.'));
848 // Clear the site owner, in case nickname changed
849 if ($local->hasRole(Profile_role::OWNER)) {
850 User::blow('user:site_owner');
852 } catch (NoSuchUserException $e) {
857 return parent::update($dataObject);
860 function delete($useWhere=false)
862 $this->_deleteNotices();
863 $this->_deleteSubscriptions();
864 $this->_deleteTags();
865 $this->_deleteBlocks();
866 $this->_deleteAttentions();
867 Avatar::deleteFromProfile($this, true);
869 // Warning: delete() will run on the batch objects,
870 // not on individual objects.
871 $related = array('Reply',
874 Event::handle('ProfileDeleteRelated', array($this, &$related));
876 foreach ($related as $cls) {
878 $inst->profile_id = $this->id;
882 return parent::delete($useWhere);
885 function _deleteNotices()
887 $notice = new Notice();
888 $notice->profile_id = $this->id;
890 if ($notice->find()) {
891 while ($notice->fetch()) {
892 $other = clone($notice);
898 function _deleteSubscriptions()
900 $sub = new Subscription();
901 $sub->subscriber = $this->id;
905 while ($sub->fetch()) {
906 $other = Profile::getKV('id', $sub->subscribed);
910 if ($other->id == $this->id) {
913 Subscription::cancel($this, $other);
916 $subd = new Subscription();
917 $subd->subscribed = $this->id;
920 while ($subd->fetch()) {
921 $other = Profile::getKV('id', $subd->subscriber);
925 if ($other->id == $this->id) {
928 Subscription::cancel($other, $this);
931 $self = new Subscription();
933 $self->subscriber = $this->id;
934 $self->subscribed = $this->id;
939 function _deleteTags()
941 $tag = new Profile_tag();
942 $tag->tagged = $this->id;
946 function _deleteBlocks()
948 $block = new Profile_block();
949 $block->blocked = $this->id;
952 $block = new Group_block();
953 $block->blocked = $this->id;
957 function _deleteAttentions()
959 $att = new Attention();
960 $att->profile_id = $this->getID();
963 while ($att->fetch()) {
964 // Can't do delete() on the object directly since it won't remove all of it
965 $other = clone($att);
971 // XXX: identical to Notice::getLocation.
973 public function getLocation()
977 if (!empty($this->location_id) && !empty($this->location_ns)) {
978 $location = Location::fromId($this->location_id, $this->location_ns);
981 if (is_null($location)) { // no ID, or Location::fromId() failed
982 if (!empty($this->lat) && !empty($this->lon)) {
983 $location = Location::fromLatLon($this->lat, $this->lon);
987 if (is_null($location)) { // still haven't found it!
988 if (!empty($this->location)) {
989 $location = Location::fromName($this->location);
996 public function shareLocation()
998 $cfg = common_config('location', 'share');
1000 if ($cfg == 'always') {
1002 } else if ($cfg == 'never') {
1005 $share = common_config('location', 'sharedefault');
1007 // Check if user has a personal setting for this
1008 $prefs = User_location_prefs::getKV('user_id', $this->id);
1010 if (!empty($prefs)) {
1011 $share = $prefs->share_location;
1019 function hasRole($name)
1022 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1023 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1025 $has_role = !empty($role);
1026 Event::handle('EndHasRole', array($this, $name, $has_role));
1031 function grantRole($name)
1033 if (Event::handle('StartGrantRole', array($this, $name))) {
1035 $role = new Profile_role();
1037 $role->profile_id = $this->id;
1038 $role->role = $name;
1039 $role->created = common_sql_now();
1041 $result = $role->insert();
1044 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1047 if ($name == 'owner') {
1048 User::blow('user:site_owner');
1051 Event::handle('EndGrantRole', array($this, $name));
1057 function revokeRole($name)
1059 if (Event::handle('StartRevokeRole', array($this, $name))) {
1061 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1065 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1066 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1067 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1070 $result = $role->delete();
1073 common_log_db_error($role, 'DELETE', __FILE__);
1074 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1075 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1076 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1079 if ($name == 'owner') {
1080 User::blow('user:site_owner');
1083 Event::handle('EndRevokeRole', array($this, $name));
1089 function isSandboxed()
1091 return $this->hasRole(Profile_role::SANDBOXED);
1094 function isSilenced()
1096 return $this->hasRole(Profile_role::SILENCED);
1101 $this->grantRole(Profile_role::SANDBOXED);
1104 function unsandbox()
1106 $this->revokeRole(Profile_role::SANDBOXED);
1111 $this->grantRole(Profile_role::SILENCED);
1112 if (common_config('notice', 'hidespam')) {
1113 $this->flushVisibility();
1117 function unsilence()
1119 $this->revokeRole(Profile_role::SILENCED);
1120 if (common_config('notice', 'hidespam')) {
1121 $this->flushVisibility();
1125 function flushVisibility()
1128 $stream = new ProfileNoticeStream($this, $this);
1129 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1130 foreach ($ids as $id) {
1131 self::blow('notice:in-scope-for:%d:null', $id);
1136 * Does this user have the right to do X?
1138 * With our role-based authorization, this is merely a lookup for whether the user
1139 * has a particular role. The implementation currently uses a switch statement
1140 * to determine if the user has the pre-defined role to exercise the right. Future
1141 * implementations may allow per-site roles, and different mappings of roles to rights.
1143 * @param $right string Name of the right, usually a constant in class Right
1144 * @return boolean whether the user has the right in question
1146 public function hasRight($right)
1150 if ($this->hasRole(Profile_role::DELETED)) {
1154 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1157 case Right::DELETEOTHERSNOTICE:
1158 case Right::MAKEGROUPADMIN:
1159 case Right::SANDBOXUSER:
1160 case Right::SILENCEUSER:
1161 case Right::DELETEUSER:
1162 case Right::DELETEGROUP:
1163 case Right::TRAINSPAM:
1164 case Right::REVIEWSPAM:
1165 $result = $this->hasRole(Profile_role::MODERATOR);
1167 case Right::CONFIGURESITE:
1168 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1170 case Right::GRANTROLE:
1171 case Right::REVOKEROLE:
1172 $result = $this->hasRole(Profile_role::OWNER);
1174 case Right::NEWNOTICE:
1175 case Right::NEWMESSAGE:
1176 case Right::SUBSCRIBE:
1177 case Right::CREATEGROUP:
1178 $result = !$this->isSilenced();
1180 case Right::PUBLICNOTICE:
1181 case Right::EMAILONREPLY:
1182 case Right::EMAILONSUBSCRIBE:
1183 case Right::EMAILONFAVE:
1184 $result = !$this->isSandboxed();
1186 case Right::WEBLOGIN:
1187 $result = !$this->isSilenced();
1190 $result = !$this->isSilenced();
1192 case Right::BACKUPACCOUNT:
1193 $result = common_config('profile', 'backup');
1195 case Right::RESTOREACCOUNT:
1196 $result = common_config('profile', 'restore');
1198 case Right::DELETEACCOUNT:
1199 $result = common_config('profile', 'delete');
1201 case Right::MOVEACCOUNT:
1202 $result = common_config('profile', 'move');
1212 // FIXME: Can't put Notice typing here due to ArrayWrapper
1213 public function hasRepeated($notice)
1215 // XXX: not really a pkey, but should work
1217 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1218 'repeat_of' => $notice->id));
1220 return !empty($notice);
1224 * Returns an XML string fragment with limited profile information
1225 * as an Atom <author> element.
1227 * Assumes that Atom has been previously set up as the base namespace.
1229 * @param Profile $cur the current authenticated user
1233 function asAtomAuthor($cur = null)
1235 $xs = new XMLStringer(true);
1237 $xs->elementStart('author');
1238 $xs->element('name', null, $this->nickname);
1239 $xs->element('uri', null, $this->getUri());
1242 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1243 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1244 $xs->element('statusnet:profile_info', $attrs, null);
1246 $xs->elementEnd('author');
1248 return $xs->getString();
1252 * Extra profile info for atom entries
1254 * Clients use some extra profile info in the atom stream.
1255 * This gives it to them.
1257 * @param Profile $scoped The currently logged in/scoped profile
1259 * @return array representation of <statusnet:profile_info> element or null
1262 function profileInfo(Profile $scoped=null)
1264 $profileInfoAttr = array('local_id' => $this->id);
1266 if ($scoped instanceof Profile) {
1267 // Whether the current user is a subscribed to this profile
1268 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1269 // Whether the current user is has blocked this profile
1270 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1273 return array('statusnet:profile_info', $profileInfoAttr, null);
1277 * Returns an XML string fragment with profile information as an
1278 * Activity Streams <activity:actor> element.
1280 * Assumes that 'activity' namespace has been previously defined.
1284 function asActivityActor()
1286 return $this->asActivityNoun('actor');
1290 * Returns an XML string fragment with profile information as an
1291 * Activity Streams noun object with the given element type.
1293 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1294 * previously defined.
1296 * @param string $element one of 'actor', 'subject', 'object', 'target'
1300 function asActivityNoun($element)
1302 $noun = $this->asActivityObject();
1303 return $noun->asString('activity:' . $element);
1306 public function asActivityObject()
1308 $object = new ActivityObject();
1310 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1311 $object->type = $this->getObjectType();
1312 $object->id = $this->getUri();
1313 $object->title = $this->getBestName();
1314 $object->link = $this->getUrl();
1315 $object->summary = $this->getDescription();
1318 $avatar = Avatar::getUploaded($this);
1319 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1320 } catch (NoAvatarException $e) {
1321 // Could not find an original avatar to link
1325 AVATAR_PROFILE_SIZE,
1330 foreach ($sizes as $size) {
1333 $avatar = Avatar::byProfile($this, $size);
1334 $alink = AvatarLink::fromAvatar($avatar);
1335 } catch (NoAvatarException $e) {
1336 $alink = new AvatarLink();
1337 $alink->type = 'image/png';
1338 $alink->height = $size;
1339 $alink->width = $size;
1340 $alink->url = Avatar::defaultImage($size);
1343 $object->avatarLinks[] = $alink;
1346 if (isset($this->lat) && isset($this->lon)) {
1347 $object->geopoint = (float)$this->lat
1348 . ' ' . (float)$this->lon;
1351 $object->poco = PoCo::fromProfile($this);
1353 if ($this->isLocal()) {
1354 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1357 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1364 * Returns the profile's canonical url, not necessarily a uri/unique id
1366 * @return string $profileurl
1368 public function getUrl()
1370 if (empty($this->profileurl) ||
1371 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1372 throw new InvalidUrlException($this->profileurl);
1374 return $this->profileurl;
1377 public function getNickname()
1379 return $this->nickname;
1382 public function getDescription()
1388 * Returns the best URI for a profile. Plugins may override.
1390 * @return string $uri
1392 public function getUri()
1396 // give plugins a chance to set the URI
1397 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1399 // check for a local user first
1400 $user = User::getKV('id', $this->id);
1401 if ($user instanceof User) {
1402 $uri = $user->getUri();
1405 Event::handle('EndGetProfileUri', array($this, &$uri));
1412 * Returns an assumed acct: URI for a profile. Plugins are required.
1414 * @return string $uri
1416 public function getAcctUri()
1420 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1421 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1424 if ($acct === null) {
1425 throw new ProfileNoAcctUriException($this);
1431 function hasBlocked($other)
1433 $block = Profile_block::exists($this, $other);
1434 return !empty($block);
1437 function getAtomFeed()
1441 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1442 $user = User::getKV('id', $this->id);
1443 if (!empty($user)) {
1444 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1445 'format' => 'atom'));
1447 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1454 * Get a Profile object by URI. Will call external plugins for help
1455 * using the event StartGetProfileFromURI.
1457 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1459 static function fromUri($uri)
1463 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1464 // Get a local user when plugin lookup (like OStatus) fails
1465 $user = User::getKV('uri', $uri);
1466 if ($user instanceof User) {
1467 $profile = $user->getProfile();
1469 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1472 if (!$profile instanceof Profile) {
1473 throw new UnknownUriException($uri);
1479 function canRead(Notice $notice)
1481 if ($notice->scope & Notice::SITE_SCOPE) {
1482 $user = $this->getUser();
1488 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1489 $replies = $notice->getReplies();
1491 if (!in_array($this->id, $replies)) {
1492 $groups = $notice->getGroups();
1496 foreach ($groups as $group) {
1497 if ($this->isMember($group)) {
1509 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1510 $author = $notice->getProfile();
1511 if (!Subscription::exists($this, $author)) {
1519 static function current()
1521 $user = common_current_user();
1525 $profile = $user->getProfile();
1531 * Magic function called at serialize() time.
1533 * We use this to drop a couple process-specific references
1534 * from DB_DataObject which can cause trouble in future
1537 * @return array of variable names to include in serialization.
1542 $vars = parent::__sleep();
1543 $skip = array('_user', '_group');
1544 return array_diff($vars, $skip);
1547 public function getProfile()
1553 * This will perform shortenLinks with the connected User object.
1555 * Won't work on remote profiles or groups, so expect a
1556 * NoSuchUserException if you don't know it's a local User.
1558 * @param string $text String to shorten
1559 * @param boolean $always Disrespect minimum length etc.
1561 * @return string link-shortened $text
1563 public function shortenLinks($text, $always=false)
1565 return $this->getUser()->shortenLinks($text, $always);
1568 public function delPref($namespace, $topic) {
1569 return Profile_prefs::setData($this, $namespace, $topic, null);
1572 public function getPref($namespace, $topic, $default=null) {
1573 // If you want an exception to be thrown, call Profile_prefs::getData directly
1575 return Profile_prefs::getData($this, $namespace, $topic, $default);
1576 } catch (NoResultException $e) {
1581 public function setPref($namespace, $topic, $data) {
1582 return Profile_prefs::setData($this, $namespace, $topic, $data);