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('GNUSOCIAL')) { exit(1); }
23 * Table Definition for profile
25 class Profile extends Managed_DataObject
27 public $__table = 'profile'; // table name
28 public $id; // int(4) primary_key not_null
29 public $nickname; // varchar(64) multiple_key not_null
30 public $fullname; // text()
31 public $profileurl; // text()
32 public $homepage; // text()
33 public $bio; // text() multiple_key
34 public $location; // text()
35 public $lat; // decimal(10,7)
36 public $lon; // decimal(10,7)
37 public $location_id; // int(4)
38 public $location_ns; // int(4)
39 public $created; // datetime() not_null
40 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
42 public static function schemaDef()
45 'description' => 'local and remote users have profiles',
47 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
48 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8mb4_general_ci'),
49 'fullname' => array('type' => 'text', 'description' => 'display name', 'collate' => 'utf8mb4_general_ci'),
50 'profileurl' => array('type' => 'text', 'description' => 'URL, cached so we dont regenerate'),
51 'homepage' => array('type' => 'text', 'description' => 'identifying URL', 'collate' => 'utf8mb4_general_ci'),
52 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8mb4_general_ci'),
53 'location' => array('type' => 'text', 'description' => 'physical location', 'collate' => 'utf8mb4_general_ci'),
54 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
55 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
56 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
57 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
59 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
60 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
62 'primary key' => array('id'),
64 'profile_nickname_idx' => array('nickname'),
68 // Add a fulltext index
70 if (common_config('search', 'type') == 'fulltext') {
71 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
77 public static function getByEmail($email)
79 // in the future, profiles should have emails stored...
80 $user = User::getKV('email', $email);
81 if (!($user instanceof User)) {
82 throw new NoSuchUserException(array('email'=>$email));
84 return $user->getProfile();
87 protected $_user = array();
89 public function getUser()
91 if (!isset($this->_user[$this->id])) {
92 $user = User::getKV('id', $this->id);
93 if (!$user instanceof User) {
94 throw new NoSuchUserException(array('id'=>$this->id));
96 $this->_user[$this->id] = $user;
98 return $this->_user[$this->id];
101 protected $_group = array();
103 public function getGroup()
105 if (!isset($this->_group[$this->id])) {
106 $group = User_group::getKV('profile_id', $this->id);
107 if (!$group instanceof User_group) {
108 throw new NoSuchGroupException(array('profile_id'=>$this->id));
110 $this->_group[$this->id] = $group;
112 return $this->_group[$this->id];
115 public function isGroup()
120 } catch (NoSuchGroupException $e) {
125 public function isLocal()
129 } catch (NoSuchUserException $e) {
135 // Returns false if the user has no password (which will always
136 // be the case for remote users). This can be the case for OpenID
137 // logins or other mechanisms which don't store a password hash.
138 public function hasPassword()
141 return $this->getUser()->hasPassword();
142 } catch (NoSuchUserException $e) {
147 public function getObjectType()
149 // FIXME: More types... like peopletags and whatever
150 if ($this->isGroup()) {
151 return ActivityObject::GROUP;
153 return ActivityObject::PERSON;
157 public function getAvatar($width, $height=null)
159 return Avatar::byProfile($this, $width, $height);
162 public function setOriginal($filename)
164 if ($this->isGroup()) {
165 // Until Group avatars are handled just like profile avatars.
166 return $this->getGroup()->setOriginal($filename);
169 $imagefile = new ImageFile(null, Avatar::path($filename));
171 $avatar = new Avatar();
172 $avatar->profile_id = $this->id;
173 $avatar->width = $imagefile->width;
174 $avatar->height = $imagefile->height;
175 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
176 $avatar->filename = $filename;
177 $avatar->original = true;
178 $avatar->url = Avatar::url($filename);
179 $avatar->created = common_sql_now();
181 // XXX: start a transaction here
182 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
183 // If we can't delete the old avatars, let's abort right here.
184 @unlink(Avatar::path($filename));
192 * Gets either the full name (if filled) or the nickname.
196 function getBestName()
198 return ($this->fullname) ? $this->fullname : $this->nickname;
202 * Takes the currently scoped profile into account to give a name
203 * to list in notice streams. Preferences may differ between profiles.
205 function getStreamName()
207 $user = common_current_user();
208 if ($user instanceof User && $user->streamNicknames()) {
209 return $this->nickname;
212 return $this->getBestName();
216 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
217 * if no fullname is provided.
221 function getFancyName()
223 if ($this->fullname) {
224 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
225 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
227 return $this->nickname;
232 * Get the most recent notice posted by this user, if any.
234 * @return mixed Notice or null
236 function getCurrentNotice()
238 $notice = $this->getNotices(0, 1);
240 if ($notice->fetch()) {
241 if ($notice instanceof ArrayWrapper) {
242 // hack for things trying to work with single notices
243 return $notice->_items[0];
251 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
253 return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
256 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
258 $stream = new TaggedProfileNoticeStream($this, $tag);
260 return $stream->getNotices($offset, $limit, $since_id, $max_id);
263 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
265 $stream = new ProfileNoticeStream($this, $scoped);
267 return $stream->getNotices($offset, $limit, $since_id, $max_id);
270 function isMember(User_group $group)
272 $groups = $this->getGroups(0, null);
273 while ($groups instanceof User_group && $groups->fetch()) {
274 if ($groups->id == $group->id) {
281 function isAdmin(User_group $group)
283 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
284 'group_id' => $group->id));
285 return (!empty($gm) && $gm->is_admin);
288 function isPendingMember($group)
290 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
291 'group_id' => $group->id));
292 return !empty($request);
295 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
299 $keypart = sprintf('profile:groups:%d', $this->id);
301 $idstring = self::cacheGet($keypart);
303 if ($idstring !== false) {
304 $ids = explode(',', $idstring);
306 $gm = new Group_member();
308 $gm->profile_id = $this->id;
311 while ($gm->fetch()) {
312 $ids[] = $gm->group_id;
316 self::cacheSet($keypart, implode(',', $ids));
319 if (!is_null($offset) && !is_null($limit)) {
320 $ids = array_slice($ids, $offset, $limit);
324 return User_group::multiGet('id', $ids);
325 } catch (NoResultException $e) {
326 return null; // throw exception when we handle it everywhere
330 function getGroupCount() {
331 $groups = $this->getGroups(0, null);
332 return $groups instanceof User_group
337 function isTagged($peopletag)
339 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
340 'tagged' => $this->id,
341 'tag' => $peopletag->tag));
345 function canTag($tagged)
347 if (empty($tagged)) {
351 if ($tagged->id == $this->id) {
355 $all = common_config('peopletag', 'allow_tagging', 'all');
356 $local = common_config('peopletag', 'allow_tagging', 'local');
357 $remote = common_config('peopletag', 'allow_tagging', 'remote');
358 $subs = common_config('peopletag', 'allow_tagging', 'subs');
364 $tagged_user = $tagged->getUser();
365 if (!empty($tagged_user)) {
370 return (Subscription::exists($this, $tagged) ||
371 Subscription::exists($tagged, $this));
372 } else if ($remote) {
378 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
382 $keypart = sprintf('profile:lists:%d', $this->id);
384 $idstr = self::cacheGet($keypart);
386 if ($idstr !== false) {
387 $ids = explode(',', $idstr);
389 $list = new Profile_list();
391 $list->selectAdd('id');
392 $list->tagger = $this->id;
393 $list->selectAdd('id as "cursor"');
396 $list->whereAdd('id > '.$since_id);
400 $list->whereAdd('id <= '.$max_id);
403 if($offset>=0 && !is_null($limit)) {
404 $list->limit($offset, $limit);
407 $list->orderBy('id DESC');
410 while ($list->fetch()) {
415 self::cacheSet($keypart, implode(',', $ids));
418 $showPrivate = (($auth_user instanceof User ||
419 $auth_user instanceof Profile) &&
420 $auth_user->id === $this->id);
424 foreach ($ids as $id) {
425 $list = Profile_list::getKV('id', $id);
427 ($showPrivate || !$list->private)) {
429 if (!isset($list->cursor)) {
430 $list->cursor = $list->id;
437 return new ArrayWrapper($lists);
441 * Get tags that other people put on this profile, in reverse-chron order
443 * @param (Profile|User) $auth_user Authorized user (used for privacy)
444 * @param int $offset Offset from latest
445 * @param int $limit Max number to get
446 * @param datetime $since_id max date
447 * @param datetime $max_id min date
449 * @return Profile_list resulting lists
452 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
454 $list = new Profile_list();
456 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
457 'from profile_tag join profile_list '.
458 'on (profile_tag.tagger = profile_list.tagger ' .
459 ' and profile_tag.tag = profile_list.tag) ' .
460 'where profile_tag.tagged = %d ',
464 if ($auth_user instanceof User || $auth_user instanceof Profile) {
465 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
466 'OR ( profile_list.tagger = %d AND ' .
467 'profile_list.private = true ) )',
470 $qry .= 'AND profile_list.private = 0 ';
474 $qry .= sprintf('AND (cursor > %d) ', $since_id);
478 $qry .= sprintf('AND (cursor < %d) ', $max_id);
481 $qry .= 'ORDER BY profile_tag.modified DESC ';
483 if ($offset >= 0 && !is_null($limit)) {
484 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
491 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
493 $tags = new Profile_list();
494 $tags->private = true;
495 $tags->tagger = $this->id;
498 $tags->whereAdd('id > '.$since_id);
502 $tags->whereAdd('id <= '.$max_id);
505 if($offset>=0 && !is_null($limit)) {
506 $tags->limit($offset, $limit);
509 $tags->orderBy('id DESC');
515 function hasLocalTags()
517 $tags = new Profile_tag();
519 $tags->joinAdd(array('tagger', 'user:id'));
520 $tags->whereAdd('tagged = '.$this->id);
521 $tags->whereAdd('tagger != '.$this->id);
526 return ($tags->N == 0) ? false : true;
529 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
531 $lists = new Profile_list();
532 $subs = new Profile_tag_subscription();
534 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
536 #@fixme: postgres (round(date_part('epoch', my_date)))
537 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
539 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
542 $lists->whereAdd('cursor > '.$since_id);
546 $lists->whereAdd('cursor <= '.$max_id);
549 if($offset>=0 && !is_null($limit)) {
550 $lists->limit($offset, $limit);
553 $lists->orderBy('"cursor" DESC');
560 * Request to join the given group.
561 * May throw exceptions on failure.
563 * @param User_group $group
564 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
566 function joinGroup(User_group $group)
569 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
570 $join = Group_join_queue::saveNew($this, $group);
572 if (Event::handle('StartJoinGroup', array($group, $this))) {
573 $join = Group_member::join($group->id, $this->id);
574 self::blow('profile:groups:%d', $this->id);
575 self::blow('group:member_ids:%d', $group->id);
576 self::blow('group:member_count:%d', $group->id);
577 Event::handle('EndJoinGroup', array($group, $this));
581 // Send any applicable notifications...
588 * Leave a group that this profile is a member of.
590 * @param User_group $group
592 function leaveGroup(User_group $group)
594 if (Event::handle('StartLeaveGroup', array($group, $this))) {
595 Group_member::leave($group->id, $this->id);
596 self::blow('profile:groups:%d', $this->id);
597 self::blow('group:member_ids:%d', $group->id);
598 self::blow('group:member_count:%d', $group->id);
599 Event::handle('EndLeaveGroup', array($group, $this));
603 function avatarUrl($size=AVATAR_PROFILE_SIZE)
605 return Avatar::urlByProfile($this, $size);
608 function getSubscribed($offset=0, $limit=null)
610 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
612 $profiles = Profile::multiGet('id', $subs);
613 } catch (NoResultException $e) {
619 function getSubscribers($offset=0, $limit=null)
621 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
623 $profiles = Profile::multiGet('id', $subs);
624 } catch (NoResultException $e) {
630 function getTaggedSubscribers($tag, $offset=0, $limit=null)
633 'SELECT profile.* ' .
634 'FROM profile JOIN subscription ' .
635 'ON profile.id = subscription.subscriber ' .
636 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
637 'AND profile_tag.tagger = subscription.subscribed) ' .
638 'WHERE subscription.subscribed = %d ' .
639 "AND profile_tag.tag = '%s' " .
640 'AND subscription.subscribed != subscription.subscriber ' .
641 'ORDER BY subscription.created DESC ';
644 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
647 $profile = new Profile();
649 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
654 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
657 'SELECT profile.* ' .
658 'FROM profile JOIN subscription ' .
659 'ON profile.id = subscription.subscribed ' .
660 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
661 'AND profile_tag.tagger = subscription.subscriber) ' .
662 'WHERE subscription.subscriber = %d ' .
663 "AND profile_tag.tag = '%s' " .
664 'AND subscription.subscribed != subscription.subscriber ' .
665 'ORDER BY subscription.created DESC ';
667 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
669 $profile = new Profile();
671 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
677 * Get pending subscribers, who have not yet been approved.
683 function getRequests($offset=0, $limit=null)
686 $subqueue = new Profile();
687 $subqueue->joinAdd(array('id', 'subscription_queue:subscriber'));
688 $subqueue->whereAdd(sprintf('subscription_queue.subscribed = %d', $this->getID()));
689 $subqueue->limit($offset, $limit);
690 $subqueue->orderBy('subscription_queue.created', 'DESC');
691 if (!$subqueue->find()) {
692 throw new NoResultException($subqueue);
697 function subscriptionCount()
699 $c = Cache::instance();
702 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
703 if (is_integer($cnt)) {
708 $sub = new Subscription();
709 $sub->subscriber = $this->id;
711 $cnt = (int) $sub->count('distinct subscribed');
713 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
716 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
722 function subscriberCount()
724 $c = Cache::instance();
726 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
727 if (is_integer($cnt)) {
732 $sub = new Subscription();
733 $sub->subscribed = $this->id;
734 $sub->whereAdd('subscriber != subscribed');
735 $cnt = (int) $sub->count('distinct subscriber');
738 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
745 * Is this profile subscribed to another profile?
747 * @param Profile $other
750 function isSubscribed(Profile $other)
752 return Subscription::exists($this, $other);
755 function readableBy(Profile $other=null)
757 // If it's not a private stream, it's readable by anyone
758 if (!$this->isPrivateStream()) {
762 // If it's a private stream, $other must be a subscriber to $this
763 return is_null($other) ? false : $other->isSubscribed($this);
766 function requiresSubscriptionApproval(Profile $other=null)
768 if (!$this->isLocal()) {
769 // We don't know for remote users, and we'll always be able to send
770 // the request. Whether it'll work immediately or require moderation
771 // can be determined in another function.
775 // Assume that profiles _we_ subscribe to are permitted. Could be made configurable.
776 if (!is_null($other) && $this->isSubscribed($other)) {
780 // If the local user either has a private stream (implies the following)
781 // or user has a moderation policy for new subscriptions, return true.
782 return $this->getUser()->private_stream || $this->getUser()->subscribe_policy === User::SUBSCRIBE_POLICY_MODERATE;
786 * Check if a pending subscription request is outstanding for this...
788 * @param Profile $other
791 function hasPendingSubscription(Profile $other)
793 return Subscription_queue::exists($this, $other);
797 * Are these two profiles subscribed to each other?
799 * @param Profile $other
802 function mutuallySubscribed(Profile $other)
804 return $this->isSubscribed($other) &&
805 $other->isSubscribed($this);
808 function noticeCount()
810 $c = Cache::instance();
813 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
814 if (is_integer($cnt)) {
819 $notices = new Notice();
820 $notices->profile_id = $this->id;
821 $cnt = (int) $notices->count('distinct id');
824 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
830 function blowSubscriberCount()
832 $c = Cache::instance();
834 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
838 function blowSubscriptionCount()
840 $c = Cache::instance();
842 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
846 function blowNoticeCount()
848 $c = Cache::instance();
850 $c->delete(Cache::key('profile:notice_count:'.$this->id));
854 static function maxBio()
856 $biolimit = common_config('profile', 'biolimit');
857 // null => use global limit (distinct from 0!)
858 if (is_null($biolimit)) {
859 $biolimit = common_config('site', 'textlimit');
864 static function bioTooLong($bio)
866 $biolimit = self::maxBio();
867 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
870 function update($dataObject=false)
872 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
874 $local = $this->getUser();
875 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
876 $origuser = clone($local);
877 $local->nickname = $this->nickname;
878 // updateWithKeys throws exception on failure.
879 $local->updateWithKeys($origuser);
881 // Clear the site owner, in case nickname changed
882 if ($local->hasRole(Profile_role::OWNER)) {
883 User::blow('user:site_owner');
885 } catch (NoSuchUserException $e) {
890 return parent::update($dataObject);
893 function delete($useWhere=false)
895 // just in case it hadn't been done before... (usually set before adding deluser to queue handling!)
896 if (!$this->hasRole(Profile_role::DELETED)) {
897 $this->grantRole(Profile_role::DELETED);
900 $this->_deleteNotices();
901 $this->_deleteSubscriptions();
902 $this->_deleteTags();
903 $this->_deleteBlocks();
904 $this->_deleteAttentions();
905 Avatar::deleteFromProfile($this, true);
907 // Warning: delete() will run on the batch objects,
908 // not on individual objects.
909 $related = array('Reply',
912 Event::handle('ProfileDeleteRelated', array($this, &$related));
914 foreach ($related as $cls) {
916 $inst->profile_id = $this->id;
920 $localuser = User::getKV('id', $this->id);
921 if ($localuser instanceof User) {
922 $localuser->delete();
925 return parent::delete($useWhere);
928 function _deleteNotices()
930 $notice = new Notice();
931 $notice->profile_id = $this->id;
933 if ($notice->find()) {
934 while ($notice->fetch()) {
935 $other = clone($notice);
941 function _deleteSubscriptions()
943 $sub = new Subscription();
944 $sub->subscriber = $this->id;
948 while ($sub->fetch()) {
949 $other = Profile::getKV('id', $sub->subscribed);
953 if ($other->id == $this->id) {
956 Subscription::cancel($this, $other);
959 $subd = new Subscription();
960 $subd->subscribed = $this->id;
963 while ($subd->fetch()) {
964 $other = Profile::getKV('id', $subd->subscriber);
968 if ($other->id == $this->id) {
971 Subscription::cancel($other, $this);
974 $self = new Subscription();
976 $self->subscriber = $this->id;
977 $self->subscribed = $this->id;
982 function _deleteTags()
984 $tag = new Profile_tag();
985 $tag->tagged = $this->id;
989 function _deleteBlocks()
991 $block = new Profile_block();
992 $block->blocked = $this->id;
995 $block = new Group_block();
996 $block->blocked = $this->id;
1000 function _deleteAttentions()
1002 $att = new Attention();
1003 $att->profile_id = $this->getID();
1006 while ($att->fetch()) {
1007 // Can't do delete() on the object directly since it won't remove all of it
1008 $other = clone($att);
1014 // XXX: identical to Notice::getLocation.
1016 public function getLocation()
1020 if (!empty($this->location_id) && !empty($this->location_ns)) {
1021 $location = Location::fromId($this->location_id, $this->location_ns);
1024 if (is_null($location)) { // no ID, or Location::fromId() failed
1025 if (!empty($this->lat) && !empty($this->lon)) {
1026 $location = Location::fromLatLon($this->lat, $this->lon);
1030 if (is_null($location)) { // still haven't found it!
1031 if (!empty($this->location)) {
1032 $location = Location::fromName($this->location);
1039 public function shareLocation()
1041 $cfg = common_config('location', 'share');
1043 if ($cfg == 'always') {
1045 } else if ($cfg == 'never') {
1048 $share = common_config('location', 'sharedefault');
1050 // Check if user has a personal setting for this
1051 $prefs = User_location_prefs::getKV('user_id', $this->id);
1053 if (!empty($prefs)) {
1054 $share = $prefs->share_location;
1062 function hasRole($name)
1065 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1066 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1068 $has_role = !empty($role);
1069 Event::handle('EndHasRole', array($this, $name, $has_role));
1074 function grantRole($name)
1076 if (Event::handle('StartGrantRole', array($this, $name))) {
1078 $role = new Profile_role();
1080 $role->profile_id = $this->id;
1081 $role->role = $name;
1082 $role->created = common_sql_now();
1084 $result = $role->insert();
1087 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1090 if ($name == 'owner') {
1091 User::blow('user:site_owner');
1094 Event::handle('EndGrantRole', array($this, $name));
1100 function revokeRole($name)
1102 if (Event::handle('StartRevokeRole', array($this, $name))) {
1104 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1108 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1109 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1110 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1113 $result = $role->delete();
1116 common_log_db_error($role, 'DELETE', __FILE__);
1117 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1118 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1119 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1122 if ($name == 'owner') {
1123 User::blow('user:site_owner');
1126 Event::handle('EndRevokeRole', array($this, $name));
1132 function isSandboxed()
1134 return $this->hasRole(Profile_role::SANDBOXED);
1137 function isSilenced()
1139 return $this->hasRole(Profile_role::SILENCED);
1144 $this->grantRole(Profile_role::SANDBOXED);
1147 function unsandbox()
1149 $this->revokeRole(Profile_role::SANDBOXED);
1154 $this->grantRole(Profile_role::SILENCED);
1155 if (common_config('notice', 'hidespam')) {
1156 $this->flushVisibility();
1160 function unsilence()
1162 $this->revokeRole(Profile_role::SILENCED);
1163 if (common_config('notice', 'hidespam')) {
1164 $this->flushVisibility();
1168 function flushVisibility()
1171 $stream = new ProfileNoticeStream($this, $this);
1172 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1173 foreach ($ids as $id) {
1174 self::blow('notice:in-scope-for:%d:null', $id);
1179 * Does this user have the right to do X?
1181 * With our role-based authorization, this is merely a lookup for whether the user
1182 * has a particular role. The implementation currently uses a switch statement
1183 * to determine if the user has the pre-defined role to exercise the right. Future
1184 * implementations may allow per-site roles, and different mappings of roles to rights.
1186 * @param $right string Name of the right, usually a constant in class Right
1187 * @return boolean whether the user has the right in question
1189 public function hasRight($right)
1193 if ($this->hasRole(Profile_role::DELETED)) {
1197 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1200 case Right::DELETEOTHERSNOTICE:
1201 case Right::MAKEGROUPADMIN:
1202 case Right::SANDBOXUSER:
1203 case Right::SILENCEUSER:
1204 case Right::DELETEUSER:
1205 case Right::DELETEGROUP:
1206 case Right::TRAINSPAM:
1207 case Right::REVIEWSPAM:
1208 $result = $this->hasRole(Profile_role::MODERATOR);
1210 case Right::CONFIGURESITE:
1211 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1213 case Right::GRANTROLE:
1214 case Right::REVOKEROLE:
1215 $result = $this->hasRole(Profile_role::OWNER);
1217 case Right::NEWNOTICE:
1218 case Right::NEWMESSAGE:
1219 case Right::SUBSCRIBE:
1220 case Right::CREATEGROUP:
1221 $result = !$this->isSilenced();
1223 case Right::PUBLICNOTICE:
1224 case Right::EMAILONREPLY:
1225 case Right::EMAILONSUBSCRIBE:
1226 case Right::EMAILONFAVE:
1227 $result = !$this->isSandboxed();
1229 case Right::WEBLOGIN:
1230 $result = !$this->isSilenced();
1233 $result = !$this->isSilenced();
1235 case Right::BACKUPACCOUNT:
1236 $result = common_config('profile', 'backup');
1238 case Right::RESTOREACCOUNT:
1239 $result = common_config('profile', 'restore');
1241 case Right::DELETEACCOUNT:
1242 $result = common_config('profile', 'delete');
1244 case Right::MOVEACCOUNT:
1245 $result = common_config('profile', 'move');
1255 // FIXME: Can't put Notice typing here due to ArrayWrapper
1256 public function hasRepeated($notice)
1258 // XXX: not really a pkey, but should work
1260 $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
1261 'repeat_of' => $notice->getID(),
1262 'verb' => ActivityVerb::SHARE));
1264 return !empty($notice);
1268 * Returns an XML string fragment with limited profile information
1269 * as an Atom <author> element.
1271 * Assumes that Atom has been previously set up as the base namespace.
1273 * @param Profile $cur the current authenticated user
1277 function asAtomAuthor($cur = null)
1279 $xs = new XMLStringer(true);
1281 $xs->elementStart('author');
1282 $xs->element('name', null, $this->nickname);
1283 $xs->element('uri', null, $this->getUri());
1286 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1287 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1288 $xs->element('statusnet:profile_info', $attrs, null);
1290 $xs->elementEnd('author');
1292 return $xs->getString();
1296 * Extra profile info for atom entries
1298 * Clients use some extra profile info in the atom stream.
1299 * This gives it to them.
1301 * @param Profile $scoped The currently logged in/scoped profile
1303 * @return array representation of <statusnet:profile_info> element or null
1306 function profileInfo(Profile $scoped=null)
1308 $profileInfoAttr = array('local_id' => $this->id);
1310 if ($scoped instanceof Profile) {
1311 // Whether the current user is a subscribed to this profile
1312 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1313 // Whether the current user is has blocked this profile
1314 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1317 return array('statusnet:profile_info', $profileInfoAttr, null);
1321 * Returns an XML string fragment with profile information as an
1322 * Activity Streams <activity:actor> element.
1324 * Assumes that 'activity' namespace has been previously defined.
1328 function asActivityActor()
1330 return $this->asActivityNoun('actor');
1334 * Returns an XML string fragment with profile information as an
1335 * Activity Streams noun object with the given element type.
1337 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1338 * previously defined.
1340 * @param string $element one of 'actor', 'subject', 'object', 'target'
1344 function asActivityNoun($element)
1346 $noun = $this->asActivityObject();
1347 return $noun->asString('activity:' . $element);
1350 public function asActivityObject()
1352 $object = new ActivityObject();
1354 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1355 $object->type = $this->getObjectType();
1356 $object->id = $this->getUri();
1357 $object->title = $this->getBestName();
1358 $object->link = $this->getUrl();
1359 $object->summary = $this->getDescription();
1362 $avatar = Avatar::getUploaded($this);
1363 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1364 } catch (NoAvatarException $e) {
1365 // Could not find an original avatar to link
1369 AVATAR_PROFILE_SIZE,
1374 foreach ($sizes as $size) {
1377 $avatar = Avatar::byProfile($this, $size);
1378 $alink = AvatarLink::fromAvatar($avatar);
1379 } catch (NoAvatarException $e) {
1380 $alink = new AvatarLink();
1381 $alink->type = 'image/png';
1382 $alink->height = $size;
1383 $alink->width = $size;
1384 $alink->url = Avatar::defaultImage($size);
1387 $object->avatarLinks[] = $alink;
1390 if (isset($this->lat) && isset($this->lon)) {
1391 $object->geopoint = (float)$this->lat
1392 . ' ' . (float)$this->lon;
1395 $object->poco = PoCo::fromProfile($this);
1397 if ($this->isLocal()) {
1398 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1401 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1408 * Returns the profile's canonical url, not necessarily a uri/unique id
1410 * @return string $profileurl
1412 public function getUrl()
1414 if (empty($this->profileurl) ||
1415 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1416 throw new InvalidUrlException($this->profileurl);
1418 return $this->profileurl;
1421 public function getNickname()
1423 return $this->nickname;
1426 public function getFullname()
1428 return $this->fullname;
1431 public function getHomepage()
1433 return $this->homepage;
1436 public function getDescription()
1442 * Returns the best URI for a profile. Plugins may override.
1444 * @return string $uri
1446 public function getUri()
1450 // give plugins a chance to set the URI
1451 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1453 // check for a local user first
1454 $user = User::getKV('id', $this->id);
1455 if ($user instanceof User) {
1456 $uri = $user->getUri();
1458 $group = User_group::getKV('profile_id', $this->id);
1459 if ($group instanceof User_group) {
1460 $uri = $group->getUri();
1464 Event::handle('EndGetProfileUri', array($this, &$uri));
1471 * Returns an assumed acct: URI for a profile. Plugins are required.
1473 * @return string $uri
1475 public function getAcctUri()
1479 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1480 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1483 if ($acct === null) {
1484 throw new ProfileNoAcctUriException($this);
1490 function hasBlocked($other)
1492 $block = Profile_block::exists($this, $other);
1493 return !empty($block);
1496 function getAtomFeed()
1500 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1501 $user = User::getKV('id', $this->id);
1502 if (!empty($user)) {
1503 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1504 'format' => 'atom'));
1506 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1512 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1514 // TRANS: Exception thrown when trying view "repeated to me".
1515 throw new Exception(_('Not implemented since inbox change.'));
1519 * Get a Profile object by URI. Will call external plugins for help
1520 * using the event StartGetProfileFromURI.
1522 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1524 static function fromUri($uri)
1528 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1529 // Get a local user when plugin lookup (like OStatus) fails
1530 $user = User::getKV('uri', $uri);
1531 if ($user instanceof User) {
1532 $profile = $user->getProfile();
1534 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1537 if (!$profile instanceof Profile) {
1538 throw new UnknownUriException($uri);
1544 function canRead(Notice $notice)
1546 if ($notice->scope & Notice::SITE_SCOPE) {
1547 $user = $this->getUser();
1553 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1554 $replies = $notice->getReplies();
1556 if (!in_array($this->id, $replies)) {
1557 $groups = $notice->getGroups();
1561 foreach ($groups as $group) {
1562 if ($this->isMember($group)) {
1574 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1575 $author = $notice->getProfile();
1576 if (!Subscription::exists($this, $author)) {
1584 static function current()
1586 $user = common_current_user();
1590 $profile = $user->getProfile();
1596 * Magic function called at serialize() time.
1598 * We use this to drop a couple process-specific references
1599 * from DB_DataObject which can cause trouble in future
1602 * @return array of variable names to include in serialization.
1607 $vars = parent::__sleep();
1608 $skip = array('_user', '_group');
1609 return array_diff($vars, $skip);
1612 public function getProfile()
1618 * Test whether the given profile is the same as the current class,
1619 * for testing identities.
1621 * @param Profile $other The other profile, usually from Action's $this->scoped
1625 public function sameAs(Profile $other=null)
1627 if (is_null($other)) {
1628 // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
1631 return $this->getID() === $other->getID();
1635 * This will perform shortenLinks with the connected User object.
1637 * Won't work on remote profiles or groups, so expect a
1638 * NoSuchUserException if you don't know it's a local User.
1640 * @param string $text String to shorten
1641 * @param boolean $always Disrespect minimum length etc.
1643 * @return string link-shortened $text
1645 public function shortenLinks($text, $always=false)
1647 return $this->getUser()->shortenLinks($text, $always);
1650 public function isPrivateStream()
1652 // We only know of public remote users as of yet...
1653 if (!$this->isLocal()) {
1656 return $this->getUser()->private_stream ? true : false;
1659 public function delPref($namespace, $topic) {
1660 return Profile_prefs::setData($this, $namespace, $topic, null);
1663 public function getPref($namespace, $topic, $default=null) {
1664 // If you want an exception to be thrown, call Profile_prefs::getData directly
1666 return Profile_prefs::getData($this, $namespace, $topic, $default);
1667 } catch (NoResultException $e) {
1672 // The same as getPref but will fall back to common_config value for the same namespace/topic
1673 public function getConfigPref($namespace, $topic)
1675 return Profile_prefs::getConfigData($this, $namespace, $topic);
1678 public function setPref($namespace, $topic, $data) {
1679 return Profile_prefs::setData($this, $namespace, $topic, $data);
1682 public function getConnectedApps($offset=0, $limit=null)
1684 return $this->getUser()->getConnectedApps($offset, $limit);