3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
23 * Table Definition for profile
25 class Profile extends Managed_DataObject
28 /* the code below is auto generated do not remove the above tag */
30 public $__table = 'profile'; // table name
31 public $id; // int(4) primary_key not_null
32 public $nickname; // varchar(64) multiple_key not_null
33 public $fullname; // varchar(191) multiple_key not 255 because utf8mb4 takes more space
34 public $profileurl; // varchar(191) not 255 because utf8mb4 takes more space
35 public $homepage; // varchar(191) multiple_key not 255 because utf8mb4 takes more space
36 public $bio; // text() multiple_key
37 public $location; // varchar(191) multiple_key not 255 because utf8mb4 takes more space
38 public $lat; // decimal(10,7)
39 public $lon; // decimal(10,7)
40 public $location_id; // int(4)
41 public $location_ns; // int(4)
42 public $created; // datetime() not_null
43 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
45 public static function schemaDef()
48 'description' => 'local and remote users have profiles',
50 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
51 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8mb4_general_ci'),
52 'fullname' => array('type' => 'varchar', 'length' => 191, 'description' => 'display name', 'collate' => 'utf8mb4_general_ci'),
53 'profileurl' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL, cached so we dont regenerate'),
54 'homepage' => array('type' => 'varchar', 'length' => 191, 'description' => 'identifying URL', 'collate' => 'utf8mb4_general_ci'),
55 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8mb4_general_ci'),
56 'location' => array('type' => 'varchar', 'length' => 191, 'description' => 'physical location', 'collate' => 'utf8mb4_general_ci'),
57 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
58 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
59 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
60 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
62 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
63 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
65 'primary key' => array('id'),
67 'profile_nickname_idx' => array('nickname'),
71 // Add a fulltext index
73 if (common_config('search', 'type') == 'fulltext') {
74 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
80 /* the code above is auto generated do not remove the tag below */
83 public static function getByEmail($email)
85 // in the future, profiles should have emails stored...
86 $user = User::getKV('email', $email);
87 if (!($user instanceof User)) {
88 throw new NoSuchUserException(array('email'=>$email));
90 return $user->getProfile();
93 protected $_user = array();
95 public function getUser()
97 if (!isset($this->_user[$this->id])) {
98 $user = User::getKV('id', $this->id);
99 if (!$user instanceof User) {
100 throw new NoSuchUserException(array('id'=>$this->id));
102 $this->_user[$this->id] = $user;
104 return $this->_user[$this->id];
107 protected $_group = array();
109 public function getGroup()
111 if (!isset($this->_group[$this->id])) {
112 $group = User_group::getKV('profile_id', $this->id);
113 if (!$group instanceof User_group) {
114 throw new NoSuchGroupException(array('profile_id'=>$this->id));
116 $this->_group[$this->id] = $group;
118 return $this->_group[$this->id];
121 public function isGroup()
126 } catch (NoSuchGroupException $e) {
131 public function isLocal()
135 } catch (NoSuchUserException $e) {
141 // 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->url = Avatar::url($filename);
185 $avatar->created = common_sql_now();
187 // XXX: start a transaction here
188 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
189 // If we can't delete the old avatars, let's abort right here.
190 @unlink(Avatar::path($filename));
198 * Gets either the full name (if filled) or the nickname.
202 function getBestName()
204 return ($this->fullname) ? $this->fullname : $this->nickname;
208 * Takes the currently scoped profile into account to give a name
209 * to list in notice streams. Preferences may differ between profiles.
211 function getStreamName()
213 $user = common_current_user();
214 if ($user instanceof User && $user->streamNicknames()) {
215 return $this->nickname;
218 return $this->getBestName();
222 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
223 * if no fullname is provided.
227 function getFancyName()
229 if ($this->fullname) {
230 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
231 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
233 return $this->nickname;
238 * Get the most recent notice posted by this user, if any.
240 * @return mixed Notice or null
242 function getCurrentNotice()
244 $notice = $this->getNotices(0, 1);
246 if ($notice->fetch()) {
247 if ($notice instanceof ArrayWrapper) {
248 // hack for things trying to work with single notices
249 return $notice->_items[0];
257 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
259 return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
262 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
264 $stream = new TaggedProfileNoticeStream($this, $tag);
266 return $stream->getNotices($offset, $limit, $since_id, $max_id);
269 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
271 $stream = new ProfileNoticeStream($this, $scoped);
273 return $stream->getNotices($offset, $limit, $since_id, $max_id);
276 function isMember(User_group $group)
278 $groups = $this->getGroups(0, null);
279 while ($groups instanceof User_group && $groups->fetch()) {
280 if ($groups->id == $group->id) {
287 function isAdmin(User_group $group)
289 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
290 'group_id' => $group->id));
291 return (!empty($gm) && $gm->is_admin);
294 function isPendingMember($group)
296 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
297 'group_id' => $group->id));
298 return !empty($request);
301 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
305 $keypart = sprintf('profile:groups:%d', $this->id);
307 $idstring = self::cacheGet($keypart);
309 if ($idstring !== false) {
310 $ids = explode(',', $idstring);
312 $gm = new Group_member();
314 $gm->profile_id = $this->id;
317 while ($gm->fetch()) {
318 $ids[] = $gm->group_id;
322 self::cacheSet($keypart, implode(',', $ids));
325 if (!is_null($offset) && !is_null($limit)) {
326 $ids = array_slice($ids, $offset, $limit);
330 return User_group::multiGet('id', $ids);
331 } catch (NoResultException $e) {
332 return null; // throw exception when we handle it everywhere
336 function getGroupCount() {
337 $groups = $this->getGroups(0, null);
338 return $groups instanceof User_group
343 function isTagged($peopletag)
345 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
346 'tagged' => $this->id,
347 'tag' => $peopletag->tag));
351 function canTag($tagged)
353 if (empty($tagged)) {
357 if ($tagged->id == $this->id) {
361 $all = common_config('peopletag', 'allow_tagging', 'all');
362 $local = common_config('peopletag', 'allow_tagging', 'local');
363 $remote = common_config('peopletag', 'allow_tagging', 'remote');
364 $subs = common_config('peopletag', 'allow_tagging', 'subs');
370 $tagged_user = $tagged->getUser();
371 if (!empty($tagged_user)) {
376 return (Subscription::exists($this, $tagged) ||
377 Subscription::exists($tagged, $this));
378 } else if ($remote) {
384 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
388 $keypart = sprintf('profile:lists:%d', $this->id);
390 $idstr = self::cacheGet($keypart);
392 if ($idstr !== false) {
393 $ids = explode(',', $idstr);
395 $list = new Profile_list();
397 $list->selectAdd('id');
398 $list->tagger = $this->id;
399 $list->selectAdd('id as "cursor"');
402 $list->whereAdd('id > '.$since_id);
406 $list->whereAdd('id <= '.$max_id);
409 if($offset>=0 && !is_null($limit)) {
410 $list->limit($offset, $limit);
413 $list->orderBy('id DESC');
416 while ($list->fetch()) {
421 self::cacheSet($keypart, implode(',', $ids));
424 $showPrivate = (($auth_user instanceof User ||
425 $auth_user instanceof Profile) &&
426 $auth_user->id === $this->id);
430 foreach ($ids as $id) {
431 $list = Profile_list::getKV('id', $id);
433 ($showPrivate || !$list->private)) {
435 if (!isset($list->cursor)) {
436 $list->cursor = $list->id;
443 return new ArrayWrapper($lists);
447 * Get tags that other people put on this profile, in reverse-chron order
449 * @param (Profile|User) $auth_user Authorized user (used for privacy)
450 * @param int $offset Offset from latest
451 * @param int $limit Max number to get
452 * @param datetime $since_id max date
453 * @param datetime $max_id min date
455 * @return Profile_list resulting lists
458 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
460 $list = new Profile_list();
462 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
463 'from profile_tag join profile_list '.
464 'on (profile_tag.tagger = profile_list.tagger ' .
465 ' and profile_tag.tag = profile_list.tag) ' .
466 'where profile_tag.tagged = %d ',
470 if ($auth_user instanceof User || $auth_user instanceof Profile) {
471 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
472 'OR ( profile_list.tagger = %d AND ' .
473 'profile_list.private = true ) )',
476 $qry .= 'AND profile_list.private = 0 ';
480 $qry .= sprintf('AND (cursor > %d) ', $since_id);
484 $qry .= sprintf('AND (cursor < %d) ', $max_id);
487 $qry .= 'ORDER BY profile_tag.modified DESC ';
489 if ($offset >= 0 && !is_null($limit)) {
490 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
497 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
499 $tags = new Profile_list();
500 $tags->private = true;
501 $tags->tagger = $this->id;
504 $tags->whereAdd('id > '.$since_id);
508 $tags->whereAdd('id <= '.$max_id);
511 if($offset>=0 && !is_null($limit)) {
512 $tags->limit($offset, $limit);
515 $tags->orderBy('id DESC');
521 function hasLocalTags()
523 $tags = new Profile_tag();
525 $tags->joinAdd(array('tagger', 'user:id'));
526 $tags->whereAdd('tagged = '.$this->id);
527 $tags->whereAdd('tagger != '.$this->id);
532 return ($tags->N == 0) ? false : true;
535 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
537 $lists = new Profile_list();
538 $subs = new Profile_tag_subscription();
540 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
542 #@fixme: postgres (round(date_part('epoch', my_date)))
543 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
545 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
548 $lists->whereAdd('cursor > '.$since_id);
552 $lists->whereAdd('cursor <= '.$max_id);
555 if($offset>=0 && !is_null($limit)) {
556 $lists->limit($offset, $limit);
559 $lists->orderBy('"cursor" DESC');
566 * Request to join the given group.
567 * May throw exceptions on failure.
569 * @param User_group $group
570 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
572 function joinGroup(User_group $group)
575 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
576 $join = Group_join_queue::saveNew($this, $group);
578 if (Event::handle('StartJoinGroup', array($group, $this))) {
579 $join = Group_member::join($group->id, $this->id);
580 self::blow('profile:groups:%d', $this->id);
581 self::blow('group:member_ids:%d', $group->id);
582 self::blow('group:member_count:%d', $group->id);
583 Event::handle('EndJoinGroup', array($group, $this));
587 // Send any applicable notifications...
594 * Leave a group that this profile is a member of.
596 * @param User_group $group
598 function leaveGroup(User_group $group)
600 if (Event::handle('StartLeaveGroup', array($group, $this))) {
601 Group_member::leave($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('EndLeaveGroup', array($group, $this));
609 function avatarUrl($size=AVATAR_PROFILE_SIZE)
611 return Avatar::urlByProfile($this, $size);
614 function getSubscribed($offset=0, $limit=null)
616 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
618 $profiles = Profile::multiGet('id', $subs);
619 } catch (NoResultException $e) {
625 function getSubscribers($offset=0, $limit=null)
627 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
629 $profiles = Profile::multiGet('id', $subs);
630 } catch (NoResultException $e) {
636 function getTaggedSubscribers($tag, $offset=0, $limit=null)
639 'SELECT profile.* ' .
640 'FROM profile JOIN subscription ' .
641 'ON profile.id = subscription.subscriber ' .
642 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
643 'AND profile_tag.tagger = subscription.subscribed) ' .
644 'WHERE subscription.subscribed = %d ' .
645 "AND profile_tag.tag = '%s' " .
646 'AND subscription.subscribed != subscription.subscriber ' .
647 'ORDER BY subscription.created DESC ';
650 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
653 $profile = new Profile();
655 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
660 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
663 'SELECT profile.* ' .
664 'FROM profile JOIN subscription ' .
665 'ON profile.id = subscription.subscribed ' .
666 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
667 'AND profile_tag.tagger = subscription.subscriber) ' .
668 'WHERE subscription.subscriber = %d ' .
669 "AND profile_tag.tag = '%s' " .
670 'AND subscription.subscribed != subscription.subscriber ' .
671 'ORDER BY subscription.created DESC ';
673 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
675 $profile = new Profile();
677 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
683 * Get pending subscribers, who have not yet been approved.
689 function getRequests($offset=0, $limit=null)
692 'SELECT profile.* ' .
693 'FROM profile JOIN subscription_queue '.
694 'ON profile.id = subscription_queue.subscriber ' .
695 'WHERE subscription_queue.subscribed = %d ' .
696 'ORDER BY subscription_queue.created DESC ';
698 if ($limit != null) {
699 if (common_config('db','type') == 'pgsql') {
700 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
702 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
706 $members = new Profile();
708 $members->query(sprintf($qry, $this->id));
712 function subscriptionCount()
714 $c = Cache::instance();
717 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
718 if (is_integer($cnt)) {
723 $sub = new Subscription();
724 $sub->subscriber = $this->id;
726 $cnt = (int) $sub->count('distinct subscribed');
728 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
731 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
737 function subscriberCount()
739 $c = Cache::instance();
741 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
742 if (is_integer($cnt)) {
747 $sub = new Subscription();
748 $sub->subscribed = $this->id;
749 $sub->whereAdd('subscriber != subscribed');
750 $cnt = (int) $sub->count('distinct subscriber');
753 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
760 * Is this profile subscribed to another profile?
762 * @param Profile $other
765 function isSubscribed(Profile $other)
767 return Subscription::exists($this, $other);
771 * Check if a pending subscription request is outstanding for this...
773 * @param Profile $other
776 function hasPendingSubscription(Profile $other)
778 return Subscription_queue::exists($this, $other);
782 * Are these two profiles subscribed to each other?
784 * @param Profile $other
787 function mutuallySubscribed(Profile $other)
789 return $this->isSubscribed($other) &&
790 $other->isSubscribed($this);
793 function noticeCount()
795 $c = Cache::instance();
798 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
799 if (is_integer($cnt)) {
804 $notices = new Notice();
805 $notices->profile_id = $this->id;
806 $cnt = (int) $notices->count('distinct id');
809 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
815 function blowSubscriberCount()
817 $c = Cache::instance();
819 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
823 function blowSubscriptionCount()
825 $c = Cache::instance();
827 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
831 function blowNoticeCount()
833 $c = Cache::instance();
835 $c->delete(Cache::key('profile:notice_count:'.$this->id));
839 static function maxBio()
841 $biolimit = common_config('profile', 'biolimit');
842 // null => use global limit (distinct from 0!)
843 if (is_null($biolimit)) {
844 $biolimit = common_config('site', 'textlimit');
849 static function bioTooLong($bio)
851 $biolimit = self::maxBio();
852 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
855 function update($dataObject=false)
857 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
859 $local = $this->getUser();
860 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
861 $origuser = clone($local);
862 $local->nickname = $this->nickname;
863 // updateWithKeys throws exception on failure.
864 $local->updateWithKeys($origuser);
866 // Clear the site owner, in case nickname changed
867 if ($local->hasRole(Profile_role::OWNER)) {
868 User::blow('user:site_owner');
870 } catch (NoSuchUserException $e) {
875 return parent::update($dataObject);
878 function delete($useWhere=false)
880 // just in case it hadn't been done before... (usually set before adding deluser to queue handling!)
881 if (!$this->hasRole(Profile_role::DELETED)) {
882 $this->grantRole(Profile_role::DELETED);
885 $this->_deleteNotices();
886 $this->_deleteSubscriptions();
887 $this->_deleteTags();
888 $this->_deleteBlocks();
889 $this->_deleteAttentions();
890 Avatar::deleteFromProfile($this, true);
892 // Warning: delete() will run on the batch objects,
893 // not on individual objects.
894 $related = array('Reply',
897 Event::handle('ProfileDeleteRelated', array($this, &$related));
899 foreach ($related as $cls) {
901 $inst->profile_id = $this->id;
905 $localuser = User::getKV('id', $this->id);
906 if ($localuser instanceof User) {
907 $localuser->delete();
910 return parent::delete($useWhere);
913 function _deleteNotices()
915 $notice = new Notice();
916 $notice->profile_id = $this->id;
918 if ($notice->find()) {
919 while ($notice->fetch()) {
920 $other = clone($notice);
926 function _deleteSubscriptions()
928 $sub = new Subscription();
929 $sub->subscriber = $this->id;
933 while ($sub->fetch()) {
934 $other = Profile::getKV('id', $sub->subscribed);
938 if ($other->id == $this->id) {
941 Subscription::cancel($this, $other);
944 $subd = new Subscription();
945 $subd->subscribed = $this->id;
948 while ($subd->fetch()) {
949 $other = Profile::getKV('id', $subd->subscriber);
953 if ($other->id == $this->id) {
956 Subscription::cancel($other, $this);
959 $self = new Subscription();
961 $self->subscriber = $this->id;
962 $self->subscribed = $this->id;
967 function _deleteTags()
969 $tag = new Profile_tag();
970 $tag->tagged = $this->id;
974 function _deleteBlocks()
976 $block = new Profile_block();
977 $block->blocked = $this->id;
980 $block = new Group_block();
981 $block->blocked = $this->id;
985 function _deleteAttentions()
987 $att = new Attention();
988 $att->profile_id = $this->getID();
991 while ($att->fetch()) {
992 // Can't do delete() on the object directly since it won't remove all of it
993 $other = clone($att);
999 // XXX: identical to Notice::getLocation.
1001 public function getLocation()
1005 if (!empty($this->location_id) && !empty($this->location_ns)) {
1006 $location = Location::fromId($this->location_id, $this->location_ns);
1009 if (is_null($location)) { // no ID, or Location::fromId() failed
1010 if (!empty($this->lat) && !empty($this->lon)) {
1011 $location = Location::fromLatLon($this->lat, $this->lon);
1015 if (is_null($location)) { // still haven't found it!
1016 if (!empty($this->location)) {
1017 $location = Location::fromName($this->location);
1024 public function shareLocation()
1026 $cfg = common_config('location', 'share');
1028 if ($cfg == 'always') {
1030 } else if ($cfg == 'never') {
1033 $share = common_config('location', 'sharedefault');
1035 // Check if user has a personal setting for this
1036 $prefs = User_location_prefs::getKV('user_id', $this->id);
1038 if (!empty($prefs)) {
1039 $share = $prefs->share_location;
1047 function hasRole($name)
1050 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1051 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1053 $has_role = !empty($role);
1054 Event::handle('EndHasRole', array($this, $name, $has_role));
1059 function grantRole($name)
1061 if (Event::handle('StartGrantRole', array($this, $name))) {
1063 $role = new Profile_role();
1065 $role->profile_id = $this->id;
1066 $role->role = $name;
1067 $role->created = common_sql_now();
1069 $result = $role->insert();
1072 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1075 if ($name == 'owner') {
1076 User::blow('user:site_owner');
1079 Event::handle('EndGrantRole', array($this, $name));
1085 function revokeRole($name)
1087 if (Event::handle('StartRevokeRole', array($this, $name))) {
1089 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1093 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1094 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1095 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1098 $result = $role->delete();
1101 common_log_db_error($role, 'DELETE', __FILE__);
1102 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1103 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1104 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1107 if ($name == 'owner') {
1108 User::blow('user:site_owner');
1111 Event::handle('EndRevokeRole', array($this, $name));
1117 function isSandboxed()
1119 return $this->hasRole(Profile_role::SANDBOXED);
1122 function isSilenced()
1124 return $this->hasRole(Profile_role::SILENCED);
1129 $this->grantRole(Profile_role::SANDBOXED);
1132 function unsandbox()
1134 $this->revokeRole(Profile_role::SANDBOXED);
1139 $this->grantRole(Profile_role::SILENCED);
1140 if (common_config('notice', 'hidespam')) {
1141 $this->flushVisibility();
1145 function unsilence()
1147 $this->revokeRole(Profile_role::SILENCED);
1148 if (common_config('notice', 'hidespam')) {
1149 $this->flushVisibility();
1153 function flushVisibility()
1156 $stream = new ProfileNoticeStream($this, $this);
1157 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1158 foreach ($ids as $id) {
1159 self::blow('notice:in-scope-for:%d:null', $id);
1164 * Does this user have the right to do X?
1166 * With our role-based authorization, this is merely a lookup for whether the user
1167 * has a particular role. The implementation currently uses a switch statement
1168 * to determine if the user has the pre-defined role to exercise the right. Future
1169 * implementations may allow per-site roles, and different mappings of roles to rights.
1171 * @param $right string Name of the right, usually a constant in class Right
1172 * @return boolean whether the user has the right in question
1174 public function hasRight($right)
1178 if ($this->hasRole(Profile_role::DELETED)) {
1182 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1185 case Right::DELETEOTHERSNOTICE:
1186 case Right::MAKEGROUPADMIN:
1187 case Right::SANDBOXUSER:
1188 case Right::SILENCEUSER:
1189 case Right::DELETEUSER:
1190 case Right::DELETEGROUP:
1191 case Right::TRAINSPAM:
1192 case Right::REVIEWSPAM:
1193 $result = $this->hasRole(Profile_role::MODERATOR);
1195 case Right::CONFIGURESITE:
1196 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1198 case Right::GRANTROLE:
1199 case Right::REVOKEROLE:
1200 $result = $this->hasRole(Profile_role::OWNER);
1202 case Right::NEWNOTICE:
1203 case Right::NEWMESSAGE:
1204 case Right::SUBSCRIBE:
1205 case Right::CREATEGROUP:
1206 $result = !$this->isSilenced();
1208 case Right::PUBLICNOTICE:
1209 case Right::EMAILONREPLY:
1210 case Right::EMAILONSUBSCRIBE:
1211 case Right::EMAILONFAVE:
1212 $result = !$this->isSandboxed();
1214 case Right::WEBLOGIN:
1215 $result = !$this->isSilenced();
1218 $result = !$this->isSilenced();
1220 case Right::BACKUPACCOUNT:
1221 $result = common_config('profile', 'backup');
1223 case Right::RESTOREACCOUNT:
1224 $result = common_config('profile', 'restore');
1226 case Right::DELETEACCOUNT:
1227 $result = common_config('profile', 'delete');
1229 case Right::MOVEACCOUNT:
1230 $result = common_config('profile', 'move');
1240 // FIXME: Can't put Notice typing here due to ArrayWrapper
1241 public function hasRepeated($notice)
1243 // XXX: not really a pkey, but should work
1245 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1246 'repeat_of' => $notice->id));
1248 return !empty($notice);
1252 * Returns an XML string fragment with limited profile information
1253 * as an Atom <author> element.
1255 * Assumes that Atom has been previously set up as the base namespace.
1257 * @param Profile $cur the current authenticated user
1261 function asAtomAuthor($cur = null)
1263 $xs = new XMLStringer(true);
1265 $xs->elementStart('author');
1266 $xs->element('name', null, $this->nickname);
1267 $xs->element('uri', null, $this->getUri());
1270 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1271 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1272 $xs->element('statusnet:profile_info', $attrs, null);
1274 $xs->elementEnd('author');
1276 return $xs->getString();
1280 * Extra profile info for atom entries
1282 * Clients use some extra profile info in the atom stream.
1283 * This gives it to them.
1285 * @param Profile $scoped The currently logged in/scoped profile
1287 * @return array representation of <statusnet:profile_info> element or null
1290 function profileInfo(Profile $scoped=null)
1292 $profileInfoAttr = array('local_id' => $this->id);
1294 if ($scoped instanceof Profile) {
1295 // Whether the current user is a subscribed to this profile
1296 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1297 // Whether the current user is has blocked this profile
1298 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1301 return array('statusnet:profile_info', $profileInfoAttr, null);
1305 * Returns an XML string fragment with profile information as an
1306 * Activity Streams <activity:actor> element.
1308 * Assumes that 'activity' namespace has been previously defined.
1312 function asActivityActor()
1314 return $this->asActivityNoun('actor');
1318 * Returns an XML string fragment with profile information as an
1319 * Activity Streams noun object with the given element type.
1321 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1322 * previously defined.
1324 * @param string $element one of 'actor', 'subject', 'object', 'target'
1328 function asActivityNoun($element)
1330 $noun = $this->asActivityObject();
1331 return $noun->asString('activity:' . $element);
1334 public function asActivityObject()
1336 $object = new ActivityObject();
1338 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1339 $object->type = $this->getObjectType();
1340 $object->id = $this->getUri();
1341 $object->title = $this->getBestName();
1342 $object->link = $this->getUrl();
1343 $object->summary = $this->getDescription();
1346 $avatar = Avatar::getUploaded($this);
1347 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1348 } catch (NoAvatarException $e) {
1349 // Could not find an original avatar to link
1353 AVATAR_PROFILE_SIZE,
1358 foreach ($sizes as $size) {
1361 $avatar = Avatar::byProfile($this, $size);
1362 $alink = AvatarLink::fromAvatar($avatar);
1363 } catch (NoAvatarException $e) {
1364 $alink = new AvatarLink();
1365 $alink->type = 'image/png';
1366 $alink->height = $size;
1367 $alink->width = $size;
1368 $alink->url = Avatar::defaultImage($size);
1371 $object->avatarLinks[] = $alink;
1374 if (isset($this->lat) && isset($this->lon)) {
1375 $object->geopoint = (float)$this->lat
1376 . ' ' . (float)$this->lon;
1379 $object->poco = PoCo::fromProfile($this);
1381 if ($this->isLocal()) {
1382 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1385 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1392 * Returns the profile's canonical url, not necessarily a uri/unique id
1394 * @return string $profileurl
1396 public function getUrl()
1398 if (empty($this->profileurl) ||
1399 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1400 throw new InvalidUrlException($this->profileurl);
1402 return $this->profileurl;
1405 public function getNickname()
1407 return $this->nickname;
1410 public function getFullname()
1412 return $this->fullname;
1415 public function getHomepage()
1417 return $this->homepage;
1420 public function getDescription()
1426 * Returns the best URI for a profile. Plugins may override.
1428 * @return string $uri
1430 public function getUri()
1434 // give plugins a chance to set the URI
1435 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1437 // check for a local user first
1438 $user = User::getKV('id', $this->id);
1439 if ($user instanceof User) {
1440 $uri = $user->getUri();
1443 Event::handle('EndGetProfileUri', array($this, &$uri));
1450 * Returns an assumed acct: URI for a profile. Plugins are required.
1452 * @return string $uri
1454 public function getAcctUri()
1458 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1459 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1462 if ($acct === null) {
1463 throw new ProfileNoAcctUriException($this);
1469 function hasBlocked($other)
1471 $block = Profile_block::exists($this, $other);
1472 return !empty($block);
1475 function getAtomFeed()
1479 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1480 $user = User::getKV('id', $this->id);
1481 if (!empty($user)) {
1482 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1483 'format' => 'atom'));
1485 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1491 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1493 // TRANS: Exception thrown when trying view "repeated to me".
1494 throw new Exception(_('Not implemented since inbox change.'));
1498 * Get a Profile object by URI. Will call external plugins for help
1499 * using the event StartGetProfileFromURI.
1501 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1503 static function fromUri($uri)
1507 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1508 // Get a local user when plugin lookup (like OStatus) fails
1509 $user = User::getKV('uri', $uri);
1510 if ($user instanceof User) {
1511 $profile = $user->getProfile();
1513 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1516 if (!$profile instanceof Profile) {
1517 throw new UnknownUriException($uri);
1523 function canRead(Notice $notice)
1525 if ($notice->scope & Notice::SITE_SCOPE) {
1526 $user = $this->getUser();
1532 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1533 $replies = $notice->getReplies();
1535 if (!in_array($this->id, $replies)) {
1536 $groups = $notice->getGroups();
1540 foreach ($groups as $group) {
1541 if ($this->isMember($group)) {
1553 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1554 $author = $notice->getProfile();
1555 if (!Subscription::exists($this, $author)) {
1563 static function current()
1565 $user = common_current_user();
1569 $profile = $user->getProfile();
1575 * Magic function called at serialize() time.
1577 * We use this to drop a couple process-specific references
1578 * from DB_DataObject which can cause trouble in future
1581 * @return array of variable names to include in serialization.
1586 $vars = parent::__sleep();
1587 $skip = array('_user', '_group');
1588 return array_diff($vars, $skip);
1591 public function getProfile()
1597 * Test whether the given profile is the same as the current class,
1598 * for testing identities.
1600 * @param Profile $other The other profile, usually from Action's $this->scoped
1604 public function sameAs(Profile $other=null)
1606 if (is_null($other)) {
1607 // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
1610 return $this->getID() === $other->getID();
1614 * This will perform shortenLinks with the connected User object.
1616 * Won't work on remote profiles or groups, so expect a
1617 * NoSuchUserException if you don't know it's a local User.
1619 * @param string $text String to shorten
1620 * @param boolean $always Disrespect minimum length etc.
1622 * @return string link-shortened $text
1624 public function shortenLinks($text, $always=false)
1626 return $this->getUser()->shortenLinks($text, $always);
1629 public function isPrivateStream()
1631 // We only know of public remote users as of yet...
1632 if (!$this->isLocal()) {
1635 return $this->getUser()->private_stream ? true : false;
1638 public function delPref($namespace, $topic) {
1639 return Profile_prefs::setData($this, $namespace, $topic, null);
1642 public function getPref($namespace, $topic, $default=null) {
1643 // If you want an exception to be thrown, call Profile_prefs::getData directly
1645 return Profile_prefs::getData($this, $namespace, $topic, $default);
1646 } catch (NoResultException $e) {
1651 // The same as getPref but will fall back to common_config value for the same namespace/topic
1652 public function getConfigPref($namespace, $topic)
1654 return Profile_prefs::getConfigData($this, $namespace, $topic);
1657 public function setPref($namespace, $topic, $data) {
1658 return Profile_prefs::setData($this, $namespace, $topic, $data);
1661 public function getConnectedApps($offset=0, $limit=null)
1663 return $this->getUser()->getConnectedApps($offset, $limit);