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 nickname as a parenthetical, or the nickname alone
222 * if no fullname is provided.
226 function getFancyName()
228 if ($this->fullname) {
229 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
230 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
232 return $this->nickname;
237 * Get the most recent notice posted by this user, if any.
239 * @return mixed Notice or null
241 function getCurrentNotice(Profile $scoped=null)
244 $notice = $this->getNotices(0, 1, 0, 0, $scoped);
246 if ($notice->fetch()) {
247 if ($notice instanceof ArrayWrapper) {
248 // hack for things trying to work with single notices
249 // ...but this shouldn't happen anymore I think. Keeping it for safety...
250 return $notice->_items[0];
254 } catch (PrivateStreamException $e) {
255 // Maybe we should let this through if it's handled well upstream
262 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
264 return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
267 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
269 $stream = new TaggedProfileNoticeStream($this, $tag);
271 return $stream->getNotices($offset, $limit, $since_id, $max_id);
274 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
276 $stream = new ProfileNoticeStream($this, $scoped);
278 return $stream->getNotices($offset, $limit, $since_id, $max_id);
281 function isMember(User_group $group)
283 $groups = $this->getGroups(0, null);
284 while ($groups instanceof User_group && $groups->fetch()) {
285 if ($groups->id == $group->id) {
292 function isAdmin(User_group $group)
294 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
295 'group_id' => $group->id));
296 return (!empty($gm) && $gm->is_admin);
299 function isPendingMember($group)
301 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
302 'group_id' => $group->id));
303 return !empty($request);
306 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
310 $keypart = sprintf('profile:groups:%d', $this->id);
312 $idstring = self::cacheGet($keypart);
314 if ($idstring !== false) {
315 $ids = explode(',', $idstring);
317 $gm = new Group_member();
319 $gm->profile_id = $this->id;
322 while ($gm->fetch()) {
323 $ids[] = $gm->group_id;
327 self::cacheSet($keypart, implode(',', $ids));
330 if (!is_null($offset) && !is_null($limit)) {
331 $ids = array_slice($ids, $offset, $limit);
335 return User_group::multiGet('id', $ids);
336 } catch (NoResultException $e) {
337 return null; // throw exception when we handle it everywhere
341 function getGroupCount() {
342 $groups = $this->getGroups(0, null);
343 return $groups instanceof User_group
348 function isTagged($peopletag)
350 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
351 'tagged' => $this->id,
352 'tag' => $peopletag->tag));
356 function canTag($tagged)
358 if (empty($tagged)) {
362 if ($tagged->id == $this->id) {
366 $all = common_config('peopletag', 'allow_tagging', 'all');
367 $local = common_config('peopletag', 'allow_tagging', 'local');
368 $remote = common_config('peopletag', 'allow_tagging', 'remote');
369 $subs = common_config('peopletag', 'allow_tagging', 'subs');
375 $tagged_user = $tagged->getUser();
376 if (!empty($tagged_user)) {
381 return (Subscription::exists($this, $tagged) ||
382 Subscription::exists($tagged, $this));
383 } else if ($remote) {
389 function getLists(Profile $scoped=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
393 $keypart = sprintf('profile:lists:%d', $this->id);
395 $idstr = self::cacheGet($keypart);
397 if ($idstr !== false) {
398 $ids = explode(',', $idstr);
400 $list = new Profile_list();
402 $list->selectAdd('id');
403 $list->tagger = $this->id;
404 $list->selectAdd('id as "cursor"');
407 $list->whereAdd('id > '.$since_id);
411 $list->whereAdd('id <= '.$max_id);
414 if($offset>=0 && !is_null($limit)) {
415 $list->limit($offset, $limit);
418 $list->orderBy('id DESC');
421 while ($list->fetch()) {
426 self::cacheSet($keypart, implode(',', $ids));
429 $showPrivate = $this->sameAs($scoped);
433 foreach ($ids as $id) {
434 $list = Profile_list::getKV('id', $id);
436 ($showPrivate || !$list->private)) {
438 if (!isset($list->cursor)) {
439 $list->cursor = $list->id;
446 return new ArrayWrapper($lists);
450 * Get tags that other people put on this profile, in reverse-chron order
452 * @param Profile $scoped User we are requesting as
453 * @param int $offset Offset from latest
454 * @param int $limit Max number to get
455 * @param datetime $since_id max date
456 * @param datetime $max_id min date
458 * @return Profile_list resulting lists
461 function getOtherTags(Profile $scoped=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
463 $list = new Profile_list();
465 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
466 'from profile_tag join profile_list '.
467 'on (profile_tag.tagger = profile_list.tagger ' .
468 ' and profile_tag.tag = profile_list.tag) ' .
469 'where profile_tag.tagged = %d ',
473 if (!is_null($scoped)) {
474 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
475 'OR ( profile_list.tagger = %d AND ' .
476 'profile_list.private = true ) )',
479 $qry .= 'AND profile_list.private = 0 ';
483 $qry .= sprintf('AND (cursor > %d) ', $since_id);
487 $qry .= sprintf('AND (cursor < %d) ', $max_id);
490 $qry .= 'ORDER BY profile_tag.modified DESC ';
492 if ($offset >= 0 && !is_null($limit)) {
493 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
500 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
502 $tags = new Profile_list();
503 $tags->private = true;
504 $tags->tagger = $this->id;
507 $tags->whereAdd('id > '.$since_id);
511 $tags->whereAdd('id <= '.$max_id);
514 if($offset>=0 && !is_null($limit)) {
515 $tags->limit($offset, $limit);
518 $tags->orderBy('id DESC');
524 function hasLocalTags()
526 $tags = new Profile_tag();
528 $tags->joinAdd(array('tagger', 'user:id'));
529 $tags->whereAdd('tagged = '.$this->id);
530 $tags->whereAdd('tagger != '.$this->id);
535 return ($tags->N == 0) ? false : true;
538 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
540 $lists = new Profile_list();
541 $subs = new Profile_tag_subscription();
543 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
545 #@fixme: postgres (round(date_part('epoch', my_date)))
546 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
548 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
551 $lists->whereAdd('cursor > '.$since_id);
555 $lists->whereAdd('cursor <= '.$max_id);
558 if($offset>=0 && !is_null($limit)) {
559 $lists->limit($offset, $limit);
562 $lists->orderBy('"cursor" DESC');
569 * Request to join the given group.
570 * May throw exceptions on failure.
572 * @param User_group $group
573 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
575 function joinGroup(User_group $group)
578 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
579 $join = Group_join_queue::saveNew($this, $group);
581 if (Event::handle('StartJoinGroup', array($group, $this))) {
582 $join = Group_member::join($group->id, $this->id);
583 self::blow('profile:groups:%d', $this->id);
584 self::blow('group:member_ids:%d', $group->id);
585 self::blow('group:member_count:%d', $group->id);
586 Event::handle('EndJoinGroup', array($group, $this));
590 // Send any applicable notifications...
597 * Leave a group that this profile is a member of.
599 * @param User_group $group
601 function leaveGroup(User_group $group)
603 if (Event::handle('StartLeaveGroup', array($group, $this))) {
604 Group_member::leave($group->id, $this->id);
605 self::blow('profile:groups:%d', $this->id);
606 self::blow('group:member_ids:%d', $group->id);
607 self::blow('group:member_count:%d', $group->id);
608 Event::handle('EndLeaveGroup', array($group, $this));
612 function avatarUrl($size=AVATAR_PROFILE_SIZE)
614 return Avatar::urlByProfile($this, $size);
617 function getSubscribed($offset=0, $limit=null)
619 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
621 $profiles = Profile::multiGet('id', $subs);
622 } catch (NoResultException $e) {
628 function getSubscribers($offset=0, $limit=null)
630 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
632 $profiles = Profile::multiGet('id', $subs);
633 } catch (NoResultException $e) {
639 function getTaggedSubscribers($tag, $offset=0, $limit=null)
642 'SELECT profile.* ' .
643 'FROM profile JOIN subscription ' .
644 'ON profile.id = subscription.subscriber ' .
645 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
646 'AND profile_tag.tagger = subscription.subscribed) ' .
647 'WHERE subscription.subscribed = %d ' .
648 "AND profile_tag.tag = '%s' " .
649 'AND subscription.subscribed != subscription.subscriber ' .
650 'ORDER BY subscription.created DESC ';
653 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
656 $profile = new Profile();
658 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
663 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
666 'SELECT profile.* ' .
667 'FROM profile JOIN subscription ' .
668 'ON profile.id = subscription.subscribed ' .
669 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
670 'AND profile_tag.tagger = subscription.subscriber) ' .
671 'WHERE subscription.subscriber = %d ' .
672 "AND profile_tag.tag = '%s' " .
673 'AND subscription.subscribed != subscription.subscriber ' .
674 'ORDER BY subscription.created DESC ';
676 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
678 $profile = new Profile();
680 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
686 * Get pending subscribers, who have not yet been approved.
692 function getRequests($offset=0, $limit=null)
695 $subqueue = new Profile();
696 $subqueue->joinAdd(array('id', 'subscription_queue:subscriber'));
697 $subqueue->whereAdd(sprintf('subscription_queue.subscribed = %d', $this->getID()));
698 $subqueue->limit($offset, $limit);
699 $subqueue->orderBy('subscription_queue.created', 'DESC');
700 if (!$subqueue->find()) {
701 throw new NoResultException($subqueue);
706 function subscriptionCount()
708 $c = Cache::instance();
711 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
712 if (is_integer($cnt)) {
717 $sub = new Subscription();
718 $sub->subscriber = $this->id;
720 $cnt = (int) $sub->count('distinct subscribed');
722 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
725 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
731 function subscriberCount()
733 $c = Cache::instance();
735 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
736 if (is_integer($cnt)) {
741 $sub = new Subscription();
742 $sub->subscribed = $this->id;
743 $sub->whereAdd('subscriber != subscribed');
744 $cnt = (int) $sub->count('distinct subscriber');
747 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
754 * Is this profile subscribed to another profile?
756 * @param Profile $other
759 function isSubscribed(Profile $other)
761 return Subscription::exists($this, $other);
764 function readableBy(Profile $other=null)
766 // If it's not a private stream, it's readable by anyone
767 if (!$this->isPrivateStream()) {
771 // If it's a private stream, $other must be a subscriber to $this
772 return is_null($other) ? false : $other->isSubscribed($this);
775 function requiresSubscriptionApproval(Profile $other=null)
777 if (!$this->isLocal()) {
778 // We don't know for remote users, and we'll always be able to send
779 // the request. Whether it'll work immediately or require moderation
780 // can be determined in another function.
784 // Assume that profiles _we_ subscribe to are permitted. Could be made configurable.
785 if (!is_null($other) && $this->isSubscribed($other)) {
789 // If the local user either has a private stream (implies the following)
790 // or user has a moderation policy for new subscriptions, return true.
791 return $this->getUser()->private_stream || $this->getUser()->subscribe_policy === User::SUBSCRIBE_POLICY_MODERATE;
795 * Check if a pending subscription request is outstanding for this...
797 * @param Profile $other
800 function hasPendingSubscription(Profile $other)
802 return Subscription_queue::exists($this, $other);
806 * Are these two profiles subscribed to each other?
808 * @param Profile $other
811 function mutuallySubscribed(Profile $other)
813 return $this->isSubscribed($other) &&
814 $other->isSubscribed($this);
817 function noticeCount()
819 $c = Cache::instance();
822 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
823 if (is_integer($cnt)) {
828 $notices = new Notice();
829 $notices->profile_id = $this->id;
830 $notices->verb = ActivityVerb::POST;
831 $cnt = (int) $notices->count('distinct id');
834 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
840 function blowSubscriberCount()
842 $c = Cache::instance();
844 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
848 function blowSubscriptionCount()
850 $c = Cache::instance();
852 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
856 function blowNoticeCount()
858 $c = Cache::instance();
860 $c->delete(Cache::key('profile:notice_count:'.$this->id));
864 static function maxBio()
866 $biolimit = common_config('profile', 'biolimit');
867 // null => use global limit (distinct from 0!)
868 if (is_null($biolimit)) {
869 $biolimit = common_config('site', 'textlimit');
874 static function bioTooLong($bio)
876 $biolimit = self::maxBio();
877 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
880 function update($dataObject=false)
882 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
884 $local = $this->getUser();
885 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
886 $origuser = clone($local);
887 $local->nickname = $this->nickname;
888 // updateWithKeys throws exception on failure.
889 $local->updateWithKeys($origuser);
891 // Clear the site owner, in case nickname changed
892 if ($local->hasRole(Profile_role::OWNER)) {
893 User::blow('user:site_owner');
895 } catch (NoSuchUserException $e) {
900 return parent::update($dataObject);
903 function delete($useWhere=false)
905 // just in case it hadn't been done before... (usually set before adding deluser to queue handling!)
906 if (!$this->hasRole(Profile_role::DELETED)) {
907 $this->grantRole(Profile_role::DELETED);
910 $this->_deleteNotices();
911 $this->_deleteSubscriptions();
912 $this->_deleteTags();
913 $this->_deleteBlocks();
914 $this->_deleteAttentions();
915 Avatar::deleteFromProfile($this, true);
917 // Warning: delete() will run on the batch objects,
918 // not on individual objects.
919 $related = array('Reply',
922 Event::handle('ProfileDeleteRelated', array($this, &$related));
924 foreach ($related as $cls) {
926 $inst->profile_id = $this->id;
930 $localuser = User::getKV('id', $this->id);
931 if ($localuser instanceof User) {
932 $localuser->delete();
935 return parent::delete($useWhere);
938 function _deleteNotices()
940 $notice = new Notice();
941 $notice->profile_id = $this->id;
943 if ($notice->find()) {
944 while ($notice->fetch()) {
945 $other = clone($notice);
951 function _deleteSubscriptions()
953 $sub = new Subscription();
954 $sub->subscriber = $this->getID();
957 while ($sub->fetch()) {
959 $other = $sub->getSubscribed();
960 if (!$other->sameAs($this)) {
961 Subscription::cancel($this, $other);
963 } catch (NoResultException $e) {
965 common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
966 } catch (ServerException $e) {
967 // Subscription cancel failed
968 common_log(LOG_INFO, 'Subscribed profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
972 $sub = new Subscription();
973 $sub->subscribed = $this->getID();
976 while ($sub->fetch()) {
978 $other = $sub->getSubscriber();
979 common_log(LOG_INFO, 'Subscriber profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
980 if (!$other->sameAs($this)) {
981 Subscription::cancel($other, $this);
983 } catch (NoResultException $e) {
985 common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
986 } catch (ServerException $e) {
987 // Subscription cancel failed
988 common_log(LOG_INFO, 'Subscriber profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
992 // Finally delete self-subscription
993 $self = new Subscription();
994 $self->subscriber = $this->getID();
995 $self->subscribed = $this->getID();
999 function _deleteTags()
1001 $tag = new Profile_tag();
1002 $tag->tagged = $this->id;
1006 function _deleteBlocks()
1008 $block = new Profile_block();
1009 $block->blocked = $this->id;
1012 $block = new Group_block();
1013 $block->blocked = $this->id;
1017 function _deleteAttentions()
1019 $att = new Attention();
1020 $att->profile_id = $this->getID();
1023 while ($att->fetch()) {
1024 // Can't do delete() on the object directly since it won't remove all of it
1025 $other = clone($att);
1031 // XXX: identical to Notice::getLocation.
1033 public function getLocation()
1037 if (!empty($this->location_id) && !empty($this->location_ns)) {
1038 $location = Location::fromId($this->location_id, $this->location_ns);
1041 if (is_null($location)) { // no ID, or Location::fromId() failed
1042 if (!empty($this->lat) && !empty($this->lon)) {
1043 $location = Location::fromLatLon($this->lat, $this->lon);
1047 if (is_null($location)) { // still haven't found it!
1048 if (!empty($this->location)) {
1049 $location = Location::fromName($this->location);
1056 public function shareLocation()
1058 $cfg = common_config('location', 'share');
1060 if ($cfg == 'always') {
1062 } else if ($cfg == 'never') {
1065 $share = common_config('location', 'sharedefault');
1067 // Check if user has a personal setting for this
1068 $prefs = User_location_prefs::getKV('user_id', $this->id);
1070 if (!empty($prefs)) {
1071 $share = $prefs->share_location;
1079 function hasRole($name)
1082 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1083 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1085 $has_role = !empty($role);
1086 Event::handle('EndHasRole', array($this, $name, $has_role));
1091 function grantRole($name)
1093 if (Event::handle('StartGrantRole', array($this, $name))) {
1095 $role = new Profile_role();
1097 $role->profile_id = $this->id;
1098 $role->role = $name;
1099 $role->created = common_sql_now();
1101 $result = $role->insert();
1104 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1107 if ($name == 'owner') {
1108 User::blow('user:site_owner');
1111 Event::handle('EndGrantRole', array($this, $name));
1117 function revokeRole($name)
1119 if (Event::handle('StartRevokeRole', array($this, $name))) {
1121 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1125 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1126 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1127 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1130 $result = $role->delete();
1133 common_log_db_error($role, 'DELETE', __FILE__);
1134 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1135 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1136 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1139 if ($name == 'owner') {
1140 User::blow('user:site_owner');
1143 Event::handle('EndRevokeRole', array($this, $name));
1149 function isSandboxed()
1151 return $this->hasRole(Profile_role::SANDBOXED);
1154 function isSilenced()
1156 return $this->hasRole(Profile_role::SILENCED);
1161 $this->grantRole(Profile_role::SANDBOXED);
1164 function unsandbox()
1166 $this->revokeRole(Profile_role::SANDBOXED);
1171 $this->grantRole(Profile_role::SILENCED);
1172 if (common_config('notice', 'hidespam')) {
1173 $this->flushVisibility();
1177 function silenceAs(Profile $actor)
1179 if (!$actor->hasRight(Right::SILENCEUSER)) {
1180 throw new AuthorizationException(_('You cannot silence users on this site.'));
1182 // Only administrators can silence other privileged users (such as others who have the right to silence).
1183 if ($this->isPrivileged() && !$actor->hasRole(Profile_role::ADMINISTRATOR)) {
1184 throw new AuthorizationException(_('You cannot silence other privileged users.'));
1186 if ($this->isSilenced()) {
1187 // TRANS: Client error displayed trying to silence an already silenced user.
1188 throw new AlreadyFulfilledException(_('User is already silenced.'));
1190 return $this->silence();
1193 function unsilence()
1195 $this->revokeRole(Profile_role::SILENCED);
1196 if (common_config('notice', 'hidespam')) {
1197 $this->flushVisibility();
1201 function unsilenceAs(Profile $actor)
1203 if (!$actor->hasRight(Right::SILENCEUSER)) {
1204 // TRANS: Client error displayed trying to unsilence a user when the user does not have the right.
1205 throw new AuthorizationException(_('You cannot unsilence users on this site.'));
1207 if (!$this->isSilenced()) {
1208 // TRANS: Client error displayed trying to unsilence a user when the target user has not been silenced.
1209 throw new AlreadyFulfilledException(_('User is not silenced.'));
1211 return $this->unsilence();
1214 function flushVisibility()
1217 $stream = new ProfileNoticeStream($this, $this);
1218 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1219 foreach ($ids as $id) {
1220 self::blow('notice:in-scope-for:%d:null', $id);
1224 public function isPrivileged()
1226 // TODO: An Event::handle so plugins can report if users are privileged.
1227 // The ModHelper is the only one I care about when coding this, and that
1228 // can be tested with Right::SILENCEUSER which I do below:
1230 case $this->hasRight(Right::SILENCEUSER):
1231 case $this->hasRole(Profile_role::MODERATOR):
1232 case $this->hasRole(Profile_role::ADMINISTRATOR):
1233 case $this->hasRole(Profile_role::OWNER):
1241 * Does this user have the right to do X?
1243 * With our role-based authorization, this is merely a lookup for whether the user
1244 * has a particular role. The implementation currently uses a switch statement
1245 * to determine if the user has the pre-defined role to exercise the right. Future
1246 * implementations may allow per-site roles, and different mappings of roles to rights.
1248 * @param $right string Name of the right, usually a constant in class Right
1249 * @return boolean whether the user has the right in question
1251 public function hasRight($right)
1255 if ($this->hasRole(Profile_role::DELETED)) {
1259 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1262 case Right::DELETEOTHERSNOTICE:
1263 case Right::MAKEGROUPADMIN:
1264 case Right::SANDBOXUSER:
1265 case Right::SILENCEUSER:
1266 case Right::DELETEUSER:
1267 case Right::DELETEGROUP:
1268 case Right::TRAINSPAM:
1269 case Right::REVIEWSPAM:
1270 $result = $this->hasRole(Profile_role::MODERATOR);
1272 case Right::CONFIGURESITE:
1273 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1275 case Right::GRANTROLE:
1276 case Right::REVOKEROLE:
1277 $result = $this->hasRole(Profile_role::OWNER);
1279 case Right::NEWNOTICE:
1280 case Right::NEWMESSAGE:
1281 case Right::SUBSCRIBE:
1282 case Right::CREATEGROUP:
1283 $result = !$this->isSilenced();
1285 case Right::PUBLICNOTICE:
1286 case Right::EMAILONREPLY:
1287 case Right::EMAILONSUBSCRIBE:
1288 case Right::EMAILONFAVE:
1289 $result = !$this->isSandboxed();
1291 case Right::WEBLOGIN:
1292 $result = !$this->isSilenced();
1295 $result = !$this->isSilenced();
1297 case Right::BACKUPACCOUNT:
1298 $result = common_config('profile', 'backup');
1300 case Right::RESTOREACCOUNT:
1301 $result = common_config('profile', 'restore');
1303 case Right::DELETEACCOUNT:
1304 $result = common_config('profile', 'delete');
1306 case Right::MOVEACCOUNT:
1307 $result = common_config('profile', 'move');
1317 // FIXME: Can't put Notice typing here due to ArrayWrapper
1318 public function hasRepeated($notice)
1320 // XXX: not really a pkey, but should work
1322 $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
1323 'repeat_of' => $notice->getID(),
1324 'verb' => ActivityVerb::SHARE));
1326 return !empty($notice);
1330 * Returns an XML string fragment with limited profile information
1331 * as an Atom <author> element.
1333 * Assumes that Atom has been previously set up as the base namespace.
1335 * @param Profile $cur the current authenticated user
1339 function asAtomAuthor($cur = null)
1341 $xs = new XMLStringer(true);
1343 $xs->elementStart('author');
1344 $xs->element('name', null, $this->nickname);
1345 $xs->element('uri', null, $this->getUri());
1348 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1349 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1350 $xs->element('statusnet:profile_info', $attrs, null);
1352 $xs->elementEnd('author');
1354 return $xs->getString();
1358 * Extra profile info for atom entries
1360 * Clients use some extra profile info in the atom stream.
1361 * This gives it to them.
1363 * @param Profile $scoped The currently logged in/scoped profile
1365 * @return array representation of <statusnet:profile_info> element or null
1368 function profileInfo(Profile $scoped=null)
1370 $profileInfoAttr = array('local_id' => $this->id);
1372 if ($scoped instanceof Profile) {
1373 // Whether the current user is a subscribed to this profile
1374 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1375 // Whether the current user is has blocked this profile
1376 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1379 return array('statusnet:profile_info', $profileInfoAttr, null);
1383 * Returns an XML string fragment with profile information as an
1384 * Activity Streams <activity:actor> element.
1386 * Assumes that 'activity' namespace has been previously defined.
1390 function asActivityActor()
1392 return $this->asActivityNoun('actor');
1396 * Returns an XML string fragment with profile information as an
1397 * Activity Streams noun object with the given element type.
1399 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1400 * previously defined.
1402 * @param string $element one of 'actor', 'subject', 'object', 'target'
1406 function asActivityNoun($element)
1408 $noun = $this->asActivityObject();
1409 return $noun->asString('activity:' . $element);
1412 public function asActivityObject()
1414 $object = new ActivityObject();
1416 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1417 $object->type = $this->getObjectType();
1418 $object->id = $this->getUri();
1419 $object->title = $this->getBestName();
1420 $object->link = $this->getUrl();
1421 $object->summary = $this->getDescription();
1424 $avatar = Avatar::getUploaded($this);
1425 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1426 } catch (NoAvatarException $e) {
1427 // Could not find an original avatar to link
1431 AVATAR_PROFILE_SIZE,
1436 foreach ($sizes as $size) {
1439 $avatar = Avatar::byProfile($this, $size);
1440 $alink = AvatarLink::fromAvatar($avatar);
1441 } catch (NoAvatarException $e) {
1442 $alink = new AvatarLink();
1443 $alink->type = 'image/png';
1444 $alink->height = $size;
1445 $alink->width = $size;
1446 $alink->url = Avatar::defaultImage($size);
1449 $object->avatarLinks[] = $alink;
1452 if (isset($this->lat) && isset($this->lon)) {
1453 $object->geopoint = (float)$this->lat
1454 . ' ' . (float)$this->lon;
1457 $object->poco = PoCo::fromProfile($this);
1459 if ($this->isLocal()) {
1460 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1463 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1470 * Returns the profile's canonical url, not necessarily a uri/unique id
1472 * @return string $profileurl
1474 public function getUrl()
1477 if ($this->isGroup()) {
1478 // FIXME: Get rid of this event, it fills no real purpose, data should be in Profile->profileurl (replaces User_group->mainpage)
1479 if (Event::handle('StartUserGroupHomeUrl', array($this->getGroup(), &$url))) {
1480 $url = $this->getGroup()->isLocal()
1481 ? common_local_url('showgroup', array('nickname' => $this->getNickname()))
1482 : $this->profileurl;
1484 Event::handle('EndUserGroupHomeUrl', array($this->getGroup(), $url));
1485 } elseif ($this->isLocal()) {
1486 $url = common_local_url('showstream', array('nickname' => $this->getNickname()));
1488 $url = $this->profileurl;
1491 !filter_var($url, FILTER_VALIDATE_URL)) {
1492 throw new InvalidUrlException($url);
1497 public function getNickname()
1499 return $this->nickname;
1502 public function getFullname()
1504 return $this->fullname;
1507 public function getHomepage()
1509 return $this->homepage;
1512 public function getDescription()
1518 * Returns the best URI for a profile. Plugins may override.
1520 * @return string $uri
1522 public function getUri()
1526 // give plugins a chance to set the URI
1527 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1529 // check for a local user first
1530 $user = User::getKV('id', $this->id);
1531 if ($user instanceof User) {
1532 $uri = $user->getUri();
1534 $group = User_group::getKV('profile_id', $this->id);
1535 if ($group instanceof User_group) {
1536 $uri = $group->getUri();
1540 Event::handle('EndGetProfileUri', array($this, &$uri));
1547 * Returns an assumed acct: URI for a profile. Plugins are required.
1549 * @return string $uri
1551 public function getAcctUri()
1555 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1556 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1559 if ($acct === null) {
1560 throw new ProfileNoAcctUriException($this);
1566 function hasBlocked($other)
1568 $block = Profile_block::exists($this, $other);
1569 return !empty($block);
1572 function getAtomFeed()
1576 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1577 $user = User::getKV('id', $this->id);
1578 if (!empty($user)) {
1579 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1580 'format' => 'atom'));
1582 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1588 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1590 // TRANS: Exception thrown when trying view "repeated to me".
1591 throw new Exception(_('Not implemented since inbox change.'));
1595 * Get a Profile object by URI. Will call external plugins for help
1596 * using the event StartGetProfileFromURI.
1598 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1600 static function fromUri($uri)
1604 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1605 // Get a local user when plugin lookup (like OStatus) fails
1606 $user = User::getKV('uri', $uri);
1607 if ($user instanceof User) {
1608 $profile = $user->getProfile();
1610 $group = User_group::getKV('uri', $uri);
1611 if ($group instanceof User_group) {
1612 $profile = $group->getProfile();
1615 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1618 if (!$profile instanceof Profile) {
1619 throw new UnknownUriException($uri);
1625 function canRead(Notice $notice)
1627 if ($notice->scope & Notice::SITE_SCOPE) {
1628 $user = $this->getUser();
1634 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1635 $replies = $notice->getReplies();
1637 if (!in_array($this->id, $replies)) {
1638 $groups = $notice->getGroups();
1642 foreach ($groups as $group) {
1643 if ($this->isMember($group)) {
1655 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1656 $author = $notice->getProfile();
1657 if (!Subscription::exists($this, $author)) {
1665 static function current()
1667 $user = common_current_user();
1671 $profile = $user->getProfile();
1676 static function ensureCurrent()
1678 $profile = self::current();
1679 if (!$profile instanceof Profile) {
1680 throw new AuthorizationException('A currently scoped profile is required.');
1686 * Magic function called at serialize() time.
1688 * We use this to drop a couple process-specific references
1689 * from DB_DataObject which can cause trouble in future
1692 * @return array of variable names to include in serialization.
1697 $vars = parent::__sleep();
1698 $skip = array('_user', '_group');
1699 return array_diff($vars, $skip);
1702 public function getProfile()
1708 * Test whether the given profile is the same as the current class,
1709 * for testing identities.
1711 * @param Profile $other The other profile, usually from Action's $this->scoped
1715 public function sameAs(Profile $other=null)
1717 if (is_null($other)) {
1718 // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
1721 return $this->getID() === $other->getID();
1725 * This will perform shortenLinks with the connected User object.
1727 * Won't work on remote profiles or groups, so expect a
1728 * NoSuchUserException if you don't know it's a local User.
1730 * @param string $text String to shorten
1731 * @param boolean $always Disrespect minimum length etc.
1733 * @return string link-shortened $text
1735 public function shortenLinks($text, $always=false)
1737 return $this->getUser()->shortenLinks($text, $always);
1740 public function isPrivateStream()
1742 // We only know of public remote users as of yet...
1743 if (!$this->isLocal()) {
1746 return $this->getUser()->private_stream ? true : false;
1749 public function delPref($namespace, $topic) {
1750 return Profile_prefs::setData($this, $namespace, $topic, null);
1753 public function getPref($namespace, $topic, $default=null) {
1754 // If you want an exception to be thrown, call Profile_prefs::getData directly
1756 return Profile_prefs::getData($this, $namespace, $topic, $default);
1757 } catch (NoResultException $e) {
1762 // The same as getPref but will fall back to common_config value for the same namespace/topic
1763 public function getConfigPref($namespace, $topic)
1765 return Profile_prefs::getConfigData($this, $namespace, $topic);
1768 public function setPref($namespace, $topic, $data) {
1769 return Profile_prefs::setData($this, $namespace, $topic, $data);
1772 public function getConnectedApps($offset=0, $limit=null)
1774 return $this->getUser()->getConnectedApps($offset, $limit);