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 $cur_user = common_current_user();
93 if (($cur_user instanceof User) && $cur_user->sameAs($this)) {
96 $user = User::getKV('id', $this->id);
97 if (!$user instanceof User) {
98 throw new NoSuchUserException(array('id'=>$this->id));
101 $this->_user[$this->id] = $user;
103 return $this->_user[$this->id];
106 protected $_group = array();
108 public function getGroup()
110 if (!isset($this->_group[$this->id])) {
111 $group = User_group::getKV('profile_id', $this->id);
112 if (!$group instanceof User_group) {
113 throw new NoSuchGroupException(array('profile_id'=>$this->id));
115 $this->_group[$this->id] = $group;
117 return $this->_group[$this->id];
120 public function isGroup()
125 } catch (NoSuchGroupException $e) {
130 public function isPerson()
132 // Maybe other things than PERSON and GROUP can have Profiles in the future?
133 return !$this->isGroup();
136 public function isLocal()
140 } catch (NoSuchUserException $e) {
146 // Returns false if the user has no password (which will always
147 // be the case for remote users). This can be the case for OpenID
148 // logins or other mechanisms which don't store a password hash.
149 public function hasPassword()
152 return $this->getUser()->hasPassword();
153 } catch (NoSuchUserException $e) {
158 public function getObjectType()
160 // FIXME: More types... like peopletags and whatever
161 if ($this->isGroup()) {
162 return ActivityObject::GROUP;
164 return ActivityObject::PERSON;
168 public function getAvatar($width, $height=null)
170 return Avatar::byProfile($this, $width, $height);
173 public function setOriginal($filename)
175 if ($this->isGroup()) {
176 // Until Group avatars are handled just like profile avatars.
177 return $this->getGroup()->setOriginal($filename);
180 $imagefile = new ImageFile(null, Avatar::path($filename));
182 $avatar = new Avatar();
183 $avatar->profile_id = $this->id;
184 $avatar->width = $imagefile->width;
185 $avatar->height = $imagefile->height;
186 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
187 $avatar->filename = $filename;
188 $avatar->original = true;
189 $avatar->created = common_sql_now();
191 // XXX: start a transaction here
192 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
193 // If we can't delete the old avatars, let's abort right here.
194 @unlink(Avatar::path($filename));
202 * Gets either the full name (if filled) or the nickname.
206 function getBestName()
208 return ($this->fullname) ? $this->fullname : $this->nickname;
212 * Takes the currently scoped profile into account to give a name
213 * to list in notice streams. Preferences may differ between profiles.
215 function getStreamName()
217 $user = common_current_user();
218 if ($user instanceof User && $user->streamNicknames()) {
219 return $this->nickname;
222 return $this->getBestName();
226 * Gets the full name (if filled) with acct URI, URL, or URI as a
227 * parenthetical (in that order, for each not found). If no full
228 * name is found only the second part is returned, without ()s.
232 function getFancyName()
236 $uri = $this->getAcctUri(false);
237 } catch (ProfileNoAcctUriException $e) {
239 $uri = $this->getUrl();
240 } catch (InvalidUrlException $e) {
241 $uri = $this->getUri();
245 if (mb_strlen($this->getFullname()) > 0) {
246 // TRANS: The "fancy name": Full name of a profile or group (%1$s) followed by some URI (%2$s) in parentheses.
247 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->getFullname(), $uri);
254 * Get the most recent notice posted by this user, if any.
256 * @return mixed Notice or null
258 function getCurrentNotice(Profile $scoped=null)
261 $notice = $this->getNotices(0, 1, 0, 0, $scoped);
263 if ($notice->fetch()) {
264 if ($notice instanceof ArrayWrapper) {
265 // hack for things trying to work with single notices
266 // ...but this shouldn't happen anymore I think. Keeping it for safety...
267 return $notice->_items[0];
271 } catch (PrivateStreamException $e) {
272 // Maybe we should let this through if it's handled well upstream
279 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
281 return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
284 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
286 //FIXME: Get Profile::current() some other way to avoid possible
287 // confusion between current session profile and background processing.
288 $stream = new TaggedProfileNoticeStream($this, $tag, Profile::current());
290 return $stream->getNotices($offset, $limit, $since_id, $max_id);
293 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
295 $stream = new ProfileNoticeStream($this, $scoped);
297 return $stream->getNotices($offset, $limit, $since_id, $max_id);
300 function isMember(User_group $group)
302 $groups = $this->getGroups(0, null);
303 while ($groups instanceof User_group && $groups->fetch()) {
304 if ($groups->id == $group->id) {
311 function isAdmin(User_group $group)
313 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
314 'group_id' => $group->id));
315 return (!empty($gm) && $gm->is_admin);
318 function isPendingMember($group)
320 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
321 'group_id' => $group->id));
322 return !empty($request);
325 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
329 $keypart = sprintf('profile:groups:%d', $this->id);
331 $idstring = self::cacheGet($keypart);
333 if ($idstring !== false) {
334 $ids = explode(',', $idstring);
336 $gm = new Group_member();
338 $gm->profile_id = $this->id;
341 while ($gm->fetch()) {
342 $ids[] = $gm->group_id;
346 self::cacheSet($keypart, implode(',', $ids));
349 if (!is_null($offset) && !is_null($limit)) {
350 $ids = array_slice($ids, $offset, $limit);
354 return User_group::multiGet('id', $ids);
355 } catch (NoResultException $e) {
356 return null; // throw exception when we handle it everywhere
360 function getGroupCount() {
361 $groups = $this->getGroups(0, null);
362 return $groups instanceof User_group
367 function isTagged($peopletag)
369 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
370 'tagged' => $this->id,
371 'tag' => $peopletag->tag));
375 function canTag($tagged)
377 if (empty($tagged)) {
381 if ($tagged->id == $this->id) {
385 $all = common_config('peopletag', 'allow_tagging', 'all');
386 $local = common_config('peopletag', 'allow_tagging', 'local');
387 $remote = common_config('peopletag', 'allow_tagging', 'remote');
388 $subs = common_config('peopletag', 'allow_tagging', 'subs');
394 $tagged_user = $tagged->getUser();
395 if (!empty($tagged_user)) {
400 return (Subscription::exists($this, $tagged) ||
401 Subscription::exists($tagged, $this));
402 } else if ($remote) {
408 function getLists(Profile $scoped=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
412 $keypart = sprintf('profile:lists:%d', $this->id);
414 $idstr = self::cacheGet($keypart);
416 if ($idstr !== false) {
417 $ids = explode(',', $idstr);
419 $list = new Profile_list();
421 $list->selectAdd('id');
422 $list->tagger = $this->id;
423 $list->selectAdd('id as "cursor"');
426 $list->whereAdd('id > '.$since_id);
430 $list->whereAdd('id <= '.$max_id);
433 if($offset>=0 && !is_null($limit)) {
434 $list->limit($offset, $limit);
437 $list->orderBy('id DESC');
440 while ($list->fetch()) {
445 self::cacheSet($keypart, implode(',', $ids));
448 $showPrivate = $this->sameAs($scoped);
452 foreach ($ids as $id) {
453 $list = Profile_list::getKV('id', $id);
455 ($showPrivate || !$list->private)) {
457 if (!isset($list->cursor)) {
458 $list->cursor = $list->id;
465 return new ArrayWrapper($lists);
469 * Get tags that other people put on this profile, in reverse-chron order
471 * @param Profile $scoped User we are requesting as
472 * @param int $offset Offset from latest
473 * @param int $limit Max number to get
474 * @param datetime $since_id max date
475 * @param datetime $max_id min date
477 * @return Profile_list resulting lists
480 function getOtherTags(Profile $scoped=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
482 $list = new Profile_list();
484 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
485 'from profile_tag join profile_list '.
486 'on (profile_tag.tagger = profile_list.tagger ' .
487 ' and profile_tag.tag = profile_list.tag) ' .
488 'where profile_tag.tagged = %d ',
492 if (!is_null($scoped)) {
493 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
494 'OR ( profile_list.tagger = %d AND ' .
495 'profile_list.private = true ) )',
498 $qry .= 'AND profile_list.private = 0 ';
502 $qry .= sprintf('AND (cursor > %d) ', $since_id);
506 $qry .= sprintf('AND (cursor < %d) ', $max_id);
509 $qry .= 'ORDER BY profile_tag.modified DESC ';
511 if ($offset >= 0 && !is_null($limit)) {
512 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
519 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
521 $tags = new Profile_list();
522 $tags->private = true;
523 $tags->tagger = $this->id;
526 $tags->whereAdd('id > '.$since_id);
530 $tags->whereAdd('id <= '.$max_id);
533 if($offset>=0 && !is_null($limit)) {
534 $tags->limit($offset, $limit);
537 $tags->orderBy('id DESC');
543 function hasLocalTags()
545 $tags = new Profile_tag();
547 $tags->joinAdd(array('tagger', 'user:id'));
548 $tags->whereAdd('tagged = '.$this->id);
549 $tags->whereAdd('tagger != '.$this->id);
554 return ($tags->N == 0) ? false : true;
557 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
559 $lists = new Profile_list();
560 $subs = new Profile_tag_subscription();
562 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
564 #@fixme: postgres (round(date_part('epoch', my_date)))
565 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
567 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
570 $lists->whereAdd('cursor > '.$since_id);
574 $lists->whereAdd('cursor <= '.$max_id);
577 if($offset>=0 && !is_null($limit)) {
578 $lists->limit($offset, $limit);
581 $lists->orderBy('"cursor" DESC');
588 * Request to join the given group.
589 * May throw exceptions on failure.
591 * @param User_group $group
592 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
594 function joinGroup(User_group $group)
597 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
598 $join = Group_join_queue::saveNew($this, $group);
600 if (Event::handle('StartJoinGroup', array($group, $this))) {
601 $join = Group_member::join($group->id, $this->id);
602 self::blow('profile:groups:%d', $this->id);
603 self::blow('group:member_ids:%d', $group->id);
604 self::blow('group:member_count:%d', $group->id);
605 Event::handle('EndJoinGroup', array($group, $this));
609 // Send any applicable notifications...
616 * Leave a group that this profile is a member of.
618 * @param User_group $group
620 function leaveGroup(User_group $group)
622 if (Event::handle('StartLeaveGroup', array($group, $this))) {
623 Group_member::leave($group->id, $this->id);
624 self::blow('profile:groups:%d', $this->id);
625 self::blow('group:member_ids:%d', $group->id);
626 self::blow('group:member_count:%d', $group->id);
627 Event::handle('EndLeaveGroup', array($group, $this));
631 function avatarUrl($size=AVATAR_PROFILE_SIZE)
633 return Avatar::urlByProfile($this, $size);
636 function getSubscribed($offset=0, $limit=null)
638 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
640 $profiles = Profile::multiGet('id', $subs);
641 } catch (NoResultException $e) {
647 function getSubscribers($offset=0, $limit=null)
649 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
651 $profiles = Profile::multiGet('id', $subs);
652 } catch (NoResultException $e) {
658 function getTaggedSubscribers($tag, $offset=0, $limit=null)
661 'SELECT profile.* ' .
662 'FROM profile JOIN subscription ' .
663 'ON profile.id = subscription.subscriber ' .
664 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
665 'AND profile_tag.tagger = subscription.subscribed) ' .
666 'WHERE subscription.subscribed = %d ' .
667 "AND profile_tag.tag = '%s' " .
668 'AND subscription.subscribed != subscription.subscriber ' .
669 'ORDER BY subscription.created DESC ';
672 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
675 $profile = new Profile();
677 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
682 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
685 'SELECT profile.* ' .
686 'FROM profile JOIN subscription ' .
687 'ON profile.id = subscription.subscribed ' .
688 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
689 'AND profile_tag.tagger = subscription.subscriber) ' .
690 'WHERE subscription.subscriber = %d ' .
691 "AND profile_tag.tag = '%s' " .
692 'AND subscription.subscribed != subscription.subscriber ' .
693 'ORDER BY subscription.created DESC ';
695 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
697 $profile = new Profile();
699 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
705 * Get pending subscribers, who have not yet been approved.
711 function getRequests($offset=0, $limit=null)
714 $subqueue = new Profile();
715 $subqueue->joinAdd(array('id', 'subscription_queue:subscriber'));
716 $subqueue->whereAdd(sprintf('subscription_queue.subscribed = %d', $this->getID()));
717 $subqueue->limit($offset, $limit);
718 $subqueue->orderBy('subscription_queue.created', 'DESC');
719 if (!$subqueue->find()) {
720 throw new NoResultException($subqueue);
725 function subscriptionCount()
727 $c = Cache::instance();
730 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
731 if (is_integer($cnt)) {
736 $sub = new Subscription();
737 $sub->subscriber = $this->id;
739 $cnt = (int) $sub->count('distinct subscribed');
741 // Local users are subscribed to themselves
742 if ($this->isLocal()) {
743 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
747 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
753 function subscriberCount()
755 $c = Cache::instance();
757 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
758 if (is_integer($cnt)) {
763 $sub = new Subscription();
764 $sub->subscribed = $this->id;
765 $sub->whereAdd('subscriber != subscribed');
766 $cnt = (int) $sub->count('distinct subscriber');
769 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
776 * Is this profile subscribed to another profile?
778 * @param Profile $other
781 function isSubscribed(Profile $other)
783 return Subscription::exists($this, $other);
786 function readableBy(Profile $other=null)
788 // If it's not a private stream, it's readable by anyone
789 if (!$this->isPrivateStream()) {
793 // If it's a private stream, $other must be a subscriber to $this
794 return is_null($other) ? false : $other->isSubscribed($this);
797 function requiresSubscriptionApproval(Profile $other=null)
799 if (!$this->isLocal()) {
800 // We don't know for remote users, and we'll always be able to send
801 // the request. Whether it'll work immediately or require moderation
802 // can be determined in another function.
806 // Assume that profiles _we_ subscribe to are permitted. Could be made configurable.
807 if (!is_null($other) && $this->isSubscribed($other)) {
811 // If the local user either has a private stream (implies the following)
812 // or user has a moderation policy for new subscriptions, return true.
813 return $this->getUser()->private_stream || $this->getUser()->subscribe_policy === User::SUBSCRIBE_POLICY_MODERATE;
817 * Check if a pending subscription request is outstanding for this...
819 * @param Profile $other
822 function hasPendingSubscription(Profile $other)
824 return Subscription_queue::exists($this, $other);
828 * Are these two profiles subscribed to each other?
830 * @param Profile $other
833 function mutuallySubscribed(Profile $other)
835 return $this->isSubscribed($other) &&
836 $other->isSubscribed($this);
839 function noticeCount()
841 $c = Cache::instance();
844 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->getID()));
845 if (is_integer($cnt)) {
850 $notices = new Notice();
851 $notices->profile_id = $this->getID();
852 $notices->verb = ActivityVerb::POST;
853 $cnt = (int) $notices->count('id'); // Not sure if I imagine this, but 'id' was faster than the defaulting 'uri'?
856 $c->set(Cache::key('profile:notice_count:'.$this->getID()), $cnt);
862 function blowSubscriberCount()
864 $c = Cache::instance();
866 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
870 function blowSubscriptionCount()
872 $c = Cache::instance();
874 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
878 function blowNoticeCount()
880 $c = Cache::instance();
882 $c->delete(Cache::key('profile:notice_count:'.$this->id));
886 static function maxBio()
888 $biolimit = common_config('profile', 'biolimit');
889 // null => use global limit (distinct from 0!)
890 if (is_null($biolimit)) {
891 $biolimit = common_config('site', 'textlimit');
896 static function bioTooLong($bio)
898 $biolimit = self::maxBio();
899 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
902 function update($dataObject=false)
904 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
906 $local = $this->getUser();
907 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
908 $origuser = clone($local);
909 $local->nickname = $this->nickname;
910 // updateWithKeys throws exception on failure.
911 $local->updateWithKeys($origuser);
913 // Clear the site owner, in case nickname changed
914 if ($local->hasRole(Profile_role::OWNER)) {
915 User::blow('user:site_owner');
917 } catch (NoSuchUserException $e) {
922 return parent::update($dataObject);
925 public function getRelSelf()
927 return ['href' => $this->getUrl(),
928 'text' => common_config('site', 'name'),
929 'image' => Avatar::urlByProfile($this)];
932 // All the known rel="me", used for the IndieWeb audience
933 public function getRelMes()
937 $relMes[] = $this->getRelSelf();
938 } catch (InvalidUrlException $e) {
939 // no valid profile URL available
941 if (common_valid_http_url($this->getHomepage())) {
942 $relMes[] = ['href' => $this->getHomepage(),
943 'text' => _('Homepage'),
946 Event::handle('OtherAccountProfiles', array($this, &$relMes));
950 function delete($useWhere=false)
952 $this->_deleteNotices();
953 $this->_deleteSubscriptions();
954 $this->_deleteTags();
955 $this->_deleteBlocks();
956 $this->_deleteAttentions();
957 Avatar::deleteFromProfile($this, true);
959 // Warning: delete() will run on the batch objects,
960 // not on individual objects.
961 $related = array('Reply',
965 Event::handle('ProfileDeleteRelated', array($this, &$related));
967 foreach ($related as $cls) {
969 $inst->profile_id = $this->id;
973 $this->grantRole(Profile_role::DELETED);
975 $localuser = User::getKV('id', $this->id);
976 if ($localuser instanceof User) {
977 $localuser->delete();
980 return parent::delete($useWhere);
983 function _deleteNotices()
985 $notice = new Notice();
986 $notice->profile_id = $this->id;
988 if ($notice->find()) {
989 while ($notice->fetch()) {
990 $other = clone($notice);
996 function _deleteSubscriptions()
998 $sub = new Subscription();
999 $sub->subscriber = $this->getID();
1002 while ($sub->fetch()) {
1004 $other = $sub->getSubscribed();
1005 if (!$other->sameAs($this)) {
1006 Subscription::cancel($this, $other);
1008 } catch (NoResultException $e) {
1009 // Profile not found
1010 common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
1011 } catch (ServerException $e) {
1012 // Subscription cancel failed
1013 common_log(LOG_INFO, 'Subscribed profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
1017 $sub = new Subscription();
1018 $sub->subscribed = $this->getID();
1021 while ($sub->fetch()) {
1023 $other = $sub->getSubscriber();
1024 common_log(LOG_INFO, 'Subscriber profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
1025 if (!$other->sameAs($this)) {
1026 Subscription::cancel($other, $this);
1028 } catch (NoResultException $e) {
1029 // Profile not found
1030 common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
1031 } catch (ServerException $e) {
1032 // Subscription cancel failed
1033 common_log(LOG_INFO, 'Subscriber profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
1037 // Finally delete self-subscription
1038 $self = new Subscription();
1039 $self->subscriber = $this->getID();
1040 $self->subscribed = $this->getID();
1044 function _deleteTags()
1046 $tag = new Profile_tag();
1047 $tag->tagged = $this->id;
1051 function _deleteBlocks()
1053 $block = new Profile_block();
1054 $block->blocked = $this->id;
1057 $block = new Group_block();
1058 $block->blocked = $this->id;
1062 function _deleteAttentions()
1064 $att = new Attention();
1065 $att->profile_id = $this->getID();
1068 while ($att->fetch()) {
1069 // Can't do delete() on the object directly since it won't remove all of it
1070 $other = clone($att);
1076 // XXX: identical to Notice::getLocation.
1078 public function getLocation()
1082 if (!empty($this->location_id) && !empty($this->location_ns)) {
1083 $location = Location::fromId($this->location_id, $this->location_ns);
1086 if (is_null($location)) { // no ID, or Location::fromId() failed
1087 if (!empty($this->lat) && !empty($this->lon)) {
1088 $location = Location::fromLatLon($this->lat, $this->lon);
1092 if (is_null($location)) { // still haven't found it!
1093 if (!empty($this->location)) {
1094 $location = Location::fromName($this->location);
1101 public function shareLocation()
1103 $cfg = common_config('location', 'share');
1105 if ($cfg == 'always') {
1107 } else if ($cfg == 'never') {
1110 $share = common_config('location', 'sharedefault');
1112 // Check if user has a personal setting for this
1113 $prefs = User_location_prefs::getKV('user_id', $this->id);
1115 if (!empty($prefs)) {
1116 $share = $prefs->share_location;
1124 function hasRole($name)
1127 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1128 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1130 $has_role = !empty($role);
1131 Event::handle('EndHasRole', array($this, $name, $has_role));
1136 function grantRole($name)
1138 if (Event::handle('StartGrantRole', array($this, $name))) {
1140 $role = new Profile_role();
1142 $role->profile_id = $this->id;
1143 $role->role = $name;
1144 $role->created = common_sql_now();
1146 $result = $role->insert();
1149 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1152 if ($name == 'owner') {
1153 User::blow('user:site_owner');
1156 Event::handle('EndGrantRole', array($this, $name));
1162 function revokeRole($name)
1164 if (Event::handle('StartRevokeRole', array($this, $name))) {
1166 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1170 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1171 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1172 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1175 $result = $role->delete();
1178 common_log_db_error($role, 'DELETE', __FILE__);
1179 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1180 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1181 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1184 if ($name == 'owner') {
1185 User::blow('user:site_owner');
1188 Event::handle('EndRevokeRole', array($this, $name));
1194 function isSandboxed()
1196 return $this->hasRole(Profile_role::SANDBOXED);
1199 function isSilenced()
1201 return $this->hasRole(Profile_role::SILENCED);
1206 $this->grantRole(Profile_role::SANDBOXED);
1209 function unsandbox()
1211 $this->revokeRole(Profile_role::SANDBOXED);
1216 $this->grantRole(Profile_role::SILENCED);
1217 if (common_config('notice', 'hidespam')) {
1218 $this->flushVisibility();
1222 function silenceAs(Profile $actor)
1224 if (!$actor->hasRight(Right::SILENCEUSER)) {
1225 throw new AuthorizationException(_('You cannot silence users on this site.'));
1227 // Only administrators can silence other privileged users (such as others who have the right to silence).
1228 if ($this->isPrivileged() && !$actor->hasRole(Profile_role::ADMINISTRATOR)) {
1229 throw new AuthorizationException(_('You cannot silence other privileged users.'));
1231 if ($this->isSilenced()) {
1232 // TRANS: Client error displayed trying to silence an already silenced user.
1233 throw new AlreadyFulfilledException(_('User is already silenced.'));
1235 return $this->silence();
1238 function unsilence()
1240 $this->revokeRole(Profile_role::SILENCED);
1241 if (common_config('notice', 'hidespam')) {
1242 $this->flushVisibility();
1246 function unsilenceAs(Profile $actor)
1248 if (!$actor->hasRight(Right::SILENCEUSER)) {
1249 // TRANS: Client error displayed trying to unsilence a user when the user does not have the right.
1250 throw new AuthorizationException(_('You cannot unsilence users on this site.'));
1252 if (!$this->isSilenced()) {
1253 // TRANS: Client error displayed trying to unsilence a user when the target user has not been silenced.
1254 throw new AlreadyFulfilledException(_('User is not silenced.'));
1256 return $this->unsilence();
1259 function flushVisibility()
1262 $stream = new ProfileNoticeStream($this, $this);
1263 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1264 foreach ($ids as $id) {
1265 self::blow('notice:in-scope-for:%d:null', $id);
1269 public function isPrivileged()
1271 // TODO: An Event::handle so plugins can report if users are privileged.
1272 // The ModHelper is the only one I care about when coding this, and that
1273 // can be tested with Right::SILENCEUSER which I do below:
1275 case $this->hasRight(Right::SILENCEUSER):
1276 case $this->hasRole(Profile_role::MODERATOR):
1277 case $this->hasRole(Profile_role::ADMINISTRATOR):
1278 case $this->hasRole(Profile_role::OWNER):
1286 * Does this user have the right to do X?
1288 * With our role-based authorization, this is merely a lookup for whether the user
1289 * has a particular role. The implementation currently uses a switch statement
1290 * to determine if the user has the pre-defined role to exercise the right. Future
1291 * implementations may allow per-site roles, and different mappings of roles to rights.
1293 * @param $right string Name of the right, usually a constant in class Right
1294 * @return boolean whether the user has the right in question
1296 public function hasRight($right)
1300 if ($this->hasRole(Profile_role::DELETED)) {
1304 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1307 case Right::DELETEOTHERSNOTICE:
1308 case Right::MAKEGROUPADMIN:
1309 case Right::SANDBOXUSER:
1310 case Right::SILENCEUSER:
1311 case Right::DELETEUSER:
1312 case Right::DELETEGROUP:
1313 case Right::TRAINSPAM:
1314 case Right::REVIEWSPAM:
1315 $result = $this->hasRole(Profile_role::MODERATOR);
1317 case Right::CONFIGURESITE:
1318 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1320 case Right::GRANTROLE:
1321 case Right::REVOKEROLE:
1322 $result = $this->hasRole(Profile_role::OWNER);
1324 case Right::NEWNOTICE:
1325 case Right::NEWMESSAGE:
1326 case Right::SUBSCRIBE:
1327 case Right::CREATEGROUP:
1328 $result = !$this->isSilenced();
1330 case Right::PUBLICNOTICE:
1331 case Right::EMAILONREPLY:
1332 case Right::EMAILONSUBSCRIBE:
1333 case Right::EMAILONFAVE:
1334 $result = !$this->isSandboxed() && !$this->isSilenced();
1336 case Right::WEBLOGIN:
1337 $result = !$this->isSilenced();
1340 $result = !$this->isSilenced();
1342 case Right::BACKUPACCOUNT:
1343 $result = common_config('profile', 'backup');
1345 case Right::RESTOREACCOUNT:
1346 $result = common_config('profile', 'restore');
1348 case Right::DELETEACCOUNT:
1349 $result = common_config('profile', 'delete');
1351 case Right::MOVEACCOUNT:
1352 $result = common_config('profile', 'move');
1362 // FIXME: Can't put Notice typing here due to ArrayWrapper
1363 public function hasRepeated($notice)
1365 // XXX: not really a pkey, but should work
1367 $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
1368 'repeat_of' => $notice->getID(),
1369 'verb' => ActivityVerb::SHARE));
1371 return !empty($notice);
1375 * Returns an XML string fragment with limited profile information
1376 * as an Atom <author> element.
1378 * Assumes that Atom has been previously set up as the base namespace.
1380 * @param Profile $cur the current authenticated user
1384 function asAtomAuthor($cur = null)
1386 $xs = new XMLStringer(true);
1388 $xs->elementStart('author');
1389 $xs->element('name', null, $this->nickname);
1390 $xs->element('uri', null, $this->getUri());
1393 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1394 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1395 $xs->element('statusnet:profile_info', $attrs, null);
1397 $xs->elementEnd('author');
1399 return $xs->getString();
1403 * Extra profile info for atom entries
1405 * Clients use some extra profile info in the atom stream.
1406 * This gives it to them.
1408 * @param Profile $scoped The currently logged in/scoped profile
1410 * @return array representation of <statusnet:profile_info> element or null
1413 function profileInfo(Profile $scoped=null)
1415 $profileInfoAttr = array('local_id' => $this->id);
1417 if ($scoped instanceof Profile) {
1418 // Whether the current user is a subscribed to this profile
1419 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1420 // Whether the current user is has blocked this profile
1421 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1424 return array('statusnet:profile_info', $profileInfoAttr, null);
1428 * Returns an XML string fragment with profile information as an
1429 * Activity Streams <activity:actor> element.
1431 * Assumes that 'activity' namespace has been previously defined.
1435 function asActivityActor()
1437 return $this->asActivityNoun('actor');
1441 * Returns an XML string fragment with profile information as an
1442 * Activity Streams noun object with the given element type.
1444 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1445 * previously defined.
1447 * @param string $element one of 'actor', 'subject', 'object', 'target'
1451 function asActivityNoun($element)
1453 $noun = $this->asActivityObject();
1454 return $noun->asString('activity:' . $element);
1457 public function asActivityObject()
1459 $object = new ActivityObject();
1461 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1462 $object->type = $this->getObjectType();
1463 $object->id = $this->getUri();
1464 $object->title = $this->getBestName();
1465 $object->link = $this->getUrl();
1466 $object->summary = $this->getDescription();
1469 $avatar = Avatar::getUploaded($this);
1470 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1471 } catch (NoAvatarException $e) {
1472 // Could not find an original avatar to link
1476 AVATAR_PROFILE_SIZE,
1481 foreach ($sizes as $size) {
1484 $avatar = Avatar::byProfile($this, $size);
1485 $alink = AvatarLink::fromAvatar($avatar);
1486 } catch (NoAvatarException $e) {
1487 $alink = new AvatarLink();
1488 $alink->type = 'image/png';
1489 $alink->height = $size;
1490 $alink->width = $size;
1491 $alink->url = Avatar::defaultImage($size);
1494 $object->avatarLinks[] = $alink;
1497 if (isset($this->lat) && isset($this->lon)) {
1498 $object->geopoint = (float)$this->lat
1499 . ' ' . (float)$this->lon;
1502 $object->poco = PoCo::fromProfile($this);
1504 if ($this->isLocal()) {
1505 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1508 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1515 * Returns the profile's canonical url, not necessarily a uri/unique id
1517 * @return string $profileurl
1519 public function getUrl()
1522 if ($this->isGroup()) {
1523 // FIXME: Get rid of this event, it fills no real purpose, data should be in Profile->profileurl (replaces User_group->mainpage)
1524 if (Event::handle('StartUserGroupHomeUrl', array($this->getGroup(), &$url))) {
1525 $url = $this->getGroup()->isLocal()
1526 ? common_local_url('showgroup', array('nickname' => $this->getNickname()))
1527 : $this->profileurl;
1529 Event::handle('EndUserGroupHomeUrl', array($this->getGroup(), $url));
1530 } elseif ($this->isLocal()) {
1531 $url = common_local_url('showstream', array('nickname' => $this->getNickname()));
1533 $url = $this->profileurl;
1536 !filter_var($url, FILTER_VALIDATE_URL)) {
1537 throw new InvalidUrlException($url);
1541 public function getHtmlTitle()
1544 return $this->getAcctUri(false);
1545 } catch (ProfileNoAcctUriException $e) {
1546 return $this->getNickname();
1550 public function getNickname()
1552 return $this->nickname;
1555 public function getFullname()
1557 return $this->fullname;
1560 public function getHomepage()
1562 return $this->homepage;
1565 public function getDescription()
1571 * Returns the best URI for a profile. Plugins may override.
1573 * @return string $uri
1575 public function getUri()
1579 // give plugins a chance to set the URI
1580 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1582 // check for a local user first
1583 $user = User::getKV('id', $this->id);
1584 if ($user instanceof User) {
1585 $uri = $user->getUri();
1587 $group = User_group::getKV('profile_id', $this->id);
1588 if ($group instanceof User_group) {
1589 $uri = $group->getUri();
1593 Event::handle('EndGetProfileUri', array($this, &$uri));
1600 * Returns an assumed acct: URI for a profile. Plugins are required.
1602 * @return string $uri
1604 public function getAcctUri($scheme=true)
1608 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1609 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1612 if ($acct === null) {
1613 throw new ProfileNoAcctUriException($this);
1615 if (parse_url($acct, PHP_URL_SCHEME) !== 'acct') {
1616 throw new ServerException('Acct URI does not have acct: scheme');
1619 // if we don't return the scheme, just remove the 'acct:' in the beginning
1620 return $scheme ? $acct : mb_substr($acct, 5);
1623 function hasBlocked(Profile $other)
1625 $block = Profile_block::exists($this, $other);
1626 return !empty($block);
1629 public function getAtomFeed()
1633 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1634 if ($this->isLocal()) {
1635 $feed = common_local_url('ApiTimelineUser', array('id' => $this->getID(),
1636 'format' => 'atom'));
1638 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1644 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1646 // TRANS: Exception thrown when trying view "repeated to me".
1647 throw new Exception(_('Not implemented since inbox change.'));
1651 * Get a Profile object by URI. Will call external plugins for help
1652 * using the event StartGetProfileFromURI.
1654 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1656 static function fromUri($uri)
1660 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1661 // Get a local user when plugin lookup (like OStatus) fails
1662 $user = User::getKV('uri', $uri);
1663 if ($user instanceof User) {
1664 $profile = $user->getProfile();
1666 $group = User_group::getKV('uri', $uri);
1667 if ($group instanceof User_group) {
1668 $profile = $group->getProfile();
1671 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1674 if (!$profile instanceof Profile) {
1675 throw new UnknownUriException($uri);
1681 function canRead(Notice $notice)
1683 if ($notice->scope & Notice::SITE_SCOPE) {
1684 $user = $this->getUser();
1690 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1691 $replies = $notice->getReplies();
1693 if (!in_array($this->id, $replies)) {
1694 $groups = $notice->getGroups();
1698 foreach ($groups as $group) {
1699 if ($this->isMember($group)) {
1711 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1712 $author = $notice->getProfile();
1713 if (!Subscription::exists($this, $author)) {
1721 static function current()
1723 $user = common_current_user();
1727 $profile = $user->getProfile();
1732 static function ensureCurrent()
1734 $profile = self::current();
1735 if (!$profile instanceof Profile) {
1736 throw new AuthorizationException('A currently scoped profile is required.');
1742 * Magic function called at serialize() time.
1744 * We use this to drop a couple process-specific references
1745 * from DB_DataObject which can cause trouble in future
1748 * @return array of variable names to include in serialization.
1753 $vars = parent::__sleep();
1754 $skip = array('_user', '_group');
1755 return array_diff($vars, $skip);
1758 public function getProfile()
1764 * Test whether the given profile is the same as the current class,
1765 * for testing identities.
1767 * @param Profile $other The other profile, usually from Action's $this->scoped
1771 public function sameAs(Profile $other=null)
1773 if (is_null($other)) {
1774 // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
1777 return $this->getID() === $other->getID();
1781 * This will perform shortenLinks with the connected User object.
1783 * Won't work on remote profiles or groups, so expect a
1784 * NoSuchUserException if you don't know it's a local User.
1786 * @param string $text String to shorten
1787 * @param boolean $always Disrespect minimum length etc.
1789 * @return string link-shortened $text
1791 public function shortenLinks($text, $always=false)
1793 return $this->getUser()->shortenLinks($text, $always);
1796 public function isPrivateStream()
1798 // We only know of public remote users as of yet...
1799 if (!$this->isLocal()) {
1802 return $this->getUser()->private_stream ? true : false;
1805 public function delPref($namespace, $topic) {
1806 return Profile_prefs::setData($this, $namespace, $topic, null);
1809 public function getPref($namespace, $topic, $default=null) {
1810 // If you want an exception to be thrown, call Profile_prefs::getData directly
1812 return Profile_prefs::getData($this, $namespace, $topic, $default);
1813 } catch (NoResultException $e) {
1818 // The same as getPref but will fall back to common_config value for the same namespace/topic
1819 public function getConfigPref($namespace, $topic)
1821 return Profile_prefs::getConfigData($this, $namespace, $topic);
1824 public function setPref($namespace, $topic, $data) {
1825 return Profile_prefs::setData($this, $namespace, $topic, $data);
1828 public function getConnectedApps($offset=0, $limit=null)
1830 return $this->getUser()->getConnectedApps($offset, $limit);