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 public function isLocal()
113 } catch (NoSuchUserException $e) {
119 protected $_avatars = array();
121 public function getAvatar($width, $height=null)
123 return Avatar::byProfile($this, $width, $height);
126 public function setOriginal($filename)
128 $imagefile = new ImageFile($this->id, Avatar::path($filename));
130 $avatar = new Avatar();
131 $avatar->profile_id = $this->id;
132 $avatar->width = $imagefile->width;
133 $avatar->height = $imagefile->height;
134 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
135 $avatar->filename = $filename;
136 $avatar->original = true;
137 $avatar->url = Avatar::url($filename);
138 $avatar->created = common_sql_now();
140 // XXX: start a transaction here
141 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
142 // If we can't delete the old avatars, let's abort right here.
143 @unlink(Avatar::path($filename));
147 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
148 // We don't do a scaled one if original is our scaled size
149 if (!($avatar->width == $size && $avatar->height == $size)) {
151 Avatar::newSize($this, $size);
152 } catch (Exception $e) {
153 // should we abort the generation and live without smaller avatars?
162 * Gets either the full name (if filled) or the nickname.
166 function getBestName()
168 return ($this->fullname) ? $this->fullname : $this->nickname;
172 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
173 * if no fullname is provided.
177 function getFancyName()
179 if ($this->fullname) {
180 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
181 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
183 return $this->nickname;
188 * Get the most recent notice posted by this user, if any.
190 * @return mixed Notice or null
192 function getCurrentNotice()
194 $notice = $this->getNotices(0, 1);
196 if ($notice->fetch()) {
197 if ($notice instanceof ArrayWrapper) {
198 // hack for things trying to work with single notices
199 return $notice->_items[0];
207 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
209 $stream = new TaggedProfileNoticeStream($this, $tag);
211 return $stream->getNotices($offset, $limit, $since_id, $max_id);
214 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
216 $stream = new ProfileNoticeStream($this, $scoped);
218 return $stream->getNotices($offset, $limit, $since_id, $max_id);
221 function isMember($group)
223 $groups = $this->getGroups(0, null);
224 while ($groups instanceof User_group && $groups->fetch()) {
225 if ($groups->id == $group->id) {
232 function isAdmin($group)
234 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
235 'group_id' => $group->id));
236 return (!empty($gm) && $gm->is_admin);
239 function isPendingMember($group)
241 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
242 'group_id' => $group->id));
243 return !empty($request);
246 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
250 $keypart = sprintf('profile:groups:%d', $this->id);
252 $idstring = self::cacheGet($keypart);
254 if ($idstring !== false) {
255 $ids = explode(',', $idstring);
257 $gm = new Group_member();
259 $gm->profile_id = $this->id;
262 while ($gm->fetch()) {
263 $ids[] = $gm->group_id;
267 self::cacheSet($keypart, implode(',', $ids));
270 if (!is_null($offset) && !is_null($limit)) {
271 $ids = array_slice($ids, $offset, $limit);
275 return User_group::listFind('id', $ids);
276 } catch (NoResultException $e) {
277 return null; // throw exception when we handle it everywhere
281 function getGroupCount() {
282 $groups = $this->getGroups(0, null);
283 return $groups instanceof User_group
288 function isTagged($peopletag)
290 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
291 'tagged' => $this->id,
292 'tag' => $peopletag->tag));
296 function canTag($tagged)
298 if (empty($tagged)) {
302 if ($tagged->id == $this->id) {
306 $all = common_config('peopletag', 'allow_tagging', 'all');
307 $local = common_config('peopletag', 'allow_tagging', 'local');
308 $remote = common_config('peopletag', 'allow_tagging', 'remote');
309 $subs = common_config('peopletag', 'allow_tagging', 'subs');
315 $tagged_user = $tagged->getUser();
316 if (!empty($tagged_user)) {
321 return (Subscription::exists($this, $tagged) ||
322 Subscription::exists($tagged, $this));
323 } else if ($remote) {
329 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
333 $keypart = sprintf('profile:lists:%d', $this->id);
335 $idstr = self::cacheGet($keypart);
337 if ($idstr !== false) {
338 $ids = explode(',', $idstr);
340 $list = new Profile_list();
342 $list->selectAdd('id');
343 $list->tagger = $this->id;
344 $list->selectAdd('id as "cursor"');
347 $list->whereAdd('id > '.$since_id);
351 $list->whereAdd('id <= '.$max_id);
354 if($offset>=0 && !is_null($limit)) {
355 $list->limit($offset, $limit);
358 $list->orderBy('id DESC');
361 while ($list->fetch()) {
366 self::cacheSet($keypart, implode(',', $ids));
369 $showPrivate = (($auth_user instanceof User ||
370 $auth_user instanceof Profile) &&
371 $auth_user->id === $this->id);
375 foreach ($ids as $id) {
376 $list = Profile_list::getKV('id', $id);
378 ($showPrivate || !$list->private)) {
380 if (!isset($list->cursor)) {
381 $list->cursor = $list->id;
388 return new ArrayWrapper($lists);
392 * Get tags that other people put on this profile, in reverse-chron order
394 * @param (Profile|User) $auth_user Authorized user (used for privacy)
395 * @param int $offset Offset from latest
396 * @param int $limit Max number to get
397 * @param datetime $since_id max date
398 * @param datetime $max_id min date
400 * @return Profile_list resulting lists
403 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
405 $list = new Profile_list();
407 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
408 'from profile_tag join profile_list '.
409 'on (profile_tag.tagger = profile_list.tagger ' .
410 ' and profile_tag.tag = profile_list.tag) ' .
411 'where profile_tag.tagged = %d ',
415 if ($auth_user instanceof User || $auth_user instanceof Profile) {
416 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
417 'OR ( profile_list.tagger = %d AND ' .
418 'profile_list.private = true ) )',
421 $qry .= 'AND profile_list.private = 0 ';
425 $qry .= sprintf('AND (cursor > %d) ', $since_id);
429 $qry .= sprintf('AND (cursor < %d) ', $max_id);
432 $qry .= 'ORDER BY profile_tag.modified DESC ';
434 if ($offset >= 0 && !is_null($limit)) {
435 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
442 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
444 $tags = new Profile_list();
445 $tags->private = true;
446 $tags->tagger = $this->id;
449 $tags->whereAdd('id > '.$since_id);
453 $tags->whereAdd('id <= '.$max_id);
456 if($offset>=0 && !is_null($limit)) {
457 $tags->limit($offset, $limit);
460 $tags->orderBy('id DESC');
466 function hasLocalTags()
468 $tags = new Profile_tag();
470 $tags->joinAdd(array('tagger', 'user:id'));
471 $tags->whereAdd('tagged = '.$this->id);
472 $tags->whereAdd('tagger != '.$this->id);
477 return ($tags->N == 0) ? false : true;
480 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
482 $lists = new Profile_list();
483 $subs = new Profile_tag_subscription();
485 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
487 #@fixme: postgres (round(date_part('epoch', my_date)))
488 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
490 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
493 $lists->whereAdd('cursor > '.$since_id);
497 $lists->whereAdd('cursor <= '.$max_id);
500 if($offset>=0 && !is_null($limit)) {
501 $lists->limit($offset, $limit);
504 $lists->orderBy('"cursor" DESC');
511 * Request to join the given group.
512 * May throw exceptions on failure.
514 * @param User_group $group
515 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
517 function joinGroup(User_group $group)
520 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
521 $join = Group_join_queue::saveNew($this, $group);
523 if (Event::handle('StartJoinGroup', array($group, $this))) {
524 $join = Group_member::join($group->id, $this->id);
525 self::blow('profile:groups:%d', $this->id);
526 self::blow('group:member_ids:%d', $group->id);
527 self::blow('group:member_count:%d', $group->id);
528 Event::handle('EndJoinGroup', array($group, $this));
532 // Send any applicable notifications...
539 * Leave a group that this profile is a member of.
541 * @param User_group $group
543 function leaveGroup(User_group $group)
545 if (Event::handle('StartLeaveGroup', array($group, $this))) {
546 Group_member::leave($group->id, $this->id);
547 self::blow('profile:groups:%d', $this->id);
548 self::blow('group:member_ids:%d', $group->id);
549 self::blow('group:member_count:%d', $group->id);
550 Event::handle('EndLeaveGroup', array($group, $this));
554 function avatarUrl($size=AVATAR_PROFILE_SIZE)
556 return Avatar::urlByProfile($this, $size);
559 function getSubscribed($offset=0, $limit=null)
561 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
563 $profiles = Profile::listFind('id', $subs);
564 } catch (NoResultException $e) {
570 function getSubscribers($offset=0, $limit=null)
572 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
574 $profiles = Profile::listFind('id', $subs);
575 } catch (NoResultException $e) {
581 function getTaggedSubscribers($tag, $offset=0, $limit=null)
584 'SELECT profile.* ' .
585 'FROM profile JOIN subscription ' .
586 'ON profile.id = subscription.subscriber ' .
587 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
588 'AND profile_tag.tagger = subscription.subscribed) ' .
589 'WHERE subscription.subscribed = %d ' .
590 "AND profile_tag.tag = '%s' " .
591 'AND subscription.subscribed != subscription.subscriber ' .
592 'ORDER BY subscription.created DESC ';
595 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
598 $profile = new Profile();
600 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
605 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
608 'SELECT profile.* ' .
609 'FROM profile JOIN subscription ' .
610 'ON profile.id = subscription.subscribed ' .
611 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
612 'AND profile_tag.tagger = subscription.subscriber) ' .
613 'WHERE subscription.subscriber = %d ' .
614 "AND profile_tag.tag = '%s' " .
615 'AND subscription.subscribed != subscription.subscriber ' .
616 'ORDER BY subscription.created DESC ';
618 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
620 $profile = new Profile();
622 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
628 * Get pending subscribers, who have not yet been approved.
634 function getRequests($offset=0, $limit=null)
637 'SELECT profile.* ' .
638 'FROM profile JOIN subscription_queue '.
639 'ON profile.id = subscription_queue.subscriber ' .
640 'WHERE subscription_queue.subscribed = %d ' .
641 'ORDER BY subscription_queue.created DESC ';
643 if ($limit != null) {
644 if (common_config('db','type') == 'pgsql') {
645 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
647 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
651 $members = new Profile();
653 $members->query(sprintf($qry, $this->id));
657 function subscriptionCount()
659 $c = Cache::instance();
662 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
663 if (is_integer($cnt)) {
668 $sub = new Subscription();
669 $sub->subscriber = $this->id;
671 $cnt = (int) $sub->count('distinct subscribed');
673 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
676 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
682 function subscriberCount()
684 $c = Cache::instance();
686 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
687 if (is_integer($cnt)) {
692 $sub = new Subscription();
693 $sub->subscribed = $this->id;
694 $sub->whereAdd('subscriber != subscribed');
695 $cnt = (int) $sub->count('distinct subscriber');
698 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
705 * Is this profile subscribed to another profile?
707 * @param Profile $other
710 function isSubscribed($other)
712 return Subscription::exists($this, $other);
716 * Check if a pending subscription request is outstanding for this...
718 * @param Profile $other
721 function hasPendingSubscription($other)
723 return Subscription_queue::exists($this, $other);
727 * Are these two profiles subscribed to each other?
729 * @param Profile $other
732 function mutuallySubscribed($other)
734 return $this->isSubscribed($other) &&
735 $other->isSubscribed($this);
738 function hasFave($notice)
740 $fave = Fave::pkeyGet(array('user_id' => $this->id,
741 'notice_id' => $notice->id));
742 return ((is_null($fave)) ? false : true);
747 $c = Cache::instance();
749 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
750 if (is_integer($cnt)) {
756 $faves->user_id = $this->id;
757 $cnt = (int) $faves->count('notice_id');
760 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
766 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
768 return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
771 function noticeCount()
773 $c = Cache::instance();
776 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
777 if (is_integer($cnt)) {
782 $notices = new Notice();
783 $notices->profile_id = $this->id;
784 $cnt = (int) $notices->count('distinct id');
787 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
793 function blowFavesCache()
795 $cache = Cache::instance();
797 // Faves don't happen chronologically, so we need to blow
799 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
800 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
801 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
802 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
804 $this->blowFaveCount();
807 function blowSubscriberCount()
809 $c = Cache::instance();
811 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
815 function blowSubscriptionCount()
817 $c = Cache::instance();
819 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
823 function blowFaveCount()
825 $c = Cache::instance();
827 $c->delete(Cache::key('profile:fave_count:'.$this->id));
831 function blowNoticeCount()
833 $c = Cache::instance();
835 $c->delete(Cache::key('profile:notice_count:'.$this->id));
839 static function maxBio()
841 $biolimit = common_config('profile', 'biolimit');
842 // null => use global limit (distinct from 0!)
843 if (is_null($biolimit)) {
844 $biolimit = common_config('site', 'textlimit');
849 static function bioTooLong($bio)
851 $biolimit = self::maxBio();
852 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
855 function update($dataObject=false)
857 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
859 $local = $this->getUser();
860 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
861 $origuser = clone($local);
862 $local->nickname = $this->nickname;
863 $result = $local->updateKeys($origuser);
864 if ($result === false) {
865 common_log_db_error($local, 'UPDATE', __FILE__);
866 // TRANS: Server error thrown when user profile settings could not be updated.
867 throw new ServerException(_('Could not update user nickname.'));
870 // Clear the site owner, in case nickname changed
871 if ($local->hasRole(Profile_role::OWNER)) {
872 User::blow('user:site_owner');
874 } catch (NoSuchUserException $e) {
879 return parent::update($dataObject);
882 function delete($useWhere=false)
884 $this->_deleteNotices();
885 $this->_deleteSubscriptions();
886 $this->_deleteMessages();
887 $this->_deleteTags();
888 $this->_deleteBlocks();
889 Avatar::deleteFromProfile($this, true);
891 // Warning: delete() will run on the batch objects,
892 // not on individual objects.
893 $related = array('Reply',
896 Event::handle('ProfileDeleteRelated', array($this, &$related));
898 foreach ($related as $cls) {
900 $inst->profile_id = $this->id;
904 return parent::delete($useWhere);
907 function _deleteNotices()
909 $notice = new Notice();
910 $notice->profile_id = $this->id;
912 if ($notice->find()) {
913 while ($notice->fetch()) {
914 $other = clone($notice);
920 function _deleteSubscriptions()
922 $sub = new Subscription();
923 $sub->subscriber = $this->id;
927 while ($sub->fetch()) {
928 $other = Profile::getKV('id', $sub->subscribed);
932 if ($other->id == $this->id) {
935 Subscription::cancel($this, $other);
938 $subd = new Subscription();
939 $subd->subscribed = $this->id;
942 while ($subd->fetch()) {
943 $other = Profile::getKV('id', $subd->subscriber);
947 if ($other->id == $this->id) {
950 Subscription::cancel($other, $this);
953 $self = new Subscription();
955 $self->subscriber = $this->id;
956 $self->subscribed = $this->id;
961 function _deleteMessages()
963 $msg = new Message();
964 $msg->from_profile = $this->id;
967 $msg = new Message();
968 $msg->to_profile = $this->id;
972 function _deleteTags()
974 $tag = new Profile_tag();
975 $tag->tagged = $this->id;
979 function _deleteBlocks()
981 $block = new Profile_block();
982 $block->blocked = $this->id;
985 $block = new Group_block();
986 $block->blocked = $this->id;
990 // XXX: identical to Notice::getLocation.
992 public function getLocation()
996 if (!empty($this->location_id) && !empty($this->location_ns)) {
997 $location = Location::fromId($this->location_id, $this->location_ns);
1000 if (is_null($location)) { // no ID, or Location::fromId() failed
1001 if (!empty($this->lat) && !empty($this->lon)) {
1002 $location = Location::fromLatLon($this->lat, $this->lon);
1006 if (is_null($location)) { // still haven't found it!
1007 if (!empty($this->location)) {
1008 $location = Location::fromName($this->location);
1015 public function shareLocation()
1017 $cfg = common_config('location', 'share');
1019 if ($cfg == 'always') {
1021 } else if ($cfg == 'never') {
1024 $share = common_config('location', 'sharedefault');
1026 // Check if user has a personal setting for this
1027 $prefs = User_location_prefs::getKV('user_id', $this->id);
1029 if (!empty($prefs)) {
1030 $share = $prefs->share_location;
1038 function hasRole($name)
1041 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1042 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1044 $has_role = !empty($role);
1045 Event::handle('EndHasRole', array($this, $name, $has_role));
1050 function grantRole($name)
1052 if (Event::handle('StartGrantRole', array($this, $name))) {
1054 $role = new Profile_role();
1056 $role->profile_id = $this->id;
1057 $role->role = $name;
1058 $role->created = common_sql_now();
1060 $result = $role->insert();
1063 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1066 if ($name == 'owner') {
1067 User::blow('user:site_owner');
1070 Event::handle('EndGrantRole', array($this, $name));
1076 function revokeRole($name)
1078 if (Event::handle('StartRevokeRole', array($this, $name))) {
1080 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1084 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1085 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1086 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1089 $result = $role->delete();
1092 common_log_db_error($role, 'DELETE', __FILE__);
1093 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1094 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1095 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1098 if ($name == 'owner') {
1099 User::blow('user:site_owner');
1102 Event::handle('EndRevokeRole', array($this, $name));
1108 function isSandboxed()
1110 return $this->hasRole(Profile_role::SANDBOXED);
1113 function isSilenced()
1115 return $this->hasRole(Profile_role::SILENCED);
1120 $this->grantRole(Profile_role::SANDBOXED);
1123 function unsandbox()
1125 $this->revokeRole(Profile_role::SANDBOXED);
1130 $this->grantRole(Profile_role::SILENCED);
1131 if (common_config('notice', 'hidespam')) {
1132 $this->flushVisibility();
1136 function unsilence()
1138 $this->revokeRole(Profile_role::SILENCED);
1139 if (common_config('notice', 'hidespam')) {
1140 $this->flushVisibility();
1144 function flushVisibility()
1147 $stream = new ProfileNoticeStream($this, $this);
1148 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1149 foreach ($ids as $id) {
1150 self::blow('notice:in-scope-for:%d:null', $id);
1155 * Does this user have the right to do X?
1157 * With our role-based authorization, this is merely a lookup for whether the user
1158 * has a particular role. The implementation currently uses a switch statement
1159 * to determine if the user has the pre-defined role to exercise the right. Future
1160 * implementations may allow per-site roles, and different mappings of roles to rights.
1162 * @param $right string Name of the right, usually a constant in class Right
1163 * @return boolean whether the user has the right in question
1165 public function hasRight($right)
1169 if ($this->hasRole(Profile_role::DELETED)) {
1173 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1176 case Right::DELETEOTHERSNOTICE:
1177 case Right::MAKEGROUPADMIN:
1178 case Right::SANDBOXUSER:
1179 case Right::SILENCEUSER:
1180 case Right::DELETEUSER:
1181 case Right::DELETEGROUP:
1182 case Right::TRAINSPAM:
1183 case Right::REVIEWSPAM:
1184 $result = $this->hasRole(Profile_role::MODERATOR);
1186 case Right::CONFIGURESITE:
1187 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1189 case Right::GRANTROLE:
1190 case Right::REVOKEROLE:
1191 $result = $this->hasRole(Profile_role::OWNER);
1193 case Right::NEWNOTICE:
1194 case Right::NEWMESSAGE:
1195 case Right::SUBSCRIBE:
1196 case Right::CREATEGROUP:
1197 $result = !$this->isSilenced();
1199 case Right::PUBLICNOTICE:
1200 case Right::EMAILONREPLY:
1201 case Right::EMAILONSUBSCRIBE:
1202 case Right::EMAILONFAVE:
1203 $result = !$this->isSandboxed();
1205 case Right::WEBLOGIN:
1206 $result = !$this->isSilenced();
1209 $result = !$this->isSilenced();
1211 case Right::BACKUPACCOUNT:
1212 $result = common_config('profile', 'backup');
1214 case Right::RESTOREACCOUNT:
1215 $result = common_config('profile', 'restore');
1217 case Right::DELETEACCOUNT:
1218 $result = common_config('profile', 'delete');
1220 case Right::MOVEACCOUNT:
1221 $result = common_config('profile', 'move');
1231 // FIXME: Can't put Notice typing here due to ArrayWrapper
1232 public function hasRepeated($notice)
1234 // XXX: not really a pkey, but should work
1236 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1237 'repeat_of' => $notice->id));
1239 return !empty($notice);
1243 * Returns an XML string fragment with limited profile information
1244 * as an Atom <author> element.
1246 * Assumes that Atom has been previously set up as the base namespace.
1248 * @param Profile $cur the current authenticated user
1252 function asAtomAuthor($cur = null)
1254 $xs = new XMLStringer(true);
1256 $xs->elementStart('author');
1257 $xs->element('name', null, $this->nickname);
1258 $xs->element('uri', null, $this->getUri());
1261 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1262 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1263 $xs->element('statusnet:profile_info', $attrs, null);
1265 $xs->elementEnd('author');
1267 return $xs->getString();
1271 * Extra profile info for atom entries
1273 * Clients use some extra profile info in the atom stream.
1274 * This gives it to them.
1276 * @param User $cur Current user
1278 * @return array representation of <statusnet:profile_info> element or null
1281 function profileInfo($cur)
1283 $profileInfoAttr = array('local_id' => $this->id);
1286 // Whether the current user is a subscribed to this profile
1287 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1288 // Whether the current user is has blocked this profile
1289 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1292 return array('statusnet:profile_info', $profileInfoAttr, null);
1296 * Returns an XML string fragment with profile information as an
1297 * Activity Streams <activity:actor> element.
1299 * Assumes that 'activity' namespace has been previously defined.
1303 function asActivityActor()
1305 return $this->asActivityNoun('actor');
1309 * Returns an XML string fragment with profile information as an
1310 * Activity Streams noun object with the given element type.
1312 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1313 * previously defined.
1315 * @param string $element one of 'actor', 'subject', 'object', 'target'
1319 function asActivityNoun($element)
1321 $noun = ActivityObject::fromProfile($this);
1322 return $noun->asString('activity:' . $element);
1326 * Returns the profile's canonical url, not necessarily a uri/unique id
1328 * @return string $profileurl
1330 public function getUrl()
1332 if (empty($this->profileurl) ||
1333 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1334 throw new InvalidUrlException($this->profileurl);
1336 return $this->profileurl;
1340 * Returns the best URI for a profile. Plugins may override.
1342 * @return string $uri
1344 public function getUri()
1348 // give plugins a chance to set the URI
1349 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1351 // check for a local user first
1352 $user = User::getKV('id', $this->id);
1354 if (!empty($user)) {
1358 Event::handle('EndGetProfileUri', array($this, &$uri));
1365 * Returns an assumed acct: URI for a profile. Plugins are required.
1367 * @return string $uri
1369 public function getAcctUri()
1373 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1374 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1377 if ($acct === null) {
1378 throw new ProfileNoAcctUriException($this);
1384 function hasBlocked($other)
1386 $block = Profile_block::exists($this, $other);
1387 return !empty($block);
1390 function getAtomFeed()
1394 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1395 $user = User::getKV('id', $this->id);
1396 if (!empty($user)) {
1397 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1398 'format' => 'atom'));
1400 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1406 static function fromURI($uri)
1410 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1412 $user = User::getKV('uri', $uri);
1413 if (!empty($user)) {
1414 $profile = $user->getProfile();
1416 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1422 function canRead(Notice $notice)
1424 if ($notice->scope & Notice::SITE_SCOPE) {
1425 $user = $this->getUser();
1431 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1432 $replies = $notice->getReplies();
1434 if (!in_array($this->id, $replies)) {
1435 $groups = $notice->getGroups();
1439 foreach ($groups as $group) {
1440 if ($this->isMember($group)) {
1452 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1453 $author = $notice->getProfile();
1454 if (!Subscription::exists($this, $author)) {
1462 static function current()
1464 $user = common_current_user();
1468 $profile = $user->getProfile();
1474 * Magic function called at serialize() time.
1476 * We use this to drop a couple process-specific references
1477 * from DB_DataObject which can cause trouble in future
1480 * @return array of variable names to include in serialization.
1485 $vars = parent::__sleep();
1486 $skip = array('_user', '_avatars');
1487 return array_diff($vars, $skip);
1490 public function getProfile()