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 = array();
97 public function getUser()
99 if (!isset($this->_user[$this->id])) {
100 $user = User::getKV('id', $this->id);
101 if (!$user instanceof User) {
102 throw new NoSuchUserException(array('id'=>$this->id));
104 $this->_user[$this->id] = $user;
106 return $this->_user[$this->id];
109 protected $_group = array();
111 public function getGroup()
113 if (!isset($this->_group[$this->id])) {
114 $group = User_group::getKV('profile_id', $this->id);
115 if (!$group instanceof User_group) {
116 throw new NoSuchGroupException(array('profile_id'=>$this->id));
118 $this->_group[$this->id] = $group;
120 return $this->_group[$this->id];
123 public function isGroup()
128 } catch (NoSuchGroupException $e) {
133 public function isLocal()
137 } catch (NoSuchUserException $e) {
143 public function getAvatar($width, $height=null)
145 return Avatar::byProfile($this, $width, $height);
148 public function setOriginal($filename)
150 $imagefile = new ImageFile($this->id, Avatar::path($filename));
152 $avatar = new Avatar();
153 $avatar->profile_id = $this->id;
154 $avatar->width = $imagefile->width;
155 $avatar->height = $imagefile->height;
156 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
157 $avatar->filename = $filename;
158 $avatar->original = true;
159 $avatar->url = Avatar::url($filename);
160 $avatar->created = common_sql_now();
162 // XXX: start a transaction here
163 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
164 // If we can't delete the old avatars, let's abort right here.
165 @unlink(Avatar::path($filename));
173 * Gets either the full name (if filled) or the nickname.
177 function getBestName()
179 return ($this->fullname) ? $this->fullname : $this->nickname;
183 * Takes the currently scoped profile into account to give a name
184 * to list in notice streams. Preferences may differ between profiles.
186 function getStreamName()
188 $user = common_current_user();
189 if ($user instanceof User && $user->streamNicknames()) {
190 return $this->nickname;
193 return $this->getBestName();
197 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
198 * if no fullname is provided.
202 function getFancyName()
204 if ($this->fullname) {
205 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
206 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
208 return $this->nickname;
213 * Get the most recent notice posted by this user, if any.
215 * @return mixed Notice or null
217 function getCurrentNotice()
219 $notice = $this->getNotices(0, 1);
221 if ($notice->fetch()) {
222 if ($notice instanceof ArrayWrapper) {
223 // hack for things trying to work with single notices
224 return $notice->_items[0];
232 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
234 $stream = new TaggedProfileNoticeStream($this, $tag);
236 return $stream->getNotices($offset, $limit, $since_id, $max_id);
239 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
241 $stream = new ProfileNoticeStream($this, $scoped);
243 return $stream->getNotices($offset, $limit, $since_id, $max_id);
246 function isMember(User_group $group)
248 $groups = $this->getGroups(0, null);
249 while ($groups instanceof User_group && $groups->fetch()) {
250 if ($groups->id == $group->id) {
257 function isAdmin(User_group $group)
259 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
260 'group_id' => $group->id));
261 return (!empty($gm) && $gm->is_admin);
264 function isPendingMember($group)
266 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
267 'group_id' => $group->id));
268 return !empty($request);
271 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
275 $keypart = sprintf('profile:groups:%d', $this->id);
277 $idstring = self::cacheGet($keypart);
279 if ($idstring !== false) {
280 $ids = explode(',', $idstring);
282 $gm = new Group_member();
284 $gm->profile_id = $this->id;
287 while ($gm->fetch()) {
288 $ids[] = $gm->group_id;
292 self::cacheSet($keypart, implode(',', $ids));
295 if (!is_null($offset) && !is_null($limit)) {
296 $ids = array_slice($ids, $offset, $limit);
300 return User_group::listFind('id', $ids);
301 } catch (NoResultException $e) {
302 return null; // throw exception when we handle it everywhere
306 function getGroupCount() {
307 $groups = $this->getGroups(0, null);
308 return $groups instanceof User_group
313 function isTagged($peopletag)
315 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
316 'tagged' => $this->id,
317 'tag' => $peopletag->tag));
321 function canTag($tagged)
323 if (empty($tagged)) {
327 if ($tagged->id == $this->id) {
331 $all = common_config('peopletag', 'allow_tagging', 'all');
332 $local = common_config('peopletag', 'allow_tagging', 'local');
333 $remote = common_config('peopletag', 'allow_tagging', 'remote');
334 $subs = common_config('peopletag', 'allow_tagging', 'subs');
340 $tagged_user = $tagged->getUser();
341 if (!empty($tagged_user)) {
346 return (Subscription::exists($this, $tagged) ||
347 Subscription::exists($tagged, $this));
348 } else if ($remote) {
354 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
358 $keypart = sprintf('profile:lists:%d', $this->id);
360 $idstr = self::cacheGet($keypart);
362 if ($idstr !== false) {
363 $ids = explode(',', $idstr);
365 $list = new Profile_list();
367 $list->selectAdd('id');
368 $list->tagger = $this->id;
369 $list->selectAdd('id as "cursor"');
372 $list->whereAdd('id > '.$since_id);
376 $list->whereAdd('id <= '.$max_id);
379 if($offset>=0 && !is_null($limit)) {
380 $list->limit($offset, $limit);
383 $list->orderBy('id DESC');
386 while ($list->fetch()) {
391 self::cacheSet($keypart, implode(',', $ids));
394 $showPrivate = (($auth_user instanceof User ||
395 $auth_user instanceof Profile) &&
396 $auth_user->id === $this->id);
400 foreach ($ids as $id) {
401 $list = Profile_list::getKV('id', $id);
403 ($showPrivate || !$list->private)) {
405 if (!isset($list->cursor)) {
406 $list->cursor = $list->id;
413 return new ArrayWrapper($lists);
417 * Get tags that other people put on this profile, in reverse-chron order
419 * @param (Profile|User) $auth_user Authorized user (used for privacy)
420 * @param int $offset Offset from latest
421 * @param int $limit Max number to get
422 * @param datetime $since_id max date
423 * @param datetime $max_id min date
425 * @return Profile_list resulting lists
428 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
430 $list = new Profile_list();
432 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
433 'from profile_tag join profile_list '.
434 'on (profile_tag.tagger = profile_list.tagger ' .
435 ' and profile_tag.tag = profile_list.tag) ' .
436 'where profile_tag.tagged = %d ',
440 if ($auth_user instanceof User || $auth_user instanceof Profile) {
441 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
442 'OR ( profile_list.tagger = %d AND ' .
443 'profile_list.private = true ) )',
446 $qry .= 'AND profile_list.private = 0 ';
450 $qry .= sprintf('AND (cursor > %d) ', $since_id);
454 $qry .= sprintf('AND (cursor < %d) ', $max_id);
457 $qry .= 'ORDER BY profile_tag.modified DESC ';
459 if ($offset >= 0 && !is_null($limit)) {
460 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
467 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
469 $tags = new Profile_list();
470 $tags->private = true;
471 $tags->tagger = $this->id;
474 $tags->whereAdd('id > '.$since_id);
478 $tags->whereAdd('id <= '.$max_id);
481 if($offset>=0 && !is_null($limit)) {
482 $tags->limit($offset, $limit);
485 $tags->orderBy('id DESC');
491 function hasLocalTags()
493 $tags = new Profile_tag();
495 $tags->joinAdd(array('tagger', 'user:id'));
496 $tags->whereAdd('tagged = '.$this->id);
497 $tags->whereAdd('tagger != '.$this->id);
502 return ($tags->N == 0) ? false : true;
505 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
507 $lists = new Profile_list();
508 $subs = new Profile_tag_subscription();
510 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
512 #@fixme: postgres (round(date_part('epoch', my_date)))
513 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
515 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
518 $lists->whereAdd('cursor > '.$since_id);
522 $lists->whereAdd('cursor <= '.$max_id);
525 if($offset>=0 && !is_null($limit)) {
526 $lists->limit($offset, $limit);
529 $lists->orderBy('"cursor" DESC');
536 * Request to join the given group.
537 * May throw exceptions on failure.
539 * @param User_group $group
540 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
542 function joinGroup(User_group $group)
545 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
546 $join = Group_join_queue::saveNew($this, $group);
548 if (Event::handle('StartJoinGroup', array($group, $this))) {
549 $join = Group_member::join($group->id, $this->id);
550 self::blow('profile:groups:%d', $this->id);
551 self::blow('group:member_ids:%d', $group->id);
552 self::blow('group:member_count:%d', $group->id);
553 Event::handle('EndJoinGroup', array($group, $this));
557 // Send any applicable notifications...
564 * Leave a group that this profile is a member of.
566 * @param User_group $group
568 function leaveGroup(User_group $group)
570 if (Event::handle('StartLeaveGroup', array($group, $this))) {
571 Group_member::leave($group->id, $this->id);
572 self::blow('profile:groups:%d', $this->id);
573 self::blow('group:member_ids:%d', $group->id);
574 self::blow('group:member_count:%d', $group->id);
575 Event::handle('EndLeaveGroup', array($group, $this));
579 function avatarUrl($size=AVATAR_PROFILE_SIZE)
581 return Avatar::urlByProfile($this, $size);
584 function getSubscribed($offset=0, $limit=null)
586 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
588 $profiles = Profile::listFind('id', $subs);
589 } catch (NoResultException $e) {
595 function getSubscribers($offset=0, $limit=null)
597 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
599 $profiles = Profile::listFind('id', $subs);
600 } catch (NoResultException $e) {
606 function getTaggedSubscribers($tag, $offset=0, $limit=null)
609 'SELECT profile.* ' .
610 'FROM profile JOIN subscription ' .
611 'ON profile.id = subscription.subscriber ' .
612 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
613 'AND profile_tag.tagger = subscription.subscribed) ' .
614 'WHERE subscription.subscribed = %d ' .
615 "AND profile_tag.tag = '%s' " .
616 'AND subscription.subscribed != subscription.subscriber ' .
617 'ORDER BY subscription.created DESC ';
620 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
623 $profile = new Profile();
625 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
630 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
633 'SELECT profile.* ' .
634 'FROM profile JOIN subscription ' .
635 'ON profile.id = subscription.subscribed ' .
636 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
637 'AND profile_tag.tagger = subscription.subscriber) ' .
638 'WHERE subscription.subscriber = %d ' .
639 "AND profile_tag.tag = '%s' " .
640 'AND subscription.subscribed != subscription.subscriber ' .
641 'ORDER BY subscription.created DESC ';
643 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
645 $profile = new Profile();
647 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
653 * Get pending subscribers, who have not yet been approved.
659 function getRequests($offset=0, $limit=null)
662 'SELECT profile.* ' .
663 'FROM profile JOIN subscription_queue '.
664 'ON profile.id = subscription_queue.subscriber ' .
665 'WHERE subscription_queue.subscribed = %d ' .
666 'ORDER BY subscription_queue.created DESC ';
668 if ($limit != null) {
669 if (common_config('db','type') == 'pgsql') {
670 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
672 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
676 $members = new Profile();
678 $members->query(sprintf($qry, $this->id));
682 function subscriptionCount()
684 $c = Cache::instance();
687 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
688 if (is_integer($cnt)) {
693 $sub = new Subscription();
694 $sub->subscriber = $this->id;
696 $cnt = (int) $sub->count('distinct subscribed');
698 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
701 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
707 function subscriberCount()
709 $c = Cache::instance();
711 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
712 if (is_integer($cnt)) {
717 $sub = new Subscription();
718 $sub->subscribed = $this->id;
719 $sub->whereAdd('subscriber != subscribed');
720 $cnt = (int) $sub->count('distinct subscriber');
723 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
730 * Is this profile subscribed to another profile?
732 * @param Profile $other
735 function isSubscribed(Profile $other)
737 return Subscription::exists($this, $other);
741 * Check if a pending subscription request is outstanding for this...
743 * @param Profile $other
746 function hasPendingSubscription(Profile $other)
748 return Subscription_queue::exists($this, $other);
752 * Are these two profiles subscribed to each other?
754 * @param Profile $other
757 function mutuallySubscribed(Profile $other)
759 return $this->isSubscribed($other) &&
760 $other->isSubscribed($this);
763 function hasFave($notice)
765 $fave = Fave::pkeyGet(array('user_id' => $this->id,
766 'notice_id' => $notice->id));
767 return ((is_null($fave)) ? false : true);
772 $c = Cache::instance();
774 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
775 if (is_integer($cnt)) {
781 $faves->user_id = $this->id;
782 $cnt = (int) $faves->count('notice_id');
785 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
791 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
793 return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
796 function noticeCount()
798 $c = Cache::instance();
801 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
802 if (is_integer($cnt)) {
807 $notices = new Notice();
808 $notices->profile_id = $this->id;
809 $cnt = (int) $notices->count('distinct id');
812 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
818 function blowFavesCache()
820 $cache = Cache::instance();
822 // Faves don't happen chronologically, so we need to blow
824 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
825 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
826 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
827 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
829 $this->blowFaveCount();
832 function blowSubscriberCount()
834 $c = Cache::instance();
836 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
840 function blowSubscriptionCount()
842 $c = Cache::instance();
844 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
848 function blowFaveCount()
850 $c = Cache::instance();
852 $c->delete(Cache::key('profile:fave_count:'.$this->id));
856 function blowNoticeCount()
858 $c = Cache::instance();
860 $c->delete(Cache::key('profile:notice_count:'.$this->id));
864 static function maxBio()
866 $biolimit = common_config('profile', 'biolimit');
867 // null => use global limit (distinct from 0!)
868 if (is_null($biolimit)) {
869 $biolimit = common_config('site', 'textlimit');
874 static function bioTooLong($bio)
876 $biolimit = self::maxBio();
877 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
880 function update($dataObject=false)
882 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
884 $local = $this->getUser();
885 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
886 $origuser = clone($local);
887 $local->nickname = $this->nickname;
888 $result = $local->updateKeys($origuser);
889 if ($result === false) {
890 common_log_db_error($local, 'UPDATE', __FILE__);
891 // TRANS: Server error thrown when user profile settings could not be updated.
892 throw new ServerException(_('Could not update user nickname.'));
895 // Clear the site owner, in case nickname changed
896 if ($local->hasRole(Profile_role::OWNER)) {
897 User::blow('user:site_owner');
899 } catch (NoSuchUserException $e) {
904 return parent::update($dataObject);
907 function delete($useWhere=false)
909 $this->_deleteNotices();
910 $this->_deleteSubscriptions();
911 $this->_deleteMessages();
912 $this->_deleteTags();
913 $this->_deleteBlocks();
914 $this->_deleteAttentions();
915 Avatar::deleteFromProfile($this, true);
917 // Warning: delete() will run on the batch objects,
918 // not on individual objects.
919 $related = array('Reply',
922 Event::handle('ProfileDeleteRelated', array($this, &$related));
924 foreach ($related as $cls) {
926 $inst->profile_id = $this->id;
930 return parent::delete($useWhere);
933 function _deleteNotices()
935 $notice = new Notice();
936 $notice->profile_id = $this->id;
938 if ($notice->find()) {
939 while ($notice->fetch()) {
940 $other = clone($notice);
946 function _deleteSubscriptions()
948 $sub = new Subscription();
949 $sub->subscriber = $this->id;
953 while ($sub->fetch()) {
954 $other = Profile::getKV('id', $sub->subscribed);
958 if ($other->id == $this->id) {
961 Subscription::cancel($this, $other);
964 $subd = new Subscription();
965 $subd->subscribed = $this->id;
968 while ($subd->fetch()) {
969 $other = Profile::getKV('id', $subd->subscriber);
973 if ($other->id == $this->id) {
976 Subscription::cancel($other, $this);
979 $self = new Subscription();
981 $self->subscriber = $this->id;
982 $self->subscribed = $this->id;
987 function _deleteMessages()
989 $msg = new Message();
990 $msg->from_profile = $this->id;
993 $msg = new Message();
994 $msg->to_profile = $this->id;
998 function _deleteTags()
1000 $tag = new Profile_tag();
1001 $tag->tagged = $this->id;
1005 function _deleteBlocks()
1007 $block = new Profile_block();
1008 $block->blocked = $this->id;
1011 $block = new Group_block();
1012 $block->blocked = $this->id;
1016 function _deleteAttentions()
1018 $att = new Attention();
1019 $att->profile_id = $this->getID();
1022 while ($att->fetch()) {
1023 // Can't do delete() on the object directly since it won't remove all of it
1024 $other = clone($att);
1030 // XXX: identical to Notice::getLocation.
1032 public function getLocation()
1036 if (!empty($this->location_id) && !empty($this->location_ns)) {
1037 $location = Location::fromId($this->location_id, $this->location_ns);
1040 if (is_null($location)) { // no ID, or Location::fromId() failed
1041 if (!empty($this->lat) && !empty($this->lon)) {
1042 $location = Location::fromLatLon($this->lat, $this->lon);
1046 if (is_null($location)) { // still haven't found it!
1047 if (!empty($this->location)) {
1048 $location = Location::fromName($this->location);
1055 public function shareLocation()
1057 $cfg = common_config('location', 'share');
1059 if ($cfg == 'always') {
1061 } else if ($cfg == 'never') {
1064 $share = common_config('location', 'sharedefault');
1066 // Check if user has a personal setting for this
1067 $prefs = User_location_prefs::getKV('user_id', $this->id);
1069 if (!empty($prefs)) {
1070 $share = $prefs->share_location;
1078 function hasRole($name)
1081 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1082 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1084 $has_role = !empty($role);
1085 Event::handle('EndHasRole', array($this, $name, $has_role));
1090 function grantRole($name)
1092 if (Event::handle('StartGrantRole', array($this, $name))) {
1094 $role = new Profile_role();
1096 $role->profile_id = $this->id;
1097 $role->role = $name;
1098 $role->created = common_sql_now();
1100 $result = $role->insert();
1103 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1106 if ($name == 'owner') {
1107 User::blow('user:site_owner');
1110 Event::handle('EndGrantRole', array($this, $name));
1116 function revokeRole($name)
1118 if (Event::handle('StartRevokeRole', array($this, $name))) {
1120 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1124 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1125 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1126 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1129 $result = $role->delete();
1132 common_log_db_error($role, 'DELETE', __FILE__);
1133 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1134 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1135 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1138 if ($name == 'owner') {
1139 User::blow('user:site_owner');
1142 Event::handle('EndRevokeRole', array($this, $name));
1148 function isSandboxed()
1150 return $this->hasRole(Profile_role::SANDBOXED);
1153 function isSilenced()
1155 return $this->hasRole(Profile_role::SILENCED);
1160 $this->grantRole(Profile_role::SANDBOXED);
1163 function unsandbox()
1165 $this->revokeRole(Profile_role::SANDBOXED);
1170 $this->grantRole(Profile_role::SILENCED);
1171 if (common_config('notice', 'hidespam')) {
1172 $this->flushVisibility();
1176 function unsilence()
1178 $this->revokeRole(Profile_role::SILENCED);
1179 if (common_config('notice', 'hidespam')) {
1180 $this->flushVisibility();
1184 function flushVisibility()
1187 $stream = new ProfileNoticeStream($this, $this);
1188 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1189 foreach ($ids as $id) {
1190 self::blow('notice:in-scope-for:%d:null', $id);
1195 * Does this user have the right to do X?
1197 * With our role-based authorization, this is merely a lookup for whether the user
1198 * has a particular role. The implementation currently uses a switch statement
1199 * to determine if the user has the pre-defined role to exercise the right. Future
1200 * implementations may allow per-site roles, and different mappings of roles to rights.
1202 * @param $right string Name of the right, usually a constant in class Right
1203 * @return boolean whether the user has the right in question
1205 public function hasRight($right)
1209 if ($this->hasRole(Profile_role::DELETED)) {
1213 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1216 case Right::DELETEOTHERSNOTICE:
1217 case Right::MAKEGROUPADMIN:
1218 case Right::SANDBOXUSER:
1219 case Right::SILENCEUSER:
1220 case Right::DELETEUSER:
1221 case Right::DELETEGROUP:
1222 case Right::TRAINSPAM:
1223 case Right::REVIEWSPAM:
1224 $result = $this->hasRole(Profile_role::MODERATOR);
1226 case Right::CONFIGURESITE:
1227 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1229 case Right::GRANTROLE:
1230 case Right::REVOKEROLE:
1231 $result = $this->hasRole(Profile_role::OWNER);
1233 case Right::NEWNOTICE:
1234 case Right::NEWMESSAGE:
1235 case Right::SUBSCRIBE:
1236 case Right::CREATEGROUP:
1237 $result = !$this->isSilenced();
1239 case Right::PUBLICNOTICE:
1240 case Right::EMAILONREPLY:
1241 case Right::EMAILONSUBSCRIBE:
1242 case Right::EMAILONFAVE:
1243 $result = !$this->isSandboxed();
1245 case Right::WEBLOGIN:
1246 $result = !$this->isSilenced();
1249 $result = !$this->isSilenced();
1251 case Right::BACKUPACCOUNT:
1252 $result = common_config('profile', 'backup');
1254 case Right::RESTOREACCOUNT:
1255 $result = common_config('profile', 'restore');
1257 case Right::DELETEACCOUNT:
1258 $result = common_config('profile', 'delete');
1260 case Right::MOVEACCOUNT:
1261 $result = common_config('profile', 'move');
1271 // FIXME: Can't put Notice typing here due to ArrayWrapper
1272 public function hasRepeated($notice)
1274 // XXX: not really a pkey, but should work
1276 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1277 'repeat_of' => $notice->id));
1279 return !empty($notice);
1283 * Returns an XML string fragment with limited profile information
1284 * as an Atom <author> element.
1286 * Assumes that Atom has been previously set up as the base namespace.
1288 * @param Profile $cur the current authenticated user
1292 function asAtomAuthor($cur = null)
1294 $xs = new XMLStringer(true);
1296 $xs->elementStart('author');
1297 $xs->element('name', null, $this->nickname);
1298 $xs->element('uri', null, $this->getUri());
1301 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1302 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1303 $xs->element('statusnet:profile_info', $attrs, null);
1305 $xs->elementEnd('author');
1307 return $xs->getString();
1311 * Extra profile info for atom entries
1313 * Clients use some extra profile info in the atom stream.
1314 * This gives it to them.
1316 * @param User $cur Current user
1318 * @return array representation of <statusnet:profile_info> element or null
1321 function profileInfo($cur)
1323 $profileInfoAttr = array('local_id' => $this->id);
1326 // Whether the current user is a subscribed to this profile
1327 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1328 // Whether the current user is has blocked this profile
1329 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1332 return array('statusnet:profile_info', $profileInfoAttr, null);
1336 * Returns an XML string fragment with profile information as an
1337 * Activity Streams <activity:actor> element.
1339 * Assumes that 'activity' namespace has been previously defined.
1343 function asActivityActor()
1345 return $this->asActivityNoun('actor');
1349 * Returns an XML string fragment with profile information as an
1350 * Activity Streams noun object with the given element type.
1352 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1353 * previously defined.
1355 * @param string $element one of 'actor', 'subject', 'object', 'target'
1359 function asActivityNoun($element)
1361 $noun = ActivityObject::fromProfile($this);
1362 return $noun->asString('activity:' . $element);
1366 * Returns the profile's canonical url, not necessarily a uri/unique id
1368 * @return string $profileurl
1370 public function getUrl()
1372 if (empty($this->profileurl) ||
1373 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1374 throw new InvalidUrlException($this->profileurl);
1376 return $this->profileurl;
1379 public function getNickname()
1381 return $this->nickname;
1385 * Returns the best URI for a profile. Plugins may override.
1387 * @return string $uri
1389 public function getUri()
1393 // give plugins a chance to set the URI
1394 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1396 // check for a local user first
1397 $user = User::getKV('id', $this->id);
1398 if ($user instanceof User) {
1399 $uri = $user->getUri();
1402 Event::handle('EndGetProfileUri', array($this, &$uri));
1409 * Returns an assumed acct: URI for a profile. Plugins are required.
1411 * @return string $uri
1413 public function getAcctUri()
1417 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1418 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1421 if ($acct === null) {
1422 throw new ProfileNoAcctUriException($this);
1428 function hasBlocked($other)
1430 $block = Profile_block::exists($this, $other);
1431 return !empty($block);
1434 function getAtomFeed()
1438 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1439 $user = User::getKV('id', $this->id);
1440 if (!empty($user)) {
1441 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1442 'format' => 'atom'));
1444 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1451 * Get a Profile object by URI. Will call external plugins for help
1452 * using the event StartGetProfileFromURI.
1454 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1456 static function fromUri($uri)
1460 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1461 // Get a local user when plugin lookup (like OStatus) fails
1462 $user = User::getKV('uri', $uri);
1463 if ($user instanceof User) {
1464 $profile = $user->getProfile();
1466 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1469 if (!$profile instanceof Profile) {
1470 throw new UnknownUriException($uri);
1476 function canRead(Notice $notice)
1478 if ($notice->scope & Notice::SITE_SCOPE) {
1479 $user = $this->getUser();
1485 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1486 $replies = $notice->getReplies();
1488 if (!in_array($this->id, $replies)) {
1489 $groups = $notice->getGroups();
1493 foreach ($groups as $group) {
1494 if ($this->isMember($group)) {
1506 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1507 $author = $notice->getProfile();
1508 if (!Subscription::exists($this, $author)) {
1516 static function current()
1518 $user = common_current_user();
1522 $profile = $user->getProfile();
1528 * Magic function called at serialize() time.
1530 * We use this to drop a couple process-specific references
1531 * from DB_DataObject which can cause trouble in future
1534 * @return array of variable names to include in serialization.
1539 $vars = parent::__sleep();
1540 $skip = array('_user', '_group');
1541 return array_diff($vars, $skip);
1544 public function getProfile()
1550 * This will perform shortenLinks with the connected User object.
1552 * Won't work on remote profiles or groups, so expect a
1553 * NoSuchUserException if you don't know it's a local User.
1555 * @param string $text String to shorten
1556 * @param boolean $always Disrespect minimum length etc.
1558 * @return string link-shortened $text
1560 public function shortenLinks($text, $always=false)
1562 return $this->getUser()->shortenLinks($text, $always);