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 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
27 class Profile extends Managed_DataObject
30 /* the code below is auto generated do not remove the above tag */
32 public $__table = 'profile'; // table name
33 public $id; // int(4) primary_key not_null
34 public $nickname; // varchar(64) multiple_key not_null
35 public $fullname; // varchar(255) multiple_key
36 public $profileurl; // varchar(255)
37 public $homepage; // varchar(255) multiple_key
38 public $bio; // text() multiple_key
39 public $location; // varchar(255) multiple_key
40 public $lat; // decimal(10,7)
41 public $lon; // decimal(10,7)
42 public $location_id; // int(4)
43 public $location_ns; // int(4)
44 public $created; // datetime() not_null
45 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
47 public static function schemaDef()
50 'description' => 'local and remote users have profiles',
52 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
53 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
54 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
55 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
56 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
57 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
58 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
59 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
60 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
61 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
62 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
64 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
65 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
67 'primary key' => array('id'),
69 'profile_nickname_idx' => array('nickname'),
73 // Add a fulltext index
75 if (common_config('search', 'type') == 'fulltext') {
76 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
82 /* the code above is auto generated do not remove the tag below */
85 public static function getByEmail($email)
87 // in the future, profiles should have emails stored...
88 $user = User::getKV('email', $email);
89 if (!($user instanceof User)) {
90 throw new NoSuchUserException(array('email'=>$email));
92 return $user->getProfile();
95 protected $_user = -1; // Uninitialized value distinct from null
97 public function getUser()
99 if ($this->_user === -1) {
100 $this->_user = User::getKV('id', $this->id);
102 if (!$this->_user instanceof User) {
103 throw new NoSuchUserException(array('id'=>$this->id));
109 protected $_group = -1;
111 public function getGroup()
113 if ($this->_group === -1) {
114 $this->_group = User_group::getKV('profile_id', $this->id);
116 if (!$this->_group instanceof User_group) {
117 throw new NoSuchGroupException(array('profile_id'=>$this->id));
120 return $this->_group;
123 public function isGroup()
128 } catch (NoSuchGroupException $e) {
133 public function isLocal()
137 } catch (NoSuchUserException $e) {
143 protected $_avatars = array();
145 public function getAvatar($width, $height=null)
147 return Avatar::byProfile($this, $width, $height);
150 public function setOriginal($filename)
152 $imagefile = new ImageFile($this->id, Avatar::path($filename));
154 $avatar = new Avatar();
155 $avatar->profile_id = $this->id;
156 $avatar->width = $imagefile->width;
157 $avatar->height = $imagefile->height;
158 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
159 $avatar->filename = $filename;
160 $avatar->original = true;
161 $avatar->url = Avatar::url($filename);
162 $avatar->created = common_sql_now();
164 // XXX: start a transaction here
165 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
166 // If we can't delete the old avatars, let's abort right here.
167 @unlink(Avatar::path($filename));
175 * Gets either the full name (if filled) or the nickname.
179 function getBestName()
181 return ($this->fullname) ? $this->fullname : $this->nickname;
185 * Takes the currently scoped profile into account to give a name
186 * to list in notice streams. Preferences may differ between profiles.
188 function getStreamName()
190 $user = common_current_user();
191 if ($user instanceof User && $user->streamNicknames()) {
192 return $this->nickname;
195 return $this->getBestName();
199 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
200 * if no fullname is provided.
204 function getFancyName()
206 if ($this->fullname) {
207 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
208 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
210 return $this->nickname;
215 * Get the most recent notice posted by this user, if any.
217 * @return mixed Notice or null
219 function getCurrentNotice()
221 $notice = $this->getNotices(0, 1);
223 if ($notice->fetch()) {
224 if ($notice instanceof ArrayWrapper) {
225 // hack for things trying to work with single notices
226 return $notice->_items[0];
234 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
236 $stream = new TaggedProfileNoticeStream($this, $tag);
238 return $stream->getNotices($offset, $limit, $since_id, $max_id);
241 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
243 $stream = new ProfileNoticeStream($this, $scoped);
245 return $stream->getNotices($offset, $limit, $since_id, $max_id);
248 function isMember(User_group $group)
250 $groups = $this->getGroups(0, null);
251 while ($groups instanceof User_group && $groups->fetch()) {
252 if ($groups->id == $group->id) {
259 function isAdmin(User_group $group)
261 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
262 'group_id' => $group->id));
263 return (!empty($gm) && $gm->is_admin);
266 function isPendingMember($group)
268 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
269 'group_id' => $group->id));
270 return !empty($request);
273 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
277 $keypart = sprintf('profile:groups:%d', $this->id);
279 $idstring = self::cacheGet($keypart);
281 if ($idstring !== false) {
282 $ids = explode(',', $idstring);
284 $gm = new Group_member();
286 $gm->profile_id = $this->id;
289 while ($gm->fetch()) {
290 $ids[] = $gm->group_id;
294 self::cacheSet($keypart, implode(',', $ids));
297 if (!is_null($offset) && !is_null($limit)) {
298 $ids = array_slice($ids, $offset, $limit);
302 return User_group::listFind('id', $ids);
303 } catch (NoResultException $e) {
304 return null; // throw exception when we handle it everywhere
308 function getGroupCount() {
309 $groups = $this->getGroups(0, null);
310 return $groups instanceof User_group
315 function isTagged($peopletag)
317 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
318 'tagged' => $this->id,
319 'tag' => $peopletag->tag));
323 function canTag($tagged)
325 if (empty($tagged)) {
329 if ($tagged->id == $this->id) {
333 $all = common_config('peopletag', 'allow_tagging', 'all');
334 $local = common_config('peopletag', 'allow_tagging', 'local');
335 $remote = common_config('peopletag', 'allow_tagging', 'remote');
336 $subs = common_config('peopletag', 'allow_tagging', 'subs');
342 $tagged_user = $tagged->getUser();
343 if (!empty($tagged_user)) {
348 return (Subscription::exists($this, $tagged) ||
349 Subscription::exists($tagged, $this));
350 } else if ($remote) {
356 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
360 $keypart = sprintf('profile:lists:%d', $this->id);
362 $idstr = self::cacheGet($keypart);
364 if ($idstr !== false) {
365 $ids = explode(',', $idstr);
367 $list = new Profile_list();
369 $list->selectAdd('id');
370 $list->tagger = $this->id;
371 $list->selectAdd('id as "cursor"');
374 $list->whereAdd('id > '.$since_id);
378 $list->whereAdd('id <= '.$max_id);
381 if($offset>=0 && !is_null($limit)) {
382 $list->limit($offset, $limit);
385 $list->orderBy('id DESC');
388 while ($list->fetch()) {
393 self::cacheSet($keypart, implode(',', $ids));
396 $showPrivate = (($auth_user instanceof User ||
397 $auth_user instanceof Profile) &&
398 $auth_user->id === $this->id);
402 foreach ($ids as $id) {
403 $list = Profile_list::getKV('id', $id);
405 ($showPrivate || !$list->private)) {
407 if (!isset($list->cursor)) {
408 $list->cursor = $list->id;
415 return new ArrayWrapper($lists);
419 * Get tags that other people put on this profile, in reverse-chron order
421 * @param (Profile|User) $auth_user Authorized user (used for privacy)
422 * @param int $offset Offset from latest
423 * @param int $limit Max number to get
424 * @param datetime $since_id max date
425 * @param datetime $max_id min date
427 * @return Profile_list resulting lists
430 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
432 $list = new Profile_list();
434 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
435 'from profile_tag join profile_list '.
436 'on (profile_tag.tagger = profile_list.tagger ' .
437 ' and profile_tag.tag = profile_list.tag) ' .
438 'where profile_tag.tagged = %d ',
442 if ($auth_user instanceof User || $auth_user instanceof Profile) {
443 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
444 'OR ( profile_list.tagger = %d AND ' .
445 'profile_list.private = true ) )',
448 $qry .= 'AND profile_list.private = 0 ';
452 $qry .= sprintf('AND (cursor > %d) ', $since_id);
456 $qry .= sprintf('AND (cursor < %d) ', $max_id);
459 $qry .= 'ORDER BY profile_tag.modified DESC ';
461 if ($offset >= 0 && !is_null($limit)) {
462 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
469 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
471 $tags = new Profile_list();
472 $tags->private = true;
473 $tags->tagger = $this->id;
476 $tags->whereAdd('id > '.$since_id);
480 $tags->whereAdd('id <= '.$max_id);
483 if($offset>=0 && !is_null($limit)) {
484 $tags->limit($offset, $limit);
487 $tags->orderBy('id DESC');
493 function hasLocalTags()
495 $tags = new Profile_tag();
497 $tags->joinAdd(array('tagger', 'user:id'));
498 $tags->whereAdd('tagged = '.$this->id);
499 $tags->whereAdd('tagger != '.$this->id);
504 return ($tags->N == 0) ? false : true;
507 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
509 $lists = new Profile_list();
510 $subs = new Profile_tag_subscription();
512 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
514 #@fixme: postgres (round(date_part('epoch', my_date)))
515 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
517 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
520 $lists->whereAdd('cursor > '.$since_id);
524 $lists->whereAdd('cursor <= '.$max_id);
527 if($offset>=0 && !is_null($limit)) {
528 $lists->limit($offset, $limit);
531 $lists->orderBy('"cursor" DESC');
538 * Request to join the given group.
539 * May throw exceptions on failure.
541 * @param User_group $group
542 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
544 function joinGroup(User_group $group)
547 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
548 $join = Group_join_queue::saveNew($this, $group);
550 if (Event::handle('StartJoinGroup', array($group, $this))) {
551 $join = Group_member::join($group->id, $this->id);
552 self::blow('profile:groups:%d', $this->id);
553 self::blow('group:member_ids:%d', $group->id);
554 self::blow('group:member_count:%d', $group->id);
555 Event::handle('EndJoinGroup', array($group, $this));
559 // Send any applicable notifications...
566 * Leave a group that this profile is a member of.
568 * @param User_group $group
570 function leaveGroup(User_group $group)
572 if (Event::handle('StartLeaveGroup', array($group, $this))) {
573 Group_member::leave($group->id, $this->id);
574 self::blow('profile:groups:%d', $this->id);
575 self::blow('group:member_ids:%d', $group->id);
576 self::blow('group:member_count:%d', $group->id);
577 Event::handle('EndLeaveGroup', array($group, $this));
581 function avatarUrl($size=AVATAR_PROFILE_SIZE)
583 return Avatar::urlByProfile($this, $size);
586 function getSubscribed($offset=0, $limit=null)
588 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
590 $profiles = Profile::listFind('id', $subs);
591 } catch (NoResultException $e) {
597 function getSubscribers($offset=0, $limit=null)
599 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
601 $profiles = Profile::listFind('id', $subs);
602 } catch (NoResultException $e) {
608 function getTaggedSubscribers($tag, $offset=0, $limit=null)
611 'SELECT profile.* ' .
612 'FROM profile JOIN subscription ' .
613 'ON profile.id = subscription.subscriber ' .
614 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
615 'AND profile_tag.tagger = subscription.subscribed) ' .
616 'WHERE subscription.subscribed = %d ' .
617 "AND profile_tag.tag = '%s' " .
618 'AND subscription.subscribed != subscription.subscriber ' .
619 'ORDER BY subscription.created DESC ';
622 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
625 $profile = new Profile();
627 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
632 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
635 'SELECT profile.* ' .
636 'FROM profile JOIN subscription ' .
637 'ON profile.id = subscription.subscribed ' .
638 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
639 'AND profile_tag.tagger = subscription.subscriber) ' .
640 'WHERE subscription.subscriber = %d ' .
641 "AND profile_tag.tag = '%s' " .
642 'AND subscription.subscribed != subscription.subscriber ' .
643 'ORDER BY subscription.created DESC ';
645 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
647 $profile = new Profile();
649 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
655 * Get pending subscribers, who have not yet been approved.
661 function getRequests($offset=0, $limit=null)
664 'SELECT profile.* ' .
665 'FROM profile JOIN subscription_queue '.
666 'ON profile.id = subscription_queue.subscriber ' .
667 'WHERE subscription_queue.subscribed = %d ' .
668 'ORDER BY subscription_queue.created DESC ';
670 if ($limit != null) {
671 if (common_config('db','type') == 'pgsql') {
672 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
674 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
678 $members = new Profile();
680 $members->query(sprintf($qry, $this->id));
684 function subscriptionCount()
686 $c = Cache::instance();
689 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
690 if (is_integer($cnt)) {
695 $sub = new Subscription();
696 $sub->subscriber = $this->id;
698 $cnt = (int) $sub->count('distinct subscribed');
700 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
703 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
709 function subscriberCount()
711 $c = Cache::instance();
713 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
714 if (is_integer($cnt)) {
719 $sub = new Subscription();
720 $sub->subscribed = $this->id;
721 $sub->whereAdd('subscriber != subscribed');
722 $cnt = (int) $sub->count('distinct subscriber');
725 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
732 * Is this profile subscribed to another profile?
734 * @param Profile $other
737 function isSubscribed(Profile $other)
739 return Subscription::exists($this, $other);
743 * Check if a pending subscription request is outstanding for this...
745 * @param Profile $other
748 function hasPendingSubscription(Profile $other)
750 return Subscription_queue::exists($this, $other);
754 * Are these two profiles subscribed to each other?
756 * @param Profile $other
759 function mutuallySubscribed(Profile $other)
761 return $this->isSubscribed($other) &&
762 $other->isSubscribed($this);
765 function hasFave($notice)
767 $fave = Fave::pkeyGet(array('user_id' => $this->id,
768 'notice_id' => $notice->id));
769 return ((is_null($fave)) ? false : true);
774 $c = Cache::instance();
776 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
777 if (is_integer($cnt)) {
783 $faves->user_id = $this->id;
784 $cnt = (int) $faves->count('notice_id');
787 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
793 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
795 return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
798 function noticeCount()
800 $c = Cache::instance();
803 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
804 if (is_integer($cnt)) {
809 $notices = new Notice();
810 $notices->profile_id = $this->id;
811 $cnt = (int) $notices->count('distinct id');
814 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
820 function blowFavesCache()
822 $cache = Cache::instance();
824 // Faves don't happen chronologically, so we need to blow
826 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
827 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
828 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
829 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
831 $this->blowFaveCount();
834 function blowSubscriberCount()
836 $c = Cache::instance();
838 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
842 function blowSubscriptionCount()
844 $c = Cache::instance();
846 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
850 function blowFaveCount()
852 $c = Cache::instance();
854 $c->delete(Cache::key('profile:fave_count:'.$this->id));
858 function blowNoticeCount()
860 $c = Cache::instance();
862 $c->delete(Cache::key('profile:notice_count:'.$this->id));
866 static function maxBio()
868 $biolimit = common_config('profile', 'biolimit');
869 // null => use global limit (distinct from 0!)
870 if (is_null($biolimit)) {
871 $biolimit = common_config('site', 'textlimit');
876 static function bioTooLong($bio)
878 $biolimit = self::maxBio();
879 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
882 function update($dataObject=false)
884 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
886 $local = $this->getUser();
887 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
888 $origuser = clone($local);
889 $local->nickname = $this->nickname;
890 $result = $local->updateKeys($origuser);
891 if ($result === false) {
892 common_log_db_error($local, 'UPDATE', __FILE__);
893 // TRANS: Server error thrown when user profile settings could not be updated.
894 throw new ServerException(_('Could not update user nickname.'));
897 // Clear the site owner, in case nickname changed
898 if ($local->hasRole(Profile_role::OWNER)) {
899 User::blow('user:site_owner');
901 } catch (NoSuchUserException $e) {
906 return parent::update($dataObject);
909 function delete($useWhere=false)
911 $this->_deleteNotices();
912 $this->_deleteSubscriptions();
913 $this->_deleteMessages();
914 $this->_deleteTags();
915 $this->_deleteBlocks();
916 $this->_deleteAttentions();
917 Avatar::deleteFromProfile($this, true);
919 // Warning: delete() will run on the batch objects,
920 // not on individual objects.
921 $related = array('Reply',
924 Event::handle('ProfileDeleteRelated', array($this, &$related));
926 foreach ($related as $cls) {
928 $inst->profile_id = $this->id;
932 return parent::delete($useWhere);
935 function _deleteNotices()
937 $notice = new Notice();
938 $notice->profile_id = $this->id;
940 if ($notice->find()) {
941 while ($notice->fetch()) {
942 $other = clone($notice);
948 function _deleteSubscriptions()
950 $sub = new Subscription();
951 $sub->subscriber = $this->id;
955 while ($sub->fetch()) {
956 $other = Profile::getKV('id', $sub->subscribed);
960 if ($other->id == $this->id) {
963 Subscription::cancel($this, $other);
966 $subd = new Subscription();
967 $subd->subscribed = $this->id;
970 while ($subd->fetch()) {
971 $other = Profile::getKV('id', $subd->subscriber);
975 if ($other->id == $this->id) {
978 Subscription::cancel($other, $this);
981 $self = new Subscription();
983 $self->subscriber = $this->id;
984 $self->subscribed = $this->id;
989 function _deleteMessages()
991 $msg = new Message();
992 $msg->from_profile = $this->id;
995 $msg = new Message();
996 $msg->to_profile = $this->id;
1000 function _deleteTags()
1002 $tag = new Profile_tag();
1003 $tag->tagged = $this->id;
1007 function _deleteBlocks()
1009 $block = new Profile_block();
1010 $block->blocked = $this->id;
1013 $block = new Group_block();
1014 $block->blocked = $this->id;
1018 function _deleteAttentions()
1020 $att = new Attention();
1021 $att->profile_id = $this->getID();
1024 while ($att->fetch()) {
1025 // Can't do delete() on the object directly since it won't remove all of it
1026 $other = clone($att);
1032 // XXX: identical to Notice::getLocation.
1034 public function getLocation()
1038 if (!empty($this->location_id) && !empty($this->location_ns)) {
1039 $location = Location::fromId($this->location_id, $this->location_ns);
1042 if (is_null($location)) { // no ID, or Location::fromId() failed
1043 if (!empty($this->lat) && !empty($this->lon)) {
1044 $location = Location::fromLatLon($this->lat, $this->lon);
1048 if (is_null($location)) { // still haven't found it!
1049 if (!empty($this->location)) {
1050 $location = Location::fromName($this->location);
1057 public function shareLocation()
1059 $cfg = common_config('location', 'share');
1061 if ($cfg == 'always') {
1063 } else if ($cfg == 'never') {
1066 $share = common_config('location', 'sharedefault');
1068 // Check if user has a personal setting for this
1069 $prefs = User_location_prefs::getKV('user_id', $this->id);
1071 if (!empty($prefs)) {
1072 $share = $prefs->share_location;
1080 function hasRole($name)
1083 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1084 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1086 $has_role = !empty($role);
1087 Event::handle('EndHasRole', array($this, $name, $has_role));
1092 function grantRole($name)
1094 if (Event::handle('StartGrantRole', array($this, $name))) {
1096 $role = new Profile_role();
1098 $role->profile_id = $this->id;
1099 $role->role = $name;
1100 $role->created = common_sql_now();
1102 $result = $role->insert();
1105 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1108 if ($name == 'owner') {
1109 User::blow('user:site_owner');
1112 Event::handle('EndGrantRole', array($this, $name));
1118 function revokeRole($name)
1120 if (Event::handle('StartRevokeRole', array($this, $name))) {
1122 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1126 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1127 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1128 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1131 $result = $role->delete();
1134 common_log_db_error($role, 'DELETE', __FILE__);
1135 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1136 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1137 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1140 if ($name == 'owner') {
1141 User::blow('user:site_owner');
1144 Event::handle('EndRevokeRole', array($this, $name));
1150 function isSandboxed()
1152 return $this->hasRole(Profile_role::SANDBOXED);
1155 function isSilenced()
1157 return $this->hasRole(Profile_role::SILENCED);
1162 $this->grantRole(Profile_role::SANDBOXED);
1165 function unsandbox()
1167 $this->revokeRole(Profile_role::SANDBOXED);
1172 $this->grantRole(Profile_role::SILENCED);
1173 if (common_config('notice', 'hidespam')) {
1174 $this->flushVisibility();
1178 function unsilence()
1180 $this->revokeRole(Profile_role::SILENCED);
1181 if (common_config('notice', 'hidespam')) {
1182 $this->flushVisibility();
1186 function flushVisibility()
1189 $stream = new ProfileNoticeStream($this, $this);
1190 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1191 foreach ($ids as $id) {
1192 self::blow('notice:in-scope-for:%d:null', $id);
1197 * Does this user have the right to do X?
1199 * With our role-based authorization, this is merely a lookup for whether the user
1200 * has a particular role. The implementation currently uses a switch statement
1201 * to determine if the user has the pre-defined role to exercise the right. Future
1202 * implementations may allow per-site roles, and different mappings of roles to rights.
1204 * @param $right string Name of the right, usually a constant in class Right
1205 * @return boolean whether the user has the right in question
1207 public function hasRight($right)
1211 if ($this->hasRole(Profile_role::DELETED)) {
1215 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1218 case Right::DELETEOTHERSNOTICE:
1219 case Right::MAKEGROUPADMIN:
1220 case Right::SANDBOXUSER:
1221 case Right::SILENCEUSER:
1222 case Right::DELETEUSER:
1223 case Right::DELETEGROUP:
1224 case Right::TRAINSPAM:
1225 case Right::REVIEWSPAM:
1226 $result = $this->hasRole(Profile_role::MODERATOR);
1228 case Right::CONFIGURESITE:
1229 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1231 case Right::GRANTROLE:
1232 case Right::REVOKEROLE:
1233 $result = $this->hasRole(Profile_role::OWNER);
1235 case Right::NEWNOTICE:
1236 case Right::NEWMESSAGE:
1237 case Right::SUBSCRIBE:
1238 case Right::CREATEGROUP:
1239 $result = !$this->isSilenced();
1241 case Right::PUBLICNOTICE:
1242 case Right::EMAILONREPLY:
1243 case Right::EMAILONSUBSCRIBE:
1244 case Right::EMAILONFAVE:
1245 $result = !$this->isSandboxed();
1247 case Right::WEBLOGIN:
1248 $result = !$this->isSilenced();
1251 $result = !$this->isSilenced();
1253 case Right::BACKUPACCOUNT:
1254 $result = common_config('profile', 'backup');
1256 case Right::RESTOREACCOUNT:
1257 $result = common_config('profile', 'restore');
1259 case Right::DELETEACCOUNT:
1260 $result = common_config('profile', 'delete');
1262 case Right::MOVEACCOUNT:
1263 $result = common_config('profile', 'move');
1273 // FIXME: Can't put Notice typing here due to ArrayWrapper
1274 public function hasRepeated($notice)
1276 // XXX: not really a pkey, but should work
1278 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1279 'repeat_of' => $notice->id));
1281 return !empty($notice);
1285 * Returns an XML string fragment with limited profile information
1286 * as an Atom <author> element.
1288 * Assumes that Atom has been previously set up as the base namespace.
1290 * @param Profile $cur the current authenticated user
1294 function asAtomAuthor($cur = null)
1296 $xs = new XMLStringer(true);
1298 $xs->elementStart('author');
1299 $xs->element('name', null, $this->nickname);
1300 $xs->element('uri', null, $this->getUri());
1303 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1304 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1305 $xs->element('statusnet:profile_info', $attrs, null);
1307 $xs->elementEnd('author');
1309 return $xs->getString();
1313 * Extra profile info for atom entries
1315 * Clients use some extra profile info in the atom stream.
1316 * This gives it to them.
1318 * @param User $cur Current user
1320 * @return array representation of <statusnet:profile_info> element or null
1323 function profileInfo($cur)
1325 $profileInfoAttr = array('local_id' => $this->id);
1328 // Whether the current user is a subscribed to this profile
1329 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1330 // Whether the current user is has blocked this profile
1331 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1334 return array('statusnet:profile_info', $profileInfoAttr, null);
1338 * Returns an XML string fragment with profile information as an
1339 * Activity Streams <activity:actor> element.
1341 * Assumes that 'activity' namespace has been previously defined.
1345 function asActivityActor()
1347 return $this->asActivityNoun('actor');
1351 * Returns an XML string fragment with profile information as an
1352 * Activity Streams noun object with the given element type.
1354 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1355 * previously defined.
1357 * @param string $element one of 'actor', 'subject', 'object', 'target'
1361 function asActivityNoun($element)
1363 $noun = ActivityObject::fromProfile($this);
1364 return $noun->asString('activity:' . $element);
1368 * Returns the profile's canonical url, not necessarily a uri/unique id
1370 * @return string $profileurl
1372 public function getUrl()
1374 if (empty($this->profileurl) ||
1375 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1376 throw new InvalidUrlException($this->profileurl);
1378 return $this->profileurl;
1381 public function getNickname()
1383 return $this->nickname;
1387 * Returns the best URI for a profile. Plugins may override.
1389 * @return string $uri
1391 public function getUri()
1395 // give plugins a chance to set the URI
1396 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1398 // check for a local user first
1399 $user = User::getKV('id', $this->id);
1400 if ($user instanceof User) {
1401 $uri = $user->getUri();
1404 Event::handle('EndGetProfileUri', array($this, &$uri));
1411 * Returns an assumed acct: URI for a profile. Plugins are required.
1413 * @return string $uri
1415 public function getAcctUri()
1419 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1420 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1423 if ($acct === null) {
1424 throw new ProfileNoAcctUriException($this);
1430 function hasBlocked($other)
1432 $block = Profile_block::exists($this, $other);
1433 return !empty($block);
1436 function getAtomFeed()
1440 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1441 $user = User::getKV('id', $this->id);
1442 if (!empty($user)) {
1443 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1444 'format' => 'atom'));
1446 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1453 * Get a Profile object by URI. Will call external plugins for help
1454 * using the event StartGetProfileFromURI.
1456 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1458 static function fromUri($uri)
1462 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1463 // Get a local user when plugin lookup (like OStatus) fails
1464 $user = User::getKV('uri', $uri);
1465 if ($user instanceof User) {
1466 $profile = $user->getProfile();
1468 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1471 if (!$profile instanceof Profile) {
1472 throw new UnknownUriException($uri);
1478 function canRead(Notice $notice)
1480 if ($notice->scope & Notice::SITE_SCOPE) {
1481 $user = $this->getUser();
1487 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1488 $replies = $notice->getReplies();
1490 if (!in_array($this->id, $replies)) {
1491 $groups = $notice->getGroups();
1495 foreach ($groups as $group) {
1496 if ($this->isMember($group)) {
1508 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1509 $author = $notice->getProfile();
1510 if (!Subscription::exists($this, $author)) {
1518 static function current()
1520 $user = common_current_user();
1524 $profile = $user->getProfile();
1530 * Magic function called at serialize() time.
1532 * We use this to drop a couple process-specific references
1533 * from DB_DataObject which can cause trouble in future
1536 * @return array of variable names to include in serialization.
1541 $vars = parent::__sleep();
1542 $skip = array('_user', '_avatars');
1543 return array_diff($vars, $skip);
1546 public function getProfile()
1552 * This will perform shortenLinks with the connected User object.
1554 * Won't work on remote profiles or groups, so expect a
1555 * NoSuchUserException if you don't know it's a local User.
1557 * @param string $text String to shorten
1558 * @param boolean $always Disrespect minimum length etc.
1560 * @return string link-shortened $text
1562 public function shortenLinks($text, $always=false)
1564 return $this->getUser()->shortenLinks($text, $always);