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 isPerson()
127 // Maybe other things than PERSON and GROUP can have Profiles in the future?
128 return !$this->isGroup();
131 public function isLocal()
135 } catch (NoSuchUserException $e) {
141 // Returns false if the user has no password (which will always
142 // be the case for remote users). This can be the case for OpenID
143 // logins or other mechanisms which don't store a password hash.
144 public function hasPassword()
147 return $this->getUser()->hasPassword();
148 } catch (NoSuchUserException $e) {
153 public function getObjectType()
155 // FIXME: More types... like peopletags and whatever
156 if ($this->isGroup()) {
157 return ActivityObject::GROUP;
159 return ActivityObject::PERSON;
163 public function getAvatar($width, $height=null)
165 return Avatar::byProfile($this, $width, $height);
168 public function setOriginal($filename)
170 if ($this->isGroup()) {
171 // Until Group avatars are handled just like profile avatars.
172 return $this->getGroup()->setOriginal($filename);
175 $imagefile = new ImageFile(null, Avatar::path($filename));
177 $avatar = new Avatar();
178 $avatar->profile_id = $this->id;
179 $avatar->width = $imagefile->width;
180 $avatar->height = $imagefile->height;
181 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
182 $avatar->filename = $filename;
183 $avatar->original = true;
184 $avatar->created = common_sql_now();
186 // XXX: start a transaction here
187 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
188 // If we can't delete the old avatars, let's abort right here.
189 @unlink(Avatar::path($filename));
197 * Gets either the full name (if filled) or the nickname.
201 function getBestName()
203 return ($this->fullname) ? $this->fullname : $this->nickname;
207 * Takes the currently scoped profile into account to give a name
208 * to list in notice streams. Preferences may differ between profiles.
210 function getStreamName()
212 $user = common_current_user();
213 if ($user instanceof User && $user->streamNicknames()) {
214 return $this->nickname;
217 return $this->getBestName();
221 * Gets the full name (if filled) with acct URI, URL, or URI as a
222 * parenthetical (in that order, for each not found). If no full
223 * name is found only the second part is returned, without ()s.
227 function getFancyName()
231 $uri = $this->getAcctUri(false);
232 } catch (ProfileNoAcctUriException $e) {
234 $uri = $this->getUrl();
235 } catch (InvalidUrlException $e) {
236 $uri = $this->getUri();
240 if (mb_strlen($this->getFullname()) > 0) {
241 // TRANS: The "fancy name": Full name of a profile or group (%1$s) followed by some URI (%2$s) in parentheses.
242 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->getFullname(), $uri);
249 * Get the most recent notice posted by this user, if any.
251 * @return mixed Notice or null
253 function getCurrentNotice(Profile $scoped=null)
256 $notice = $this->getNotices(0, 1, 0, 0, $scoped);
258 if ($notice->fetch()) {
259 if ($notice instanceof ArrayWrapper) {
260 // hack for things trying to work with single notices
261 // ...but this shouldn't happen anymore I think. Keeping it for safety...
262 return $notice->_items[0];
266 } catch (PrivateStreamException $e) {
267 // Maybe we should let this through if it's handled well upstream
274 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
276 return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
279 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
281 //FIXME: Get Profile::current() some other way to avoid possible
282 // confusion between current session profile and background processing.
283 $stream = new TaggedProfileNoticeStream($this, $tag, Profile::current());
285 return $stream->getNotices($offset, $limit, $since_id, $max_id);
288 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
290 $stream = new ProfileNoticeStream($this, $scoped);
292 return $stream->getNotices($offset, $limit, $since_id, $max_id);
295 function isMember(User_group $group)
297 $groups = $this->getGroups(0, null);
298 while ($groups instanceof User_group && $groups->fetch()) {
299 if ($groups->id == $group->id) {
306 function isAdmin(User_group $group)
308 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
309 'group_id' => $group->id));
310 return (!empty($gm) && $gm->is_admin);
313 function isPendingMember($group)
315 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
316 'group_id' => $group->id));
317 return !empty($request);
320 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
324 $keypart = sprintf('profile:groups:%d', $this->id);
326 $idstring = self::cacheGet($keypart);
328 if ($idstring !== false) {
329 $ids = explode(',', $idstring);
331 $gm = new Group_member();
333 $gm->profile_id = $this->id;
336 while ($gm->fetch()) {
337 $ids[] = $gm->group_id;
341 self::cacheSet($keypart, implode(',', $ids));
344 if (!is_null($offset) && !is_null($limit)) {
345 $ids = array_slice($ids, $offset, $limit);
349 return User_group::multiGet('id', $ids);
350 } catch (NoResultException $e) {
351 return null; // throw exception when we handle it everywhere
355 function getGroupCount() {
356 $groups = $this->getGroups(0, null);
357 return $groups instanceof User_group
362 function isTagged($peopletag)
364 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
365 'tagged' => $this->id,
366 'tag' => $peopletag->tag));
370 function canTag($tagged)
372 if (empty($tagged)) {
376 if ($tagged->id == $this->id) {
380 $all = common_config('peopletag', 'allow_tagging', 'all');
381 $local = common_config('peopletag', 'allow_tagging', 'local');
382 $remote = common_config('peopletag', 'allow_tagging', 'remote');
383 $subs = common_config('peopletag', 'allow_tagging', 'subs');
389 $tagged_user = $tagged->getUser();
390 if (!empty($tagged_user)) {
395 return (Subscription::exists($this, $tagged) ||
396 Subscription::exists($tagged, $this));
397 } else if ($remote) {
403 function getLists(Profile $scoped=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
407 $keypart = sprintf('profile:lists:%d', $this->id);
409 $idstr = self::cacheGet($keypart);
411 if ($idstr !== false) {
412 $ids = explode(',', $idstr);
414 $list = new Profile_list();
416 $list->selectAdd('id');
417 $list->tagger = $this->id;
418 $list->selectAdd('id as "cursor"');
421 $list->whereAdd('id > '.$since_id);
425 $list->whereAdd('id <= '.$max_id);
428 if($offset>=0 && !is_null($limit)) {
429 $list->limit($offset, $limit);
432 $list->orderBy('id DESC');
435 while ($list->fetch()) {
440 self::cacheSet($keypart, implode(',', $ids));
443 $showPrivate = $this->sameAs($scoped);
447 foreach ($ids as $id) {
448 $list = Profile_list::getKV('id', $id);
450 ($showPrivate || !$list->private)) {
452 if (!isset($list->cursor)) {
453 $list->cursor = $list->id;
460 return new ArrayWrapper($lists);
464 * Get tags that other people put on this profile, in reverse-chron order
466 * @param Profile $scoped User we are requesting as
467 * @param int $offset Offset from latest
468 * @param int $limit Max number to get
469 * @param datetime $since_id max date
470 * @param datetime $max_id min date
472 * @return Profile_list resulting lists
475 function getOtherTags(Profile $scoped=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
477 $list = new Profile_list();
479 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
480 'from profile_tag join profile_list '.
481 'on (profile_tag.tagger = profile_list.tagger ' .
482 ' and profile_tag.tag = profile_list.tag) ' .
483 'where profile_tag.tagged = %d ',
487 if (!is_null($scoped)) {
488 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
489 'OR ( profile_list.tagger = %d AND ' .
490 'profile_list.private = true ) )',
493 $qry .= 'AND profile_list.private = 0 ';
497 $qry .= sprintf('AND (cursor > %d) ', $since_id);
501 $qry .= sprintf('AND (cursor < %d) ', $max_id);
504 $qry .= 'ORDER BY profile_tag.modified DESC ';
506 if ($offset >= 0 && !is_null($limit)) {
507 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
514 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
516 $tags = new Profile_list();
517 $tags->private = true;
518 $tags->tagger = $this->id;
521 $tags->whereAdd('id > '.$since_id);
525 $tags->whereAdd('id <= '.$max_id);
528 if($offset>=0 && !is_null($limit)) {
529 $tags->limit($offset, $limit);
532 $tags->orderBy('id DESC');
538 function hasLocalTags()
540 $tags = new Profile_tag();
542 $tags->joinAdd(array('tagger', 'user:id'));
543 $tags->whereAdd('tagged = '.$this->id);
544 $tags->whereAdd('tagger != '.$this->id);
549 return ($tags->N == 0) ? false : true;
552 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
554 $lists = new Profile_list();
555 $subs = new Profile_tag_subscription();
557 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
559 #@fixme: postgres (round(date_part('epoch', my_date)))
560 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
562 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
565 $lists->whereAdd('cursor > '.$since_id);
569 $lists->whereAdd('cursor <= '.$max_id);
572 if($offset>=0 && !is_null($limit)) {
573 $lists->limit($offset, $limit);
576 $lists->orderBy('"cursor" DESC');
583 * Request to join the given group.
584 * May throw exceptions on failure.
586 * @param User_group $group
587 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
589 function joinGroup(User_group $group)
592 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
593 $join = Group_join_queue::saveNew($this, $group);
595 if (Event::handle('StartJoinGroup', array($group, $this))) {
596 $join = Group_member::join($group->id, $this->id);
597 self::blow('profile:groups:%d', $this->id);
598 self::blow('group:member_ids:%d', $group->id);
599 self::blow('group:member_count:%d', $group->id);
600 Event::handle('EndJoinGroup', array($group, $this));
604 // Send any applicable notifications...
611 * Leave a group that this profile is a member of.
613 * @param User_group $group
615 function leaveGroup(User_group $group)
617 if (Event::handle('StartLeaveGroup', array($group, $this))) {
618 Group_member::leave($group->id, $this->id);
619 self::blow('profile:groups:%d', $this->id);
620 self::blow('group:member_ids:%d', $group->id);
621 self::blow('group:member_count:%d', $group->id);
622 Event::handle('EndLeaveGroup', array($group, $this));
626 function avatarUrl($size=AVATAR_PROFILE_SIZE)
628 return Avatar::urlByProfile($this, $size);
631 function getSubscribed($offset=0, $limit=null)
633 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
635 $profiles = Profile::multiGet('id', $subs);
636 } catch (NoResultException $e) {
642 function getSubscribers($offset=0, $limit=null)
644 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
646 $profiles = Profile::multiGet('id', $subs);
647 } catch (NoResultException $e) {
653 function getTaggedSubscribers($tag, $offset=0, $limit=null)
656 'SELECT profile.* ' .
657 'FROM profile JOIN subscription ' .
658 'ON profile.id = subscription.subscriber ' .
659 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
660 'AND profile_tag.tagger = subscription.subscribed) ' .
661 'WHERE subscription.subscribed = %d ' .
662 "AND profile_tag.tag = '%s' " .
663 'AND subscription.subscribed != subscription.subscriber ' .
664 'ORDER BY subscription.created DESC ';
667 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
670 $profile = new Profile();
672 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
677 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
680 'SELECT profile.* ' .
681 'FROM profile JOIN subscription ' .
682 'ON profile.id = subscription.subscribed ' .
683 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
684 'AND profile_tag.tagger = subscription.subscriber) ' .
685 'WHERE subscription.subscriber = %d ' .
686 "AND profile_tag.tag = '%s' " .
687 'AND subscription.subscribed != subscription.subscriber ' .
688 'ORDER BY subscription.created DESC ';
690 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
692 $profile = new Profile();
694 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
700 * Get pending subscribers, who have not yet been approved.
706 function getRequests($offset=0, $limit=null)
709 $subqueue = new Profile();
710 $subqueue->joinAdd(array('id', 'subscription_queue:subscriber'));
711 $subqueue->whereAdd(sprintf('subscription_queue.subscribed = %d', $this->getID()));
712 $subqueue->limit($offset, $limit);
713 $subqueue->orderBy('subscription_queue.created', 'DESC');
714 if (!$subqueue->find()) {
715 throw new NoResultException($subqueue);
720 function subscriptionCount()
722 $c = Cache::instance();
725 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
726 if (is_integer($cnt)) {
731 $sub = new Subscription();
732 $sub->subscriber = $this->id;
734 $cnt = (int) $sub->count('distinct subscribed');
736 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
739 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
745 function subscriberCount()
747 $c = Cache::instance();
749 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
750 if (is_integer($cnt)) {
755 $sub = new Subscription();
756 $sub->subscribed = $this->id;
757 $sub->whereAdd('subscriber != subscribed');
758 $cnt = (int) $sub->count('distinct subscriber');
761 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
768 * Is this profile subscribed to another profile?
770 * @param Profile $other
773 function isSubscribed(Profile $other)
775 return Subscription::exists($this, $other);
778 function readableBy(Profile $other=null)
780 // If it's not a private stream, it's readable by anyone
781 if (!$this->isPrivateStream()) {
785 // If it's a private stream, $other must be a subscriber to $this
786 return is_null($other) ? false : $other->isSubscribed($this);
789 function requiresSubscriptionApproval(Profile $other=null)
791 if (!$this->isLocal()) {
792 // We don't know for remote users, and we'll always be able to send
793 // the request. Whether it'll work immediately or require moderation
794 // can be determined in another function.
798 // Assume that profiles _we_ subscribe to are permitted. Could be made configurable.
799 if (!is_null($other) && $this->isSubscribed($other)) {
803 // If the local user either has a private stream (implies the following)
804 // or user has a moderation policy for new subscriptions, return true.
805 return $this->getUser()->private_stream || $this->getUser()->subscribe_policy === User::SUBSCRIBE_POLICY_MODERATE;
809 * Check if a pending subscription request is outstanding for this...
811 * @param Profile $other
814 function hasPendingSubscription(Profile $other)
816 return Subscription_queue::exists($this, $other);
820 * Are these two profiles subscribed to each other?
822 * @param Profile $other
825 function mutuallySubscribed(Profile $other)
827 return $this->isSubscribed($other) &&
828 $other->isSubscribed($this);
831 function noticeCount()
833 $c = Cache::instance();
836 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->getID()));
837 if (is_integer($cnt)) {
842 $notices = new Notice();
843 $notices->profile_id = $this->getID();
844 $notices->verb = ActivityVerb::POST;
845 $cnt = (int) $notices->count('id'); // Not sure if I imagine this, but 'id' was faster than the defaulting 'uri'?
848 $c->set(Cache::key('profile:notice_count:'.$this->getID()), $cnt);
854 function blowSubscriberCount()
856 $c = Cache::instance();
858 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
862 function blowSubscriptionCount()
864 $c = Cache::instance();
866 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
870 function blowNoticeCount()
872 $c = Cache::instance();
874 $c->delete(Cache::key('profile:notice_count:'.$this->id));
878 static function maxBio()
880 $biolimit = common_config('profile', 'biolimit');
881 // null => use global limit (distinct from 0!)
882 if (is_null($biolimit)) {
883 $biolimit = common_config('site', 'textlimit');
888 static function bioTooLong($bio)
890 $biolimit = self::maxBio();
891 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
894 function update($dataObject=false)
896 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
898 $local = $this->getUser();
899 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
900 $origuser = clone($local);
901 $local->nickname = $this->nickname;
902 // updateWithKeys throws exception on failure.
903 $local->updateWithKeys($origuser);
905 // Clear the site owner, in case nickname changed
906 if ($local->hasRole(Profile_role::OWNER)) {
907 User::blow('user:site_owner');
909 } catch (NoSuchUserException $e) {
914 return parent::update($dataObject);
917 public function getRelSelf()
919 return ['href' => $this->getUrl(),
920 'text' => common_config('site', 'name'),
921 'image' => Avatar::urlByProfile($this)];
924 // All the known rel="me", used for the IndieWeb audience
925 public function getRelMes()
929 $relMes[] = $this->getRelSelf();
930 } catch (InvalidUrlException $e) {
931 // no valid profile URL available
933 if (common_valid_http_url($this->getHomepage())) {
934 $relMes[] = ['href' => $this->getHomepage(),
935 'text' => _('Homepage'),
938 Event::handle('OtherAccountProfiles', array($this, &$relMes));
942 function delete($useWhere=false)
944 $this->_deleteNotices();
945 $this->_deleteSubscriptions();
946 $this->_deleteTags();
947 $this->_deleteBlocks();
948 $this->_deleteAttentions();
949 Avatar::deleteFromProfile($this, true);
951 // Warning: delete() will run on the batch objects,
952 // not on individual objects.
953 $related = array('Reply',
957 Event::handle('ProfileDeleteRelated', array($this, &$related));
959 foreach ($related as $cls) {
961 $inst->profile_id = $this->id;
965 $this->grantRole(Profile_role::DELETED);
967 $localuser = User::getKV('id', $this->id);
968 if ($localuser instanceof User) {
969 $localuser->delete();
972 return parent::delete($useWhere);
975 function _deleteNotices()
977 $notice = new Notice();
978 $notice->profile_id = $this->id;
980 if ($notice->find()) {
981 while ($notice->fetch()) {
982 $other = clone($notice);
988 function _deleteSubscriptions()
990 $sub = new Subscription();
991 $sub->subscriber = $this->getID();
994 while ($sub->fetch()) {
996 $other = $sub->getSubscribed();
997 if (!$other->sameAs($this)) {
998 Subscription::cancel($this, $other);
1000 } catch (NoResultException $e) {
1001 // Profile not found
1002 common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
1003 } catch (ServerException $e) {
1004 // Subscription cancel failed
1005 common_log(LOG_INFO, 'Subscribed profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
1009 $sub = new Subscription();
1010 $sub->subscribed = $this->getID();
1013 while ($sub->fetch()) {
1015 $other = $sub->getSubscriber();
1016 common_log(LOG_INFO, 'Subscriber profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
1017 if (!$other->sameAs($this)) {
1018 Subscription::cancel($other, $this);
1020 } catch (NoResultException $e) {
1021 // Profile not found
1022 common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
1023 } catch (ServerException $e) {
1024 // Subscription cancel failed
1025 common_log(LOG_INFO, 'Subscriber profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
1029 // Finally delete self-subscription
1030 $self = new Subscription();
1031 $self->subscriber = $this->getID();
1032 $self->subscribed = $this->getID();
1036 function _deleteTags()
1038 $tag = new Profile_tag();
1039 $tag->tagged = $this->id;
1043 function _deleteBlocks()
1045 $block = new Profile_block();
1046 $block->blocked = $this->id;
1049 $block = new Group_block();
1050 $block->blocked = $this->id;
1054 function _deleteAttentions()
1056 $att = new Attention();
1057 $att->profile_id = $this->getID();
1060 while ($att->fetch()) {
1061 // Can't do delete() on the object directly since it won't remove all of it
1062 $other = clone($att);
1068 // XXX: identical to Notice::getLocation.
1070 public function getLocation()
1074 if (!empty($this->location_id) && !empty($this->location_ns)) {
1075 $location = Location::fromId($this->location_id, $this->location_ns);
1078 if (is_null($location)) { // no ID, or Location::fromId() failed
1079 if (!empty($this->lat) && !empty($this->lon)) {
1080 $location = Location::fromLatLon($this->lat, $this->lon);
1084 if (is_null($location)) { // still haven't found it!
1085 if (!empty($this->location)) {
1086 $location = Location::fromName($this->location);
1093 public function shareLocation()
1095 $cfg = common_config('location', 'share');
1097 if ($cfg == 'always') {
1099 } else if ($cfg == 'never') {
1102 $share = common_config('location', 'sharedefault');
1104 // Check if user has a personal setting for this
1105 $prefs = User_location_prefs::getKV('user_id', $this->id);
1107 if (!empty($prefs)) {
1108 $share = $prefs->share_location;
1116 function hasRole($name)
1119 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1120 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1122 $has_role = !empty($role);
1123 Event::handle('EndHasRole', array($this, $name, $has_role));
1128 function grantRole($name)
1130 if (Event::handle('StartGrantRole', array($this, $name))) {
1132 $role = new Profile_role();
1134 $role->profile_id = $this->id;
1135 $role->role = $name;
1136 $role->created = common_sql_now();
1138 $result = $role->insert();
1141 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1144 if ($name == 'owner') {
1145 User::blow('user:site_owner');
1148 Event::handle('EndGrantRole', array($this, $name));
1154 function revokeRole($name)
1156 if (Event::handle('StartRevokeRole', array($this, $name))) {
1158 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1162 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1163 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1164 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1167 $result = $role->delete();
1170 common_log_db_error($role, 'DELETE', __FILE__);
1171 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1172 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1173 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1176 if ($name == 'owner') {
1177 User::blow('user:site_owner');
1180 Event::handle('EndRevokeRole', array($this, $name));
1186 function isSandboxed()
1188 return $this->hasRole(Profile_role::SANDBOXED);
1191 function isSilenced()
1193 return $this->hasRole(Profile_role::SILENCED);
1198 $this->grantRole(Profile_role::SANDBOXED);
1201 function unsandbox()
1203 $this->revokeRole(Profile_role::SANDBOXED);
1208 $this->grantRole(Profile_role::SILENCED);
1209 if (common_config('notice', 'hidespam')) {
1210 $this->flushVisibility();
1214 function silenceAs(Profile $actor)
1216 if (!$actor->hasRight(Right::SILENCEUSER)) {
1217 throw new AuthorizationException(_('You cannot silence users on this site.'));
1219 // Only administrators can silence other privileged users (such as others who have the right to silence).
1220 if ($this->isPrivileged() && !$actor->hasRole(Profile_role::ADMINISTRATOR)) {
1221 throw new AuthorizationException(_('You cannot silence other privileged users.'));
1223 if ($this->isSilenced()) {
1224 // TRANS: Client error displayed trying to silence an already silenced user.
1225 throw new AlreadyFulfilledException(_('User is already silenced.'));
1227 return $this->silence();
1230 function unsilence()
1232 $this->revokeRole(Profile_role::SILENCED);
1233 if (common_config('notice', 'hidespam')) {
1234 $this->flushVisibility();
1238 function unsilenceAs(Profile $actor)
1240 if (!$actor->hasRight(Right::SILENCEUSER)) {
1241 // TRANS: Client error displayed trying to unsilence a user when the user does not have the right.
1242 throw new AuthorizationException(_('You cannot unsilence users on this site.'));
1244 if (!$this->isSilenced()) {
1245 // TRANS: Client error displayed trying to unsilence a user when the target user has not been silenced.
1246 throw new AlreadyFulfilledException(_('User is not silenced.'));
1248 return $this->unsilence();
1251 function flushVisibility()
1254 $stream = new ProfileNoticeStream($this, $this);
1255 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1256 foreach ($ids as $id) {
1257 self::blow('notice:in-scope-for:%d:null', $id);
1261 public function isPrivileged()
1263 // TODO: An Event::handle so plugins can report if users are privileged.
1264 // The ModHelper is the only one I care about when coding this, and that
1265 // can be tested with Right::SILENCEUSER which I do below:
1267 case $this->hasRight(Right::SILENCEUSER):
1268 case $this->hasRole(Profile_role::MODERATOR):
1269 case $this->hasRole(Profile_role::ADMINISTRATOR):
1270 case $this->hasRole(Profile_role::OWNER):
1278 * Does this user have the right to do X?
1280 * With our role-based authorization, this is merely a lookup for whether the user
1281 * has a particular role. The implementation currently uses a switch statement
1282 * to determine if the user has the pre-defined role to exercise the right. Future
1283 * implementations may allow per-site roles, and different mappings of roles to rights.
1285 * @param $right string Name of the right, usually a constant in class Right
1286 * @return boolean whether the user has the right in question
1288 public function hasRight($right)
1292 if ($this->hasRole(Profile_role::DELETED)) {
1296 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1299 case Right::DELETEOTHERSNOTICE:
1300 case Right::MAKEGROUPADMIN:
1301 case Right::SANDBOXUSER:
1302 case Right::SILENCEUSER:
1303 case Right::DELETEUSER:
1304 case Right::DELETEGROUP:
1305 case Right::TRAINSPAM:
1306 case Right::REVIEWSPAM:
1307 $result = $this->hasRole(Profile_role::MODERATOR);
1309 case Right::CONFIGURESITE:
1310 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1312 case Right::GRANTROLE:
1313 case Right::REVOKEROLE:
1314 $result = $this->hasRole(Profile_role::OWNER);
1316 case Right::NEWNOTICE:
1317 case Right::NEWMESSAGE:
1318 case Right::SUBSCRIBE:
1319 case Right::CREATEGROUP:
1320 $result = !$this->isSilenced();
1322 case Right::PUBLICNOTICE:
1323 case Right::EMAILONREPLY:
1324 case Right::EMAILONSUBSCRIBE:
1325 case Right::EMAILONFAVE:
1326 $result = !$this->isSandboxed() && !$this->isSilenced();
1328 case Right::WEBLOGIN:
1329 $result = !$this->isSilenced();
1332 $result = !$this->isSilenced();
1334 case Right::BACKUPACCOUNT:
1335 $result = common_config('profile', 'backup');
1337 case Right::RESTOREACCOUNT:
1338 $result = common_config('profile', 'restore');
1340 case Right::DELETEACCOUNT:
1341 $result = common_config('profile', 'delete');
1343 case Right::MOVEACCOUNT:
1344 $result = common_config('profile', 'move');
1354 // FIXME: Can't put Notice typing here due to ArrayWrapper
1355 public function hasRepeated($notice)
1357 // XXX: not really a pkey, but should work
1359 $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
1360 'repeat_of' => $notice->getID(),
1361 'verb' => ActivityVerb::SHARE));
1363 return !empty($notice);
1367 * Returns an XML string fragment with limited profile information
1368 * as an Atom <author> element.
1370 * Assumes that Atom has been previously set up as the base namespace.
1372 * @param Profile $cur the current authenticated user
1376 function asAtomAuthor($cur = null)
1378 $xs = new XMLStringer(true);
1380 $xs->elementStart('author');
1381 $xs->element('name', null, $this->nickname);
1382 $xs->element('uri', null, $this->getUri());
1385 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1386 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1387 $xs->element('statusnet:profile_info', $attrs, null);
1389 $xs->elementEnd('author');
1391 return $xs->getString();
1395 * Extra profile info for atom entries
1397 * Clients use some extra profile info in the atom stream.
1398 * This gives it to them.
1400 * @param Profile $scoped The currently logged in/scoped profile
1402 * @return array representation of <statusnet:profile_info> element or null
1405 function profileInfo(Profile $scoped=null)
1407 $profileInfoAttr = array('local_id' => $this->id);
1409 if ($scoped instanceof Profile) {
1410 // Whether the current user is a subscribed to this profile
1411 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1412 // Whether the current user is has blocked this profile
1413 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1416 return array('statusnet:profile_info', $profileInfoAttr, null);
1420 * Returns an XML string fragment with profile information as an
1421 * Activity Streams <activity:actor> element.
1423 * Assumes that 'activity' namespace has been previously defined.
1427 function asActivityActor()
1429 return $this->asActivityNoun('actor');
1433 * Returns an XML string fragment with profile information as an
1434 * Activity Streams noun object with the given element type.
1436 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1437 * previously defined.
1439 * @param string $element one of 'actor', 'subject', 'object', 'target'
1443 function asActivityNoun($element)
1445 $noun = $this->asActivityObject();
1446 return $noun->asString('activity:' . $element);
1449 public function asActivityObject()
1451 $object = new ActivityObject();
1453 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1454 $object->type = $this->getObjectType();
1455 $object->id = $this->getUri();
1456 $object->title = $this->getBestName();
1457 $object->link = $this->getUrl();
1458 $object->summary = $this->getDescription();
1461 $avatar = Avatar::getUploaded($this);
1462 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1463 } catch (NoAvatarException $e) {
1464 // Could not find an original avatar to link
1468 AVATAR_PROFILE_SIZE,
1473 foreach ($sizes as $size) {
1476 $avatar = Avatar::byProfile($this, $size);
1477 $alink = AvatarLink::fromAvatar($avatar);
1478 } catch (NoAvatarException $e) {
1479 $alink = new AvatarLink();
1480 $alink->type = 'image/png';
1481 $alink->height = $size;
1482 $alink->width = $size;
1483 $alink->url = Avatar::defaultImage($size);
1486 $object->avatarLinks[] = $alink;
1489 if (isset($this->lat) && isset($this->lon)) {
1490 $object->geopoint = (float)$this->lat
1491 . ' ' . (float)$this->lon;
1494 $object->poco = PoCo::fromProfile($this);
1496 if ($this->isLocal()) {
1497 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1500 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1507 * Returns the profile's canonical url, not necessarily a uri/unique id
1509 * @return string $profileurl
1511 public function getUrl()
1514 if ($this->isGroup()) {
1515 // FIXME: Get rid of this event, it fills no real purpose, data should be in Profile->profileurl (replaces User_group->mainpage)
1516 if (Event::handle('StartUserGroupHomeUrl', array($this->getGroup(), &$url))) {
1517 $url = $this->getGroup()->isLocal()
1518 ? common_local_url('showgroup', array('nickname' => $this->getNickname()))
1519 : $this->profileurl;
1521 Event::handle('EndUserGroupHomeUrl', array($this->getGroup(), $url));
1522 } elseif ($this->isLocal()) {
1523 $url = common_local_url('showstream', array('nickname' => $this->getNickname()));
1525 $url = $this->profileurl;
1528 !filter_var($url, FILTER_VALIDATE_URL)) {
1529 throw new InvalidUrlException($url);
1533 public function getHtmlTitle()
1536 return $this->getAcctUri(false);
1537 } catch (ProfileNoAcctUriException $e) {
1538 return $this->getNickname();
1542 public function getNickname()
1544 return $this->nickname;
1547 public function getFullname()
1549 return $this->fullname;
1552 public function getHomepage()
1554 return $this->homepage;
1557 public function getDescription()
1563 * Returns the best URI for a profile. Plugins may override.
1565 * @return string $uri
1567 public function getUri()
1571 // give plugins a chance to set the URI
1572 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1574 // check for a local user first
1575 $user = User::getKV('id', $this->id);
1576 if ($user instanceof User) {
1577 $uri = $user->getUri();
1579 $group = User_group::getKV('profile_id', $this->id);
1580 if ($group instanceof User_group) {
1581 $uri = $group->getUri();
1585 Event::handle('EndGetProfileUri', array($this, &$uri));
1592 * Returns an assumed acct: URI for a profile. Plugins are required.
1594 * @return string $uri
1596 public function getAcctUri($scheme=true)
1600 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1601 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1604 if ($acct === null) {
1605 throw new ProfileNoAcctUriException($this);
1607 if (parse_url($acct, PHP_URL_SCHEME) !== 'acct') {
1608 throw new ServerException('Acct URI does not have acct: scheme');
1611 // if we don't return the scheme, just remove the 'acct:' in the beginning
1612 return $scheme ? $acct : mb_substr($acct, 5);
1615 function hasBlocked(Profile $other)
1617 $block = Profile_block::exists($this, $other);
1618 return !empty($block);
1621 public function getAtomFeed()
1625 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1626 if ($this->isLocal()) {
1627 $feed = common_local_url('ApiTimelineUser', array('id' => $this->getID(),
1628 'format' => 'atom'));
1630 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1636 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1638 // TRANS: Exception thrown when trying view "repeated to me".
1639 throw new Exception(_('Not implemented since inbox change.'));
1643 * Get a Profile object by URI. Will call external plugins for help
1644 * using the event StartGetProfileFromURI.
1646 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1648 static function fromUri($uri)
1652 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1653 // Get a local user when plugin lookup (like OStatus) fails
1654 $user = User::getKV('uri', $uri);
1655 if ($user instanceof User) {
1656 $profile = $user->getProfile();
1658 $group = User_group::getKV('uri', $uri);
1659 if ($group instanceof User_group) {
1660 $profile = $group->getProfile();
1663 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1666 if (!$profile instanceof Profile) {
1667 throw new UnknownUriException($uri);
1673 function canRead(Notice $notice)
1675 if ($notice->scope & Notice::SITE_SCOPE) {
1676 $user = $this->getUser();
1682 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1683 $replies = $notice->getReplies();
1685 if (!in_array($this->id, $replies)) {
1686 $groups = $notice->getGroups();
1690 foreach ($groups as $group) {
1691 if ($this->isMember($group)) {
1703 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1704 $author = $notice->getProfile();
1705 if (!Subscription::exists($this, $author)) {
1713 static function current()
1715 $user = common_current_user();
1719 $profile = $user->getProfile();
1724 static function ensureCurrent()
1726 $profile = self::current();
1727 if (!$profile instanceof Profile) {
1728 throw new AuthorizationException('A currently scoped profile is required.');
1734 * Magic function called at serialize() time.
1736 * We use this to drop a couple process-specific references
1737 * from DB_DataObject which can cause trouble in future
1740 * @return array of variable names to include in serialization.
1745 $vars = parent::__sleep();
1746 $skip = array('_user', '_group');
1747 return array_diff($vars, $skip);
1750 public function getProfile()
1756 * Test whether the given profile is the same as the current class,
1757 * for testing identities.
1759 * @param Profile $other The other profile, usually from Action's $this->scoped
1763 public function sameAs(Profile $other=null)
1765 if (is_null($other)) {
1766 // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
1769 return $this->getID() === $other->getID();
1773 * This will perform shortenLinks with the connected User object.
1775 * Won't work on remote profiles or groups, so expect a
1776 * NoSuchUserException if you don't know it's a local User.
1778 * @param string $text String to shorten
1779 * @param boolean $always Disrespect minimum length etc.
1781 * @return string link-shortened $text
1783 public function shortenLinks($text, $always=false)
1785 return $this->getUser()->shortenLinks($text, $always);
1788 public function isPrivateStream()
1790 // We only know of public remote users as of yet...
1791 if (!$this->isLocal()) {
1794 return $this->getUser()->private_stream ? true : false;
1797 public function delPref($namespace, $topic) {
1798 return Profile_prefs::setData($this, $namespace, $topic, null);
1801 public function getPref($namespace, $topic, $default=null) {
1802 // If you want an exception to be thrown, call Profile_prefs::getData directly
1804 return Profile_prefs::getData($this, $namespace, $topic, $default);
1805 } catch (NoResultException $e) {
1810 // The same as getPref but will fall back to common_config value for the same namespace/topic
1811 public function getConfigPref($namespace, $topic)
1813 return Profile_prefs::getConfigData($this, $namespace, $topic);
1816 public function setPref($namespace, $topic, $data) {
1817 return Profile_prefs::setData($this, $namespace, $topic, $data);
1820 public function getConnectedApps($offset=0, $limit=null)
1822 return $this->getUser()->getConnectedApps($offset, $limit);