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));
171 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
172 // We don't do a scaled one if original is our scaled size
173 if (!($avatar->width == $size && $avatar->height == $size)) {
175 Avatar::newSize($this, $size);
176 } catch (Exception $e) {
177 // should we abort the generation and live without smaller avatars?
186 * Gets either the full name (if filled) or the nickname.
190 function getBestName()
192 return ($this->fullname) ? $this->fullname : $this->nickname;
196 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
197 * if no fullname is provided.
201 function getFancyName()
203 if ($this->fullname) {
204 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
205 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
207 return $this->nickname;
212 * Get the most recent notice posted by this user, if any.
214 * @return mixed Notice or null
216 function getCurrentNotice()
218 $notice = $this->getNotices(0, 1);
220 if ($notice->fetch()) {
221 if ($notice instanceof ArrayWrapper) {
222 // hack for things trying to work with single notices
223 return $notice->_items[0];
231 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
233 $stream = new TaggedProfileNoticeStream($this, $tag);
235 return $stream->getNotices($offset, $limit, $since_id, $max_id);
238 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
240 $stream = new ProfileNoticeStream($this, $scoped);
242 return $stream->getNotices($offset, $limit, $since_id, $max_id);
245 function isMember($group)
247 $groups = $this->getGroups(0, null);
248 while ($groups instanceof User_group && $groups->fetch()) {
249 if ($groups->id == $group->id) {
256 function isAdmin($group)
258 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
259 'group_id' => $group->id));
260 return (!empty($gm) && $gm->is_admin);
263 function isPendingMember($group)
265 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
266 'group_id' => $group->id));
267 return !empty($request);
270 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
274 $keypart = sprintf('profile:groups:%d', $this->id);
276 $idstring = self::cacheGet($keypart);
278 if ($idstring !== false) {
279 $ids = explode(',', $idstring);
281 $gm = new Group_member();
283 $gm->profile_id = $this->id;
286 while ($gm->fetch()) {
287 $ids[] = $gm->group_id;
291 self::cacheSet($keypart, implode(',', $ids));
294 if (!is_null($offset) && !is_null($limit)) {
295 $ids = array_slice($ids, $offset, $limit);
299 return User_group::listFind('id', $ids);
300 } catch (NoResultException $e) {
301 return null; // throw exception when we handle it everywhere
305 function getGroupCount() {
306 $groups = $this->getGroups(0, null);
307 return $groups instanceof User_group
312 function isTagged($peopletag)
314 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
315 'tagged' => $this->id,
316 'tag' => $peopletag->tag));
320 function canTag($tagged)
322 if (empty($tagged)) {
326 if ($tagged->id == $this->id) {
330 $all = common_config('peopletag', 'allow_tagging', 'all');
331 $local = common_config('peopletag', 'allow_tagging', 'local');
332 $remote = common_config('peopletag', 'allow_tagging', 'remote');
333 $subs = common_config('peopletag', 'allow_tagging', 'subs');
339 $tagged_user = $tagged->getUser();
340 if (!empty($tagged_user)) {
345 return (Subscription::exists($this, $tagged) ||
346 Subscription::exists($tagged, $this));
347 } else if ($remote) {
353 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
357 $keypart = sprintf('profile:lists:%d', $this->id);
359 $idstr = self::cacheGet($keypart);
361 if ($idstr !== false) {
362 $ids = explode(',', $idstr);
364 $list = new Profile_list();
366 $list->selectAdd('id');
367 $list->tagger = $this->id;
368 $list->selectAdd('id as "cursor"');
371 $list->whereAdd('id > '.$since_id);
375 $list->whereAdd('id <= '.$max_id);
378 if($offset>=0 && !is_null($limit)) {
379 $list->limit($offset, $limit);
382 $list->orderBy('id DESC');
385 while ($list->fetch()) {
390 self::cacheSet($keypart, implode(',', $ids));
393 $showPrivate = (($auth_user instanceof User ||
394 $auth_user instanceof Profile) &&
395 $auth_user->id === $this->id);
399 foreach ($ids as $id) {
400 $list = Profile_list::getKV('id', $id);
402 ($showPrivate || !$list->private)) {
404 if (!isset($list->cursor)) {
405 $list->cursor = $list->id;
412 return new ArrayWrapper($lists);
416 * Get tags that other people put on this profile, in reverse-chron order
418 * @param (Profile|User) $auth_user Authorized user (used for privacy)
419 * @param int $offset Offset from latest
420 * @param int $limit Max number to get
421 * @param datetime $since_id max date
422 * @param datetime $max_id min date
424 * @return Profile_list resulting lists
427 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
429 $list = new Profile_list();
431 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
432 'from profile_tag join profile_list '.
433 'on (profile_tag.tagger = profile_list.tagger ' .
434 ' and profile_tag.tag = profile_list.tag) ' .
435 'where profile_tag.tagged = %d ',
439 if ($auth_user instanceof User || $auth_user instanceof Profile) {
440 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
441 'OR ( profile_list.tagger = %d AND ' .
442 'profile_list.private = true ) )',
445 $qry .= 'AND profile_list.private = 0 ';
449 $qry .= sprintf('AND (cursor > %d) ', $since_id);
453 $qry .= sprintf('AND (cursor < %d) ', $max_id);
456 $qry .= 'ORDER BY profile_tag.modified DESC ';
458 if ($offset >= 0 && !is_null($limit)) {
459 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
466 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
468 $tags = new Profile_list();
469 $tags->private = true;
470 $tags->tagger = $this->id;
473 $tags->whereAdd('id > '.$since_id);
477 $tags->whereAdd('id <= '.$max_id);
480 if($offset>=0 && !is_null($limit)) {
481 $tags->limit($offset, $limit);
484 $tags->orderBy('id DESC');
490 function hasLocalTags()
492 $tags = new Profile_tag();
494 $tags->joinAdd(array('tagger', 'user:id'));
495 $tags->whereAdd('tagged = '.$this->id);
496 $tags->whereAdd('tagger != '.$this->id);
501 return ($tags->N == 0) ? false : true;
504 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
506 $lists = new Profile_list();
507 $subs = new Profile_tag_subscription();
509 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
511 #@fixme: postgres (round(date_part('epoch', my_date)))
512 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
514 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
517 $lists->whereAdd('cursor > '.$since_id);
521 $lists->whereAdd('cursor <= '.$max_id);
524 if($offset>=0 && !is_null($limit)) {
525 $lists->limit($offset, $limit);
528 $lists->orderBy('"cursor" DESC');
535 * Request to join the given group.
536 * May throw exceptions on failure.
538 * @param User_group $group
539 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
541 function joinGroup(User_group $group)
544 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
545 $join = Group_join_queue::saveNew($this, $group);
547 if (Event::handle('StartJoinGroup', array($group, $this))) {
548 $join = Group_member::join($group->id, $this->id);
549 self::blow('profile:groups:%d', $this->id);
550 self::blow('group:member_ids:%d', $group->id);
551 self::blow('group:member_count:%d', $group->id);
552 Event::handle('EndJoinGroup', array($group, $this));
556 // Send any applicable notifications...
563 * Leave a group that this profile is a member of.
565 * @param User_group $group
567 function leaveGroup(User_group $group)
569 if (Event::handle('StartLeaveGroup', array($group, $this))) {
570 Group_member::leave($group->id, $this->id);
571 self::blow('profile:groups:%d', $this->id);
572 self::blow('group:member_ids:%d', $group->id);
573 self::blow('group:member_count:%d', $group->id);
574 Event::handle('EndLeaveGroup', array($group, $this));
578 function avatarUrl($size=AVATAR_PROFILE_SIZE)
580 return Avatar::urlByProfile($this, $size);
583 function getSubscribed($offset=0, $limit=null)
585 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
587 $profiles = Profile::listFind('id', $subs);
588 } catch (NoResultException $e) {
594 function getSubscribers($offset=0, $limit=null)
596 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
598 $profiles = Profile::listFind('id', $subs);
599 } catch (NoResultException $e) {
605 function getTaggedSubscribers($tag, $offset=0, $limit=null)
608 'SELECT profile.* ' .
609 'FROM profile JOIN subscription ' .
610 'ON profile.id = subscription.subscriber ' .
611 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
612 'AND profile_tag.tagger = subscription.subscribed) ' .
613 'WHERE subscription.subscribed = %d ' .
614 "AND profile_tag.tag = '%s' " .
615 'AND subscription.subscribed != subscription.subscriber ' .
616 'ORDER BY subscription.created DESC ';
619 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
622 $profile = new Profile();
624 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
629 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
632 'SELECT profile.* ' .
633 'FROM profile JOIN subscription ' .
634 'ON profile.id = subscription.subscribed ' .
635 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
636 'AND profile_tag.tagger = subscription.subscriber) ' .
637 'WHERE subscription.subscriber = %d ' .
638 "AND profile_tag.tag = '%s' " .
639 'AND subscription.subscribed != subscription.subscriber ' .
640 'ORDER BY subscription.created DESC ';
642 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
644 $profile = new Profile();
646 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
652 * Get pending subscribers, who have not yet been approved.
658 function getRequests($offset=0, $limit=null)
661 'SELECT profile.* ' .
662 'FROM profile JOIN subscription_queue '.
663 'ON profile.id = subscription_queue.subscriber ' .
664 'WHERE subscription_queue.subscribed = %d ' .
665 'ORDER BY subscription_queue.created DESC ';
667 if ($limit != null) {
668 if (common_config('db','type') == 'pgsql') {
669 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
671 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
675 $members = new Profile();
677 $members->query(sprintf($qry, $this->id));
681 function subscriptionCount()
683 $c = Cache::instance();
686 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
687 if (is_integer($cnt)) {
692 $sub = new Subscription();
693 $sub->subscriber = $this->id;
695 $cnt = (int) $sub->count('distinct subscribed');
697 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
700 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
706 function subscriberCount()
708 $c = Cache::instance();
710 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
711 if (is_integer($cnt)) {
716 $sub = new Subscription();
717 $sub->subscribed = $this->id;
718 $sub->whereAdd('subscriber != subscribed');
719 $cnt = (int) $sub->count('distinct subscriber');
722 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
729 * Is this profile subscribed to another profile?
731 * @param Profile $other
734 function isSubscribed($other)
736 return Subscription::exists($this, $other);
740 * Check if a pending subscription request is outstanding for this...
742 * @param Profile $other
745 function hasPendingSubscription($other)
747 return Subscription_queue::exists($this, $other);
751 * Are these two profiles subscribed to each other?
753 * @param Profile $other
756 function mutuallySubscribed($other)
758 return $this->isSubscribed($other) &&
759 $other->isSubscribed($this);
762 function hasFave($notice)
764 $fave = Fave::pkeyGet(array('user_id' => $this->id,
765 'notice_id' => $notice->id));
766 return ((is_null($fave)) ? false : true);
771 $c = Cache::instance();
773 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
774 if (is_integer($cnt)) {
780 $faves->user_id = $this->id;
781 $cnt = (int) $faves->count('notice_id');
784 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
790 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
792 return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
795 function noticeCount()
797 $c = Cache::instance();
800 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
801 if (is_integer($cnt)) {
806 $notices = new Notice();
807 $notices->profile_id = $this->id;
808 $cnt = (int) $notices->count('distinct id');
811 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
817 function blowFavesCache()
819 $cache = Cache::instance();
821 // Faves don't happen chronologically, so we need to blow
823 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
824 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
825 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
826 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
828 $this->blowFaveCount();
831 function blowSubscriberCount()
833 $c = Cache::instance();
835 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
839 function blowSubscriptionCount()
841 $c = Cache::instance();
843 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
847 function blowFaveCount()
849 $c = Cache::instance();
851 $c->delete(Cache::key('profile:fave_count:'.$this->id));
855 function blowNoticeCount()
857 $c = Cache::instance();
859 $c->delete(Cache::key('profile:notice_count:'.$this->id));
863 static function maxBio()
865 $biolimit = common_config('profile', 'biolimit');
866 // null => use global limit (distinct from 0!)
867 if (is_null($biolimit)) {
868 $biolimit = common_config('site', 'textlimit');
873 static function bioTooLong($bio)
875 $biolimit = self::maxBio();
876 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
879 function update($dataObject=false)
881 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
883 $local = $this->getUser();
884 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
885 $origuser = clone($local);
886 $local->nickname = $this->nickname;
887 $result = $local->updateKeys($origuser);
888 if ($result === false) {
889 common_log_db_error($local, 'UPDATE', __FILE__);
890 // TRANS: Server error thrown when user profile settings could not be updated.
891 throw new ServerException(_('Could not update user nickname.'));
894 // Clear the site owner, in case nickname changed
895 if ($local->hasRole(Profile_role::OWNER)) {
896 User::blow('user:site_owner');
898 } catch (NoSuchUserException $e) {
903 return parent::update($dataObject);
906 function delete($useWhere=false)
908 $this->_deleteNotices();
909 $this->_deleteSubscriptions();
910 $this->_deleteMessages();
911 $this->_deleteTags();
912 $this->_deleteBlocks();
913 Avatar::deleteFromProfile($this, true);
915 // Warning: delete() will run on the batch objects,
916 // not on individual objects.
917 $related = array('Reply',
920 Event::handle('ProfileDeleteRelated', array($this, &$related));
922 foreach ($related as $cls) {
924 $inst->profile_id = $this->id;
928 return parent::delete($useWhere);
931 function _deleteNotices()
933 $notice = new Notice();
934 $notice->profile_id = $this->id;
936 if ($notice->find()) {
937 while ($notice->fetch()) {
938 $other = clone($notice);
944 function _deleteSubscriptions()
946 $sub = new Subscription();
947 $sub->subscriber = $this->id;
951 while ($sub->fetch()) {
952 $other = Profile::getKV('id', $sub->subscribed);
956 if ($other->id == $this->id) {
959 Subscription::cancel($this, $other);
962 $subd = new Subscription();
963 $subd->subscribed = $this->id;
966 while ($subd->fetch()) {
967 $other = Profile::getKV('id', $subd->subscriber);
971 if ($other->id == $this->id) {
974 Subscription::cancel($other, $this);
977 $self = new Subscription();
979 $self->subscriber = $this->id;
980 $self->subscribed = $this->id;
985 function _deleteMessages()
987 $msg = new Message();
988 $msg->from_profile = $this->id;
991 $msg = new Message();
992 $msg->to_profile = $this->id;
996 function _deleteTags()
998 $tag = new Profile_tag();
999 $tag->tagged = $this->id;
1003 function _deleteBlocks()
1005 $block = new Profile_block();
1006 $block->blocked = $this->id;
1009 $block = new Group_block();
1010 $block->blocked = $this->id;
1014 // XXX: identical to Notice::getLocation.
1016 public function getLocation()
1020 if (!empty($this->location_id) && !empty($this->location_ns)) {
1021 $location = Location::fromId($this->location_id, $this->location_ns);
1024 if (is_null($location)) { // no ID, or Location::fromId() failed
1025 if (!empty($this->lat) && !empty($this->lon)) {
1026 $location = Location::fromLatLon($this->lat, $this->lon);
1030 if (is_null($location)) { // still haven't found it!
1031 if (!empty($this->location)) {
1032 $location = Location::fromName($this->location);
1039 public function shareLocation()
1041 $cfg = common_config('location', 'share');
1043 if ($cfg == 'always') {
1045 } else if ($cfg == 'never') {
1048 $share = common_config('location', 'sharedefault');
1050 // Check if user has a personal setting for this
1051 $prefs = User_location_prefs::getKV('user_id', $this->id);
1053 if (!empty($prefs)) {
1054 $share = $prefs->share_location;
1062 function hasRole($name)
1065 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1066 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1068 $has_role = !empty($role);
1069 Event::handle('EndHasRole', array($this, $name, $has_role));
1074 function grantRole($name)
1076 if (Event::handle('StartGrantRole', array($this, $name))) {
1078 $role = new Profile_role();
1080 $role->profile_id = $this->id;
1081 $role->role = $name;
1082 $role->created = common_sql_now();
1084 $result = $role->insert();
1087 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1090 if ($name == 'owner') {
1091 User::blow('user:site_owner');
1094 Event::handle('EndGrantRole', array($this, $name));
1100 function revokeRole($name)
1102 if (Event::handle('StartRevokeRole', array($this, $name))) {
1104 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1108 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1109 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1110 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1113 $result = $role->delete();
1116 common_log_db_error($role, 'DELETE', __FILE__);
1117 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1118 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1119 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1122 if ($name == 'owner') {
1123 User::blow('user:site_owner');
1126 Event::handle('EndRevokeRole', array($this, $name));
1132 function isSandboxed()
1134 return $this->hasRole(Profile_role::SANDBOXED);
1137 function isSilenced()
1139 return $this->hasRole(Profile_role::SILENCED);
1144 $this->grantRole(Profile_role::SANDBOXED);
1147 function unsandbox()
1149 $this->revokeRole(Profile_role::SANDBOXED);
1154 $this->grantRole(Profile_role::SILENCED);
1155 if (common_config('notice', 'hidespam')) {
1156 $this->flushVisibility();
1160 function unsilence()
1162 $this->revokeRole(Profile_role::SILENCED);
1163 if (common_config('notice', 'hidespam')) {
1164 $this->flushVisibility();
1168 function flushVisibility()
1171 $stream = new ProfileNoticeStream($this, $this);
1172 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1173 foreach ($ids as $id) {
1174 self::blow('notice:in-scope-for:%d:null', $id);
1179 * Does this user have the right to do X?
1181 * With our role-based authorization, this is merely a lookup for whether the user
1182 * has a particular role. The implementation currently uses a switch statement
1183 * to determine if the user has the pre-defined role to exercise the right. Future
1184 * implementations may allow per-site roles, and different mappings of roles to rights.
1186 * @param $right string Name of the right, usually a constant in class Right
1187 * @return boolean whether the user has the right in question
1189 public function hasRight($right)
1193 if ($this->hasRole(Profile_role::DELETED)) {
1197 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1200 case Right::DELETEOTHERSNOTICE:
1201 case Right::MAKEGROUPADMIN:
1202 case Right::SANDBOXUSER:
1203 case Right::SILENCEUSER:
1204 case Right::DELETEUSER:
1205 case Right::DELETEGROUP:
1206 case Right::TRAINSPAM:
1207 case Right::REVIEWSPAM:
1208 $result = $this->hasRole(Profile_role::MODERATOR);
1210 case Right::CONFIGURESITE:
1211 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1213 case Right::GRANTROLE:
1214 case Right::REVOKEROLE:
1215 $result = $this->hasRole(Profile_role::OWNER);
1217 case Right::NEWNOTICE:
1218 case Right::NEWMESSAGE:
1219 case Right::SUBSCRIBE:
1220 case Right::CREATEGROUP:
1221 $result = !$this->isSilenced();
1223 case Right::PUBLICNOTICE:
1224 case Right::EMAILONREPLY:
1225 case Right::EMAILONSUBSCRIBE:
1226 case Right::EMAILONFAVE:
1227 $result = !$this->isSandboxed();
1229 case Right::WEBLOGIN:
1230 $result = !$this->isSilenced();
1233 $result = !$this->isSilenced();
1235 case Right::BACKUPACCOUNT:
1236 $result = common_config('profile', 'backup');
1238 case Right::RESTOREACCOUNT:
1239 $result = common_config('profile', 'restore');
1241 case Right::DELETEACCOUNT:
1242 $result = common_config('profile', 'delete');
1244 case Right::MOVEACCOUNT:
1245 $result = common_config('profile', 'move');
1255 // FIXME: Can't put Notice typing here due to ArrayWrapper
1256 public function hasRepeated($notice)
1258 // XXX: not really a pkey, but should work
1260 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1261 'repeat_of' => $notice->id));
1263 return !empty($notice);
1267 * Returns an XML string fragment with limited profile information
1268 * as an Atom <author> element.
1270 * Assumes that Atom has been previously set up as the base namespace.
1272 * @param Profile $cur the current authenticated user
1276 function asAtomAuthor($cur = null)
1278 $xs = new XMLStringer(true);
1280 $xs->elementStart('author');
1281 $xs->element('name', null, $this->nickname);
1282 $xs->element('uri', null, $this->getUri());
1285 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1286 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1287 $xs->element('statusnet:profile_info', $attrs, null);
1289 $xs->elementEnd('author');
1291 return $xs->getString();
1295 * Extra profile info for atom entries
1297 * Clients use some extra profile info in the atom stream.
1298 * This gives it to them.
1300 * @param User $cur Current user
1302 * @return array representation of <statusnet:profile_info> element or null
1305 function profileInfo($cur)
1307 $profileInfoAttr = array('local_id' => $this->id);
1310 // Whether the current user is a subscribed to this profile
1311 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1312 // Whether the current user is has blocked this profile
1313 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1316 return array('statusnet:profile_info', $profileInfoAttr, null);
1320 * Returns an XML string fragment with profile information as an
1321 * Activity Streams <activity:actor> element.
1323 * Assumes that 'activity' namespace has been previously defined.
1327 function asActivityActor()
1329 return $this->asActivityNoun('actor');
1333 * Returns an XML string fragment with profile information as an
1334 * Activity Streams noun object with the given element type.
1336 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1337 * previously defined.
1339 * @param string $element one of 'actor', 'subject', 'object', 'target'
1343 function asActivityNoun($element)
1345 $noun = ActivityObject::fromProfile($this);
1346 return $noun->asString('activity:' . $element);
1350 * Returns the profile's canonical url, not necessarily a uri/unique id
1352 * @return string $profileurl
1354 public function getUrl()
1356 if (empty($this->profileurl) ||
1357 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1358 throw new InvalidUrlException($this->profileurl);
1360 return $this->profileurl;
1364 * Returns the best URI for a profile. Plugins may override.
1366 * @return string $uri
1368 public function getUri()
1372 // give plugins a chance to set the URI
1373 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1375 // check for a local user first
1376 $user = User::getKV('id', $this->id);
1378 if (!empty($user)) {
1382 Event::handle('EndGetProfileUri', array($this, &$uri));
1389 * Returns an assumed acct: URI for a profile. Plugins are required.
1391 * @return string $uri
1393 public function getAcctUri()
1397 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1398 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1401 if ($acct === null) {
1402 throw new ProfileNoAcctUriException($this);
1408 function hasBlocked($other)
1410 $block = Profile_block::exists($this, $other);
1411 return !empty($block);
1414 function getAtomFeed()
1418 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1419 $user = User::getKV('id', $this->id);
1420 if (!empty($user)) {
1421 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1422 'format' => 'atom'));
1424 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1430 static function fromURI($uri)
1434 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1436 $user = User::getKV('uri', $uri);
1437 if (!empty($user)) {
1438 $profile = $user->getProfile();
1440 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1446 function canRead(Notice $notice)
1448 if ($notice->scope & Notice::SITE_SCOPE) {
1449 $user = $this->getUser();
1455 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1456 $replies = $notice->getReplies();
1458 if (!in_array($this->id, $replies)) {
1459 $groups = $notice->getGroups();
1463 foreach ($groups as $group) {
1464 if ($this->isMember($group)) {
1476 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1477 $author = $notice->getProfile();
1478 if (!Subscription::exists($this, $author)) {
1486 static function current()
1488 $user = common_current_user();
1492 $profile = $user->getProfile();
1498 * Magic function called at serialize() time.
1500 * We use this to drop a couple process-specific references
1501 * from DB_DataObject which can cause trouble in future
1504 * @return array of variable names to include in serialization.
1509 $vars = parent::__sleep();
1510 $skip = array('_user', '_avatars');
1511 return array_diff($vars, $skip);
1514 public function getProfile()