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 public function getAvatar($width, $height=null)
121 $width = (int) floor($width);
123 if (is_null($height)) {
128 return $this->_getAvatar($width);
129 } catch (Exception $e) {
133 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
134 $avatar = Avatar::pkeyGet(
136 'profile_id' => $this->id,
141 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
144 if (is_null($avatar)) {
145 // Obviously we can't find an avatar, so let's resize the original!
146 $avatar = Avatar::newSize($this, $width);
149 // cache the avatar for future use
150 $this->_fillAvatar($width, $avatar);
155 protected $_avatars = array();
157 // XXX: @Fix me gargargar
158 function _getAvatar($width)
160 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
161 // the previously used profile! Please shoot me now! --Zach
162 if (array_key_exists($width, $this->_avatars)) {
163 // Don't return cached avatar unless it's really for this profile
164 if ($this->_avatars[$width]->profile_id == $this->id) {
165 return $this->_avatars[$width];
169 throw new Exception('No cached avatar available for size ');
172 protected function _fillAvatar($width, $avatar)
174 // This avoids storing null values, a problem report in issue #3478
175 if (!empty($avatar)) {
176 $this->_avatars[$width] = $avatar;
180 function setOriginal($filename)
182 $imagefile = new ImageFile($this->id, Avatar::path($filename));
184 $avatar = new Avatar();
185 $avatar->profile_id = $this->id;
186 $avatar->width = $imagefile->width;
187 $avatar->height = $imagefile->height;
188 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
189 $avatar->filename = $filename;
190 $avatar->original = true;
191 $avatar->url = Avatar::url($filename);
192 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
194 // XXX: start a transaction here
195 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
196 // If we can't delete the old avatars, let's abort right here.
197 @unlink(Avatar::path($filename));
201 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
202 // We don't do a scaled one if original is our scaled size
203 if (!($avatar->width == $size && $avatar->height == $size)) {
205 Avatar::newSize($this, $size);
206 } catch (Exception $e) {
207 // should we abort the generation and live without smaller avatars?
216 * Gets either the full name (if filled) or the nickname.
220 function getBestName()
222 return ($this->fullname) ? $this->fullname : $this->nickname;
226 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
227 * if no fullname is provided.
231 function getFancyName()
233 if ($this->fullname) {
234 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
235 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
237 return $this->nickname;
242 * Get the most recent notice posted by this user, if any.
244 * @return mixed Notice or null
246 function getCurrentNotice()
248 $notice = $this->getNotices(0, 1);
250 if ($notice->fetch()) {
251 if ($notice instanceof ArrayWrapper) {
252 // hack for things trying to work with single notices
253 return $notice->_items[0];
261 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
263 $stream = new TaggedProfileNoticeStream($this, $tag);
265 return $stream->getNotices($offset, $limit, $since_id, $max_id);
268 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
270 $stream = new ProfileNoticeStream($this);
272 return $stream->getNotices($offset, $limit, $since_id, $max_id);
275 function isMember($group)
277 $groups = $this->getGroups(0, null);
278 $gs = $groups->fetchAll();
279 foreach ($gs as $g) {
280 if ($group->id == $g->id) {
287 function isAdmin($group)
289 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
290 'group_id' => $group->id));
291 return (!empty($gm) && $gm->is_admin);
294 function isPendingMember($group)
296 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
297 'group_id' => $group->id));
298 return !empty($request);
301 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
305 $keypart = sprintf('profile:groups:%d', $this->id);
307 $idstring = self::cacheGet($keypart);
309 if ($idstring !== false) {
310 $ids = explode(',', $idstring);
312 $gm = new Group_member();
314 $gm->profile_id = $this->id;
317 while ($gm->fetch()) {
318 $ids[] = $gm->group_id;
322 self::cacheSet($keypart, implode(',', $ids));
325 if (!is_null($offset) && !is_null($limit)) {
326 $ids = array_slice($ids, $offset, $limit);
329 return User_group::multiGet('id', $ids);
332 function isTagged($peopletag)
334 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
335 'tagged' => $this->id,
336 'tag' => $peopletag->tag));
340 function canTag($tagged)
342 if (empty($tagged)) {
346 if ($tagged->id == $this->id) {
350 $all = common_config('peopletag', 'allow_tagging', 'all');
351 $local = common_config('peopletag', 'allow_tagging', 'local');
352 $remote = common_config('peopletag', 'allow_tagging', 'remote');
353 $subs = common_config('peopletag', 'allow_tagging', 'subs');
359 $tagged_user = $tagged->getUser();
360 if (!empty($tagged_user)) {
365 return (Subscription::exists($this, $tagged) ||
366 Subscription::exists($tagged, $this));
367 } else if ($remote) {
373 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
377 $keypart = sprintf('profile:lists:%d', $this->id);
379 $idstr = self::cacheGet($keypart);
381 if ($idstr !== false) {
382 $ids = explode(',', $idstr);
384 $list = new Profile_list();
386 $list->selectAdd('id');
387 $list->tagger = $this->id;
388 $list->selectAdd('id as "cursor"');
391 $list->whereAdd('id > '.$since_id);
395 $list->whereAdd('id <= '.$max_id);
398 if($offset>=0 && !is_null($limit)) {
399 $list->limit($offset, $limit);
402 $list->orderBy('id DESC');
405 while ($list->fetch()) {
410 self::cacheSet($keypart, implode(',', $ids));
413 $showPrivate = (($auth_user instanceof User ||
414 $auth_user instanceof Profile) &&
415 $auth_user->id === $this->id);
419 foreach ($ids as $id) {
420 $list = Profile_list::getKV('id', $id);
422 ($showPrivate || !$list->private)) {
424 if (!isset($list->cursor)) {
425 $list->cursor = $list->id;
432 return new ArrayWrapper($lists);
436 * Get tags that other people put on this profile, in reverse-chron order
438 * @param (Profile|User) $auth_user Authorized user (used for privacy)
439 * @param int $offset Offset from latest
440 * @param int $limit Max number to get
441 * @param datetime $since_id max date
442 * @param datetime $max_id min date
444 * @return Profile_list resulting lists
447 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
449 $list = new Profile_list();
451 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
452 'from profile_tag join profile_list '.
453 'on (profile_tag.tagger = profile_list.tagger ' .
454 ' and profile_tag.tag = profile_list.tag) ' .
455 'where profile_tag.tagged = %d ',
459 if ($auth_user instanceof User || $auth_user instanceof Profile) {
460 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
461 'OR ( profile_list.tagger = %d AND ' .
462 'profile_list.private = true ) )',
465 $qry .= 'AND profile_list.private = 0 ';
469 $qry .= sprintf('AND (cursor > %d) ', $since_id);
473 $qry .= sprintf('AND (cursor < %d) ', $max_id);
476 $qry .= 'ORDER BY profile_tag.modified DESC ';
478 if ($offset >= 0 && !is_null($limit)) {
479 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
486 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
488 $tags = new Profile_list();
489 $tags->private = true;
490 $tags->tagger = $this->id;
493 $tags->whereAdd('id > '.$since_id);
497 $tags->whereAdd('id <= '.$max_id);
500 if($offset>=0 && !is_null($limit)) {
501 $tags->limit($offset, $limit);
504 $tags->orderBy('id DESC');
510 function hasLocalTags()
512 $tags = new Profile_tag();
514 $tags->joinAdd(array('tagger', 'user:id'));
515 $tags->whereAdd('tagged = '.$this->id);
516 $tags->whereAdd('tagger != '.$this->id);
521 return ($tags->N == 0) ? false : true;
524 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
526 $lists = new Profile_list();
527 $subs = new Profile_tag_subscription();
529 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
531 #@fixme: postgres (round(date_part('epoch', my_date)))
532 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
534 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
537 $lists->whereAdd('cursor > '.$since_id);
541 $lists->whereAdd('cursor <= '.$max_id);
544 if($offset>=0 && !is_null($limit)) {
545 $lists->limit($offset, $limit);
548 $lists->orderBy('"cursor" DESC');
555 * Request to join the given group.
556 * May throw exceptions on failure.
558 * @param User_group $group
559 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
561 function joinGroup(User_group $group)
564 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
565 $join = Group_join_queue::saveNew($this, $group);
567 if (Event::handle('StartJoinGroup', array($group, $this))) {
568 $join = Group_member::join($group->id, $this->id);
569 self::blow('profile:groups:%d', $this->id);
570 self::blow('group:member_ids:%d', $group->id);
571 self::blow('group:member_count:%d', $group->id);
572 Event::handle('EndJoinGroup', array($group, $this));
576 // Send any applicable notifications...
583 * Leave a group that this profile is a member of.
585 * @param User_group $group
587 function leaveGroup(User_group $group)
589 if (Event::handle('StartLeaveGroup', array($group, $this))) {
590 Group_member::leave($group->id, $this->id);
591 self::blow('profile:groups:%d', $this->id);
592 self::blow('group:member_ids:%d', $group->id);
593 self::blow('group:member_count:%d', $group->id);
594 Event::handle('EndLeaveGroup', array($group, $this));
598 function avatarUrl($size=AVATAR_PROFILE_SIZE)
600 $size = floor($size);
602 $avatar = $this->getAvatar($size);
603 return $avatar->displayUrl();
604 } catch (Exception $e) {
605 return Avatar::defaultImage($size);
609 function getSubscribed($offset=0, $limit=null)
611 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
612 $profiles = Profile::listFind('id', $subs);
616 function getSubscribers($offset=0, $limit=null)
618 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
619 $profiles = Profile::listFind('id', $subs);
623 function getTaggedSubscribers($tag)
626 'SELECT profile.* ' .
627 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
628 'ON profile.id = subscription.subscriber ' .
629 'AND profile.id = profile_tag.tagged ' .
630 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
631 'WHERE subscription.subscribed = %d ' .
632 'AND subscription.subscribed != subscription.subscriber ' .
633 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
634 'AND profile_list.private = false ' .
635 'ORDER BY subscription.created DESC';
637 $profile = new Profile();
640 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
642 while ($profile->fetch()) {
643 $tagged[] = clone($profile);
649 * Get pending subscribers, who have not yet been approved.
655 function getRequests($offset=0, $limit=null)
658 'SELECT profile.* ' .
659 'FROM profile JOIN subscription_queue '.
660 'ON profile.id = subscription_queue.subscriber ' .
661 'WHERE subscription_queue.subscribed = %d ' .
662 'ORDER BY subscription_queue.created DESC ';
664 if ($limit != null) {
665 if (common_config('db','type') == 'pgsql') {
666 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
668 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
672 $members = new Profile();
674 $members->query(sprintf($qry, $this->id));
678 function subscriptionCount()
680 $c = Cache::instance();
683 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
684 if (is_integer($cnt)) {
689 $sub = new Subscription();
690 $sub->subscriber = $this->id;
692 $cnt = (int) $sub->count('distinct subscribed');
694 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
697 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
703 function subscriberCount()
705 $c = Cache::instance();
707 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
708 if (is_integer($cnt)) {
713 $sub = new Subscription();
714 $sub->subscribed = $this->id;
715 $sub->whereAdd('subscriber != subscribed');
716 $cnt = (int) $sub->count('distinct subscriber');
719 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
726 * Is this profile subscribed to another profile?
728 * @param Profile $other
731 function isSubscribed($other)
733 return Subscription::exists($this, $other);
737 * Check if a pending subscription request is outstanding for this...
739 * @param Profile $other
742 function hasPendingSubscription($other)
744 return Subscription_queue::exists($this, $other);
748 * Are these two profiles subscribed to each other?
750 * @param Profile $other
753 function mutuallySubscribed($other)
755 return $this->isSubscribed($other) &&
756 $other->isSubscribed($this);
759 function hasFave($notice)
761 $fave = Fave::pkeyGet(array('user_id' => $this->id,
762 'notice_id' => $notice->id));
763 return ((is_null($fave)) ? false : true);
768 $c = Cache::instance();
770 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
771 if (is_integer($cnt)) {
777 $faves->user_id = $this->id;
778 $cnt = (int) $faves->count('notice_id');
781 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
787 function noticeCount()
789 $c = Cache::instance();
792 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
793 if (is_integer($cnt)) {
798 $notices = new Notice();
799 $notices->profile_id = $this->id;
800 $cnt = (int) $notices->count('distinct id');
803 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
809 function blowFavesCache()
811 $cache = Cache::instance();
813 // Faves don't happen chronologically, so we need to blow
815 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
816 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
817 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
818 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
820 $this->blowFaveCount();
823 function blowSubscriberCount()
825 $c = Cache::instance();
827 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
831 function blowSubscriptionCount()
833 $c = Cache::instance();
835 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
839 function blowFaveCount()
841 $c = Cache::instance();
843 $c->delete(Cache::key('profile:fave_count:'.$this->id));
847 function blowNoticeCount()
849 $c = Cache::instance();
851 $c->delete(Cache::key('profile:notice_count:'.$this->id));
855 static function maxBio()
857 $biolimit = common_config('profile', 'biolimit');
858 // null => use global limit (distinct from 0!)
859 if (is_null($biolimit)) {
860 $biolimit = common_config('site', 'textlimit');
865 static function bioTooLong($bio)
867 $biolimit = self::maxBio();
868 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
873 $this->_deleteNotices();
874 $this->_deleteSubscriptions();
875 $this->_deleteMessages();
876 $this->_deleteTags();
877 $this->_deleteBlocks();
878 Avatar::deleteFromProfile($this, true);
880 // Warning: delete() will run on the batch objects,
881 // not on individual objects.
882 $related = array('Reply',
885 Event::handle('ProfileDeleteRelated', array($this, &$related));
887 foreach ($related as $cls) {
889 $inst->profile_id = $this->id;
896 function _deleteNotices()
898 $notice = new Notice();
899 $notice->profile_id = $this->id;
901 if ($notice->find()) {
902 while ($notice->fetch()) {
903 $other = clone($notice);
909 function _deleteSubscriptions()
911 $sub = new Subscription();
912 $sub->subscriber = $this->id;
916 while ($sub->fetch()) {
917 $other = Profile::getKV('id', $sub->subscribed);
921 if ($other->id == $this->id) {
924 Subscription::cancel($this, $other);
927 $subd = new Subscription();
928 $subd->subscribed = $this->id;
931 while ($subd->fetch()) {
932 $other = Profile::getKV('id', $subd->subscriber);
936 if ($other->id == $this->id) {
939 Subscription::cancel($other, $this);
942 $self = new Subscription();
944 $self->subscriber = $this->id;
945 $self->subscribed = $this->id;
950 function _deleteMessages()
952 $msg = new Message();
953 $msg->from_profile = $this->id;
956 $msg = new Message();
957 $msg->to_profile = $this->id;
961 function _deleteTags()
963 $tag = new Profile_tag();
964 $tag->tagged = $this->id;
968 function _deleteBlocks()
970 $block = new Profile_block();
971 $block->blocked = $this->id;
974 $block = new Group_block();
975 $block->blocked = $this->id;
979 // XXX: identical to Notice::getLocation.
981 function getLocation()
985 if (!empty($this->location_id) && !empty($this->location_ns)) {
986 $location = Location::fromId($this->location_id, $this->location_ns);
989 if (is_null($location)) { // no ID, or Location::fromId() failed
990 if (!empty($this->lat) && !empty($this->lon)) {
991 $location = Location::fromLatLon($this->lat, $this->lon);
995 if (is_null($location)) { // still haven't found it!
996 if (!empty($this->location)) {
997 $location = Location::fromName($this->location);
1004 function hasRole($name)
1007 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1008 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1010 $has_role = !empty($role);
1011 Event::handle('EndHasRole', array($this, $name, $has_role));
1016 function grantRole($name)
1018 if (Event::handle('StartGrantRole', array($this, $name))) {
1020 $role = new Profile_role();
1022 $role->profile_id = $this->id;
1023 $role->role = $name;
1024 $role->created = common_sql_now();
1026 $result = $role->insert();
1029 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1032 if ($name == 'owner') {
1033 User::blow('user:site_owner');
1036 Event::handle('EndGrantRole', array($this, $name));
1042 function revokeRole($name)
1044 if (Event::handle('StartRevokeRole', array($this, $name))) {
1046 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1050 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1051 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1052 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1055 $result = $role->delete();
1058 common_log_db_error($role, 'DELETE', __FILE__);
1059 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1060 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1061 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1064 if ($name == 'owner') {
1065 User::blow('user:site_owner');
1068 Event::handle('EndRevokeRole', array($this, $name));
1074 function isSandboxed()
1076 return $this->hasRole(Profile_role::SANDBOXED);
1079 function isSilenced()
1081 return $this->hasRole(Profile_role::SILENCED);
1086 $this->grantRole(Profile_role::SANDBOXED);
1089 function unsandbox()
1091 $this->revokeRole(Profile_role::SANDBOXED);
1096 $this->grantRole(Profile_role::SILENCED);
1097 if (common_config('notice', 'hidespam')) {
1098 $this->flushVisibility();
1102 function unsilence()
1104 $this->revokeRole(Profile_role::SILENCED);
1105 if (common_config('notice', 'hidespam')) {
1106 $this->flushVisibility();
1110 function flushVisibility()
1113 $stream = new ProfileNoticeStream($this, $this);
1114 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1115 foreach ($ids as $id) {
1116 self::blow('notice:in-scope-for:%d:null', $id);
1121 * Does this user have the right to do X?
1123 * With our role-based authorization, this is merely a lookup for whether the user
1124 * has a particular role. The implementation currently uses a switch statement
1125 * to determine if the user has the pre-defined role to exercise the right. Future
1126 * implementations may allow per-site roles, and different mappings of roles to rights.
1128 * @param $right string Name of the right, usually a constant in class Right
1129 * @return boolean whether the user has the right in question
1131 function hasRight($right)
1135 if ($this->hasRole(Profile_role::DELETED)) {
1139 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1142 case Right::DELETEOTHERSNOTICE:
1143 case Right::MAKEGROUPADMIN:
1144 case Right::SANDBOXUSER:
1145 case Right::SILENCEUSER:
1146 case Right::DELETEUSER:
1147 case Right::DELETEGROUP:
1148 case Right::TRAINSPAM:
1149 case Right::REVIEWSPAM:
1150 $result = $this->hasRole(Profile_role::MODERATOR);
1152 case Right::CONFIGURESITE:
1153 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1155 case Right::GRANTROLE:
1156 case Right::REVOKEROLE:
1157 $result = $this->hasRole(Profile_role::OWNER);
1159 case Right::NEWNOTICE:
1160 case Right::NEWMESSAGE:
1161 case Right::SUBSCRIBE:
1162 case Right::CREATEGROUP:
1163 $result = !$this->isSilenced();
1165 case Right::PUBLICNOTICE:
1166 case Right::EMAILONREPLY:
1167 case Right::EMAILONSUBSCRIBE:
1168 case Right::EMAILONFAVE:
1169 $result = !$this->isSandboxed();
1171 case Right::WEBLOGIN:
1172 $result = !$this->isSilenced();
1175 $result = !$this->isSilenced();
1177 case Right::BACKUPACCOUNT:
1178 $result = common_config('profile', 'backup');
1180 case Right::RESTOREACCOUNT:
1181 $result = common_config('profile', 'restore');
1183 case Right::DELETEACCOUNT:
1184 $result = common_config('profile', 'delete');
1186 case Right::MOVEACCOUNT:
1187 $result = common_config('profile', 'move');
1197 function hasRepeated($notice_id)
1199 // XXX: not really a pkey, but should work
1201 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1202 'repeat_of' => $notice_id));
1204 return !empty($notice);
1208 * Returns an XML string fragment with limited profile information
1209 * as an Atom <author> element.
1211 * Assumes that Atom has been previously set up as the base namespace.
1213 * @param Profile $cur the current authenticated user
1217 function asAtomAuthor($cur = null)
1219 $xs = new XMLStringer(true);
1221 $xs->elementStart('author');
1222 $xs->element('name', null, $this->nickname);
1223 $xs->element('uri', null, $this->getUri());
1226 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1227 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1228 $xs->element('statusnet:profile_info', $attrs, null);
1230 $xs->elementEnd('author');
1232 return $xs->getString();
1236 * Extra profile info for atom entries
1238 * Clients use some extra profile info in the atom stream.
1239 * This gives it to them.
1241 * @param User $cur Current user
1243 * @return array representation of <statusnet:profile_info> element or null
1246 function profileInfo($cur)
1248 $profileInfoAttr = array('local_id' => $this->id);
1251 // Whether the current user is a subscribed to this profile
1252 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1253 // Whether the current user is has blocked this profile
1254 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1257 return array('statusnet:profile_info', $profileInfoAttr, null);
1261 * Returns an XML string fragment with profile information as an
1262 * Activity Streams <activity:actor> element.
1264 * Assumes that 'activity' namespace has been previously defined.
1268 function asActivityActor()
1270 return $this->asActivityNoun('actor');
1274 * Returns an XML string fragment with profile information as an
1275 * Activity Streams noun object with the given element type.
1277 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1278 * previously defined.
1280 * @param string $element one of 'actor', 'subject', 'object', 'target'
1284 function asActivityNoun($element)
1286 $noun = ActivityObject::fromProfile($this);
1287 return $noun->asString('activity:' . $element);
1291 * Returns the profile's canonical url, not necessarily a uri/unique id
1293 * @return string $profileurl
1295 public function getUrl()
1297 if (empty($this->profileurl) ||
1298 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1299 throw new InvalidUrlException($this->profileurl);
1301 return $this->profileurl;
1305 * Returns the best URI for a profile. Plugins may override.
1307 * @return string $uri
1309 public function getUri()
1313 // give plugins a chance to set the URI
1314 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1316 // check for a local user first
1317 $user = User::getKV('id', $this->id);
1319 if (!empty($user)) {
1323 Event::handle('EndGetProfileUri', array($this, &$uri));
1329 function hasBlocked($other)
1331 $block = Profile_block::exists($this, $other);
1332 return !empty($block);
1335 function getAtomFeed()
1339 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1340 $user = User::getKV('id', $this->id);
1341 if (!empty($user)) {
1342 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1343 'format' => 'atom'));
1345 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1351 static function fromURI($uri)
1355 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1356 // Get a local user or remote (OMB 0.1) profile
1357 $user = User::getKV('uri', $uri);
1358 if (!empty($user)) {
1359 $profile = $user->getProfile();
1361 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1367 function canRead(Notice $notice)
1369 if ($notice->scope & Notice::SITE_SCOPE) {
1370 $user = $this->getUser();
1376 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1377 $replies = $notice->getReplies();
1379 if (!in_array($this->id, $replies)) {
1380 $groups = $notice->getGroups();
1384 foreach ($groups as $group) {
1385 if ($this->isMember($group)) {
1397 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1398 $author = $notice->getProfile();
1399 if (!Subscription::exists($this, $author)) {
1407 static function current()
1409 $user = common_current_user();
1413 $profile = $user->getProfile();
1419 * Magic function called at serialize() time.
1421 * We use this to drop a couple process-specific references
1422 * from DB_DataObject which can cause trouble in future
1425 * @return array of variable names to include in serialization.
1430 $vars = parent::__sleep();
1431 $skip = array('_user', '_avatars');
1432 return array_diff($vars, $skip);
1435 static function fillAvatars(&$profiles, $width)
1438 foreach ($profiles as $profile) {
1439 if (!empty($profile)) {
1440 $ids[] = $profile->id;
1444 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1445 'height' => $width));
1447 foreach ($profiles as $profile) {
1448 if (!empty($profile)) { // ???
1449 $profile->_fillAvatar($width, $avatars[$profile->id]);
1454 // Can't seem to find how to fix this.
1456 function getProfile()