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) {
121 public function getAvatar($width, $height=null)
123 if (is_null($height)) {
127 $avatar = $this->_getAvatar($width);
129 if (empty($avatar)) {
130 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
131 $avatar = Avatar::pkeyGet(
133 'profile_id' => $this->id,
138 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
141 // if-empty within an if-empty? Let's find a prettier solution...
142 if (empty($avatar)) {
143 // Obviously we can't find an avatar, so let's resize the original!
145 $avatar = Avatar::newSize($this, $width);
146 } catch (Exception $e) {
147 // Could not generate a resized avatar. How do we handle it?
151 // cache the avatar for future use
152 $this->_fillAvatar($width, $avatar);
158 // XXX: @Fix me gargargar
159 function _getAvatar($width)
161 if (empty($this->_avatars)) {
162 $this->_avatars = array();
165 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
166 // the previously used profile! Please shoot me now! --Zach
167 if (array_key_exists($width, $this->_avatars)) {
168 // Don't return cached avatar unless it's really for this profile
169 if ($this->_avatars[$width]->profile_id == $this->id) {
170 return $this->_avatars[$width];
177 protected function _fillAvatar($width, $avatar)
179 // This avoids storing null values, a problem report in issue #3478
180 if (!empty($avatar)) {
181 $this->_avatars[$width] = $avatar;
185 // For backwards compatibility only!
186 public function getOriginalAvatar()
189 return Avatar::getOriginal($this);
190 } catch (Exception $e) {
195 function setOriginal($filename)
197 $imagefile = new ImageFile($this->id, Avatar::path($filename));
199 $avatar = new Avatar();
200 $avatar->profile_id = $this->id;
201 $avatar->width = $imagefile->width;
202 $avatar->height = $imagefile->height;
203 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
204 $avatar->filename = $filename;
205 $avatar->original = true;
206 $avatar->url = Avatar::url($filename);
207 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
209 // XXX: start a transaction here
211 if (!$this->delete_avatars() || !$avatar->insert()) {
212 @unlink(Avatar::path($filename));
216 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
217 // We don't do a scaled one if original is our scaled size
218 if (!($avatar->width == $size && $avatar->height == $size)) {
220 Avatar::newSize($this, $size);
221 } catch (Exception $e) {
222 // should we abort the generation and live without smaller avatars?
231 * Delete attached avatars for this user from the database and filesystem.
232 * This should be used instead of a batch delete() to ensure that files
233 * get removed correctly.
235 * @param boolean $original true to delete only the original-size file
238 function delete_avatars($original=true)
240 $avatar = new Avatar();
241 $avatar->profile_id = $this->id;
243 while ($avatar->fetch()) {
244 if ($avatar->original) {
245 if ($original == false) {
255 * Gets either the full name (if filled) or the nickname.
259 function getBestName()
261 return ($this->fullname) ? $this->fullname : $this->nickname;
265 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
266 * if no fullname is provided.
270 function getFancyName()
272 if ($this->fullname) {
273 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
274 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
276 return $this->nickname;
281 * Get the most recent notice posted by this user, if any.
283 * @return mixed Notice or null
285 function getCurrentNotice()
287 $notice = $this->getNotices(0, 1);
289 if ($notice->fetch()) {
290 if ($notice instanceof ArrayWrapper) {
291 // hack for things trying to work with single notices
292 return $notice->_items[0];
300 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
302 $stream = new TaggedProfileNoticeStream($this, $tag);
304 return $stream->getNotices($offset, $limit, $since_id, $max_id);
307 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
309 $stream = new ProfileNoticeStream($this);
311 return $stream->getNotices($offset, $limit, $since_id, $max_id);
314 function isMember($group)
316 $groups = $this->getGroups(0, null);
317 $gs = $groups->fetchAll();
318 foreach ($gs as $g) {
319 if ($group->id == $g->id) {
326 function isAdmin($group)
328 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
329 'group_id' => $group->id));
330 return (!empty($gm) && $gm->is_admin);
333 function isPendingMember($group)
335 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
336 'group_id' => $group->id));
337 return !empty($request);
340 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
344 $keypart = sprintf('profile:groups:%d', $this->id);
346 $idstring = self::cacheGet($keypart);
348 if ($idstring !== false) {
349 $ids = explode(',', $idstring);
351 $gm = new Group_member();
353 $gm->profile_id = $this->id;
356 while ($gm->fetch()) {
357 $ids[] = $gm->group_id;
361 self::cacheSet($keypart, implode(',', $ids));
364 if (!is_null($offset) && !is_null($limit)) {
365 $ids = array_slice($ids, $offset, $limit);
368 return User_group::multiGet('id', $ids);
371 function isTagged($peopletag)
373 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
374 'tagged' => $this->id,
375 'tag' => $peopletag->tag));
379 function canTag($tagged)
381 if (empty($tagged)) {
385 if ($tagged->id == $this->id) {
389 $all = common_config('peopletag', 'allow_tagging', 'all');
390 $local = common_config('peopletag', 'allow_tagging', 'local');
391 $remote = common_config('peopletag', 'allow_tagging', 'remote');
392 $subs = common_config('peopletag', 'allow_tagging', 'subs');
398 $tagged_user = $tagged->getUser();
399 if (!empty($tagged_user)) {
404 return (Subscription::exists($this, $tagged) ||
405 Subscription::exists($tagged, $this));
406 } else if ($remote) {
412 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
416 $keypart = sprintf('profile:lists:%d', $this->id);
418 $idstr = self::cacheGet($keypart);
420 if ($idstr !== false) {
421 $ids = explode(',', $idstr);
423 $list = new Profile_list();
425 $list->selectAdd('id');
426 $list->tagger = $this->id;
427 $list->selectAdd('id as "cursor"');
430 $list->whereAdd('id > '.$since_id);
434 $list->whereAdd('id <= '.$max_id);
437 if($offset>=0 && !is_null($limit)) {
438 $list->limit($offset, $limit);
441 $list->orderBy('id DESC');
444 while ($list->fetch()) {
449 self::cacheSet($keypart, implode(',', $ids));
452 $showPrivate = (($auth_user instanceof User ||
453 $auth_user instanceof Profile) &&
454 $auth_user->id === $this->id);
458 foreach ($ids as $id) {
459 $list = Profile_list::getKV('id', $id);
461 ($showPrivate || !$list->private)) {
463 if (!isset($list->cursor)) {
464 $list->cursor = $list->id;
471 return new ArrayWrapper($lists);
475 * Get tags that other people put on this profile, in reverse-chron order
477 * @param (Profile|User) $auth_user Authorized user (used for privacy)
478 * @param int $offset Offset from latest
479 * @param int $limit Max number to get
480 * @param datetime $since_id max date
481 * @param datetime $max_id min date
483 * @return Profile_list resulting lists
486 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
488 $list = new Profile_list();
490 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
491 'from profile_tag join profile_list '.
492 'on (profile_tag.tagger = profile_list.tagger ' .
493 ' and profile_tag.tag = profile_list.tag) ' .
494 'where profile_tag.tagged = %d ',
498 if ($auth_user instanceof User || $auth_user instanceof Profile) {
499 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
500 'OR ( profile_list.tagger = %d AND ' .
501 'profile_list.private = true ) )',
504 $qry .= 'AND profile_list.private = 0 ';
508 $qry .= sprintf('AND (cursor > %d) ', $since_id);
512 $qry .= sprintf('AND (cursor < %d) ', $max_id);
515 $qry .= 'ORDER BY profile_tag.modified DESC ';
517 if ($offset >= 0 && !is_null($limit)) {
518 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
525 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
527 $tags = new Profile_list();
528 $tags->private = true;
529 $tags->tagger = $this->id;
532 $tags->whereAdd('id > '.$since_id);
536 $tags->whereAdd('id <= '.$max_id);
539 if($offset>=0 && !is_null($limit)) {
540 $tags->limit($offset, $limit);
543 $tags->orderBy('id DESC');
549 function hasLocalTags()
551 $tags = new Profile_tag();
553 $tags->joinAdd(array('tagger', 'user:id'));
554 $tags->whereAdd('tagged = '.$this->id);
555 $tags->whereAdd('tagger != '.$this->id);
560 return ($tags->N == 0) ? false : true;
563 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
565 $lists = new Profile_list();
566 $subs = new Profile_tag_subscription();
568 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
570 #@fixme: postgres (round(date_part('epoch', my_date)))
571 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
573 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
576 $lists->whereAdd('cursor > '.$since_id);
580 $lists->whereAdd('cursor <= '.$max_id);
583 if($offset>=0 && !is_null($limit)) {
584 $lists->limit($offset, $limit);
587 $lists->orderBy('"cursor" DESC');
594 * Request to join the given group.
595 * May throw exceptions on failure.
597 * @param User_group $group
598 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
600 function joinGroup(User_group $group)
603 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
604 $join = Group_join_queue::saveNew($this, $group);
606 if (Event::handle('StartJoinGroup', array($group, $this))) {
607 $join = Group_member::join($group->id, $this->id);
608 self::blow('profile:groups:%d', $this->id);
609 self::blow('group:member_ids:%d', $group->id);
610 self::blow('group:member_count:%d', $group->id);
611 Event::handle('EndJoinGroup', array($group, $this));
615 // Send any applicable notifications...
622 * Leave a group that this profile is a member of.
624 * @param User_group $group
626 function leaveGroup(User_group $group)
628 if (Event::handle('StartLeaveGroup', array($group, $this))) {
629 Group_member::leave($group->id, $this->id);
630 self::blow('profile:groups:%d', $this->id);
631 self::blow('group:member_ids:%d', $group->id);
632 self::blow('group:member_count:%d', $group->id);
633 Event::handle('EndLeaveGroup', array($group, $this));
637 function avatarUrl($size=AVATAR_PROFILE_SIZE)
639 $avatar = $this->getAvatar($size);
641 return $avatar->displayUrl();
643 return Avatar::defaultImage($size);
647 function getSubscribed($offset=0, $limit=null)
649 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
650 $profiles = Profile::listFind('id', $subs);
654 function getSubscribers($offset=0, $limit=null)
656 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
657 $profiles = Profile::listFind('id', $subs);
661 function getTaggedSubscribers($tag)
664 'SELECT profile.* ' .
665 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
666 'ON profile.id = subscription.subscriber ' .
667 'AND profile.id = profile_tag.tagged ' .
668 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
669 'WHERE subscription.subscribed = %d ' .
670 'AND subscription.subscribed != subscription.subscriber ' .
671 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
672 'AND profile_list.private = false ' .
673 'ORDER BY subscription.created DESC';
675 $profile = new Profile();
678 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
680 while ($profile->fetch()) {
681 $tagged[] = clone($profile);
687 * Get pending subscribers, who have not yet been approved.
693 function getRequests($offset=0, $limit=null)
696 'SELECT profile.* ' .
697 'FROM profile JOIN subscription_queue '.
698 'ON profile.id = subscription_queue.subscriber ' .
699 'WHERE subscription_queue.subscribed = %d ' .
700 'ORDER BY subscription_queue.created DESC ';
702 if ($limit != null) {
703 if (common_config('db','type') == 'pgsql') {
704 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
706 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
710 $members = new Profile();
712 $members->query(sprintf($qry, $this->id));
716 function subscriptionCount()
718 $c = Cache::instance();
721 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
722 if (is_integer($cnt)) {
727 $sub = new Subscription();
728 $sub->subscriber = $this->id;
730 $cnt = (int) $sub->count('distinct subscribed');
732 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
735 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
741 function subscriberCount()
743 $c = Cache::instance();
745 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
746 if (is_integer($cnt)) {
751 $sub = new Subscription();
752 $sub->subscribed = $this->id;
753 $sub->whereAdd('subscriber != subscribed');
754 $cnt = (int) $sub->count('distinct subscriber');
757 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
764 * Is this profile subscribed to another profile?
766 * @param Profile $other
769 function isSubscribed($other)
771 return Subscription::exists($this, $other);
775 * Check if a pending subscription request is outstanding for this...
777 * @param Profile $other
780 function hasPendingSubscription($other)
782 return Subscription_queue::exists($this, $other);
786 * Are these two profiles subscribed to each other?
788 * @param Profile $other
791 function mutuallySubscribed($other)
793 return $this->isSubscribed($other) &&
794 $other->isSubscribed($this);
797 function hasFave($notice)
799 $fave = Fave::pkeyGet(array('user_id' => $this->id,
800 'notice_id' => $notice->id));
801 return ((is_null($fave)) ? false : true);
806 $c = Cache::instance();
808 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
809 if (is_integer($cnt)) {
815 $faves->user_id = $this->id;
816 $cnt = (int) $faves->count('notice_id');
819 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
825 function noticeCount()
827 $c = Cache::instance();
830 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
831 if (is_integer($cnt)) {
836 $notices = new Notice();
837 $notices->profile_id = $this->id;
838 $cnt = (int) $notices->count('distinct id');
841 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
847 function blowFavesCache()
849 $cache = Cache::instance();
851 // Faves don't happen chronologically, so we need to blow
853 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
854 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
855 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
856 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
858 $this->blowFaveCount();
861 function blowSubscriberCount()
863 $c = Cache::instance();
865 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
869 function blowSubscriptionCount()
871 $c = Cache::instance();
873 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
877 function blowFaveCount()
879 $c = Cache::instance();
881 $c->delete(Cache::key('profile:fave_count:'.$this->id));
885 function blowNoticeCount()
887 $c = Cache::instance();
889 $c->delete(Cache::key('profile:notice_count:'.$this->id));
893 static function maxBio()
895 $biolimit = common_config('profile', 'biolimit');
896 // null => use global limit (distinct from 0!)
897 if (is_null($biolimit)) {
898 $biolimit = common_config('site', 'textlimit');
903 static function bioTooLong($bio)
905 $biolimit = self::maxBio();
906 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
911 $this->_deleteNotices();
912 $this->_deleteSubscriptions();
913 $this->_deleteMessages();
914 $this->_deleteTags();
915 $this->_deleteBlocks();
916 $this->delete_avatars();
918 // Warning: delete() will run on the batch objects,
919 // not on individual objects.
920 $related = array('Reply',
923 Event::handle('ProfileDeleteRelated', array($this, &$related));
925 foreach ($related as $cls) {
927 $inst->profile_id = $this->id;
934 function _deleteNotices()
936 $notice = new Notice();
937 $notice->profile_id = $this->id;
939 if ($notice->find()) {
940 while ($notice->fetch()) {
941 $other = clone($notice);
947 function _deleteSubscriptions()
949 $sub = new Subscription();
950 $sub->subscriber = $this->id;
954 while ($sub->fetch()) {
955 $other = Profile::getKV('id', $sub->subscribed);
959 if ($other->id == $this->id) {
962 Subscription::cancel($this, $other);
965 $subd = new Subscription();
966 $subd->subscribed = $this->id;
969 while ($subd->fetch()) {
970 $other = Profile::getKV('id', $subd->subscriber);
974 if ($other->id == $this->id) {
977 Subscription::cancel($other, $this);
980 $self = new Subscription();
982 $self->subscriber = $this->id;
983 $self->subscribed = $this->id;
988 function _deleteMessages()
990 $msg = new Message();
991 $msg->from_profile = $this->id;
994 $msg = new Message();
995 $msg->to_profile = $this->id;
999 function _deleteTags()
1001 $tag = new Profile_tag();
1002 $tag->tagged = $this->id;
1006 function _deleteBlocks()
1008 $block = new Profile_block();
1009 $block->blocked = $this->id;
1012 $block = new Group_block();
1013 $block->blocked = $this->id;
1017 // XXX: identical to Notice::getLocation.
1019 function getLocation()
1023 if (!empty($this->location_id) && !empty($this->location_ns)) {
1024 $location = Location::fromId($this->location_id, $this->location_ns);
1027 if (is_null($location)) { // no ID, or Location::fromId() failed
1028 if (!empty($this->lat) && !empty($this->lon)) {
1029 $location = Location::fromLatLon($this->lat, $this->lon);
1033 if (is_null($location)) { // still haven't found it!
1034 if (!empty($this->location)) {
1035 $location = Location::fromName($this->location);
1042 function hasRole($name)
1045 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1046 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1048 $has_role = !empty($role);
1049 Event::handle('EndHasRole', array($this, $name, $has_role));
1054 function grantRole($name)
1056 if (Event::handle('StartGrantRole', array($this, $name))) {
1058 $role = new Profile_role();
1060 $role->profile_id = $this->id;
1061 $role->role = $name;
1062 $role->created = common_sql_now();
1064 $result = $role->insert();
1067 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1070 if ($name == 'owner') {
1071 User::blow('user:site_owner');
1074 Event::handle('EndGrantRole', array($this, $name));
1080 function revokeRole($name)
1082 if (Event::handle('StartRevokeRole', array($this, $name))) {
1084 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1088 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1089 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1090 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1093 $result = $role->delete();
1096 common_log_db_error($role, 'DELETE', __FILE__);
1097 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1098 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1099 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1102 if ($name == 'owner') {
1103 User::blow('user:site_owner');
1106 Event::handle('EndRevokeRole', array($this, $name));
1112 function isSandboxed()
1114 return $this->hasRole(Profile_role::SANDBOXED);
1117 function isSilenced()
1119 return $this->hasRole(Profile_role::SILENCED);
1124 $this->grantRole(Profile_role::SANDBOXED);
1127 function unsandbox()
1129 $this->revokeRole(Profile_role::SANDBOXED);
1134 $this->grantRole(Profile_role::SILENCED);
1135 if (common_config('notice', 'hidespam')) {
1136 $this->flushVisibility();
1140 function unsilence()
1142 $this->revokeRole(Profile_role::SILENCED);
1143 if (common_config('notice', 'hidespam')) {
1144 $this->flushVisibility();
1148 function flushVisibility()
1151 $stream = new ProfileNoticeStream($this, $this);
1152 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1153 foreach ($ids as $id) {
1154 self::blow('notice:in-scope-for:%d:null', $id);
1159 * Does this user have the right to do X?
1161 * With our role-based authorization, this is merely a lookup for whether the user
1162 * has a particular role. The implementation currently uses a switch statement
1163 * to determine if the user has the pre-defined role to exercise the right. Future
1164 * implementations may allow per-site roles, and different mappings of roles to rights.
1166 * @param $right string Name of the right, usually a constant in class Right
1167 * @return boolean whether the user has the right in question
1169 function hasRight($right)
1173 if ($this->hasRole(Profile_role::DELETED)) {
1177 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1180 case Right::DELETEOTHERSNOTICE:
1181 case Right::MAKEGROUPADMIN:
1182 case Right::SANDBOXUSER:
1183 case Right::SILENCEUSER:
1184 case Right::DELETEUSER:
1185 case Right::DELETEGROUP:
1186 case Right::TRAINSPAM:
1187 case Right::REVIEWSPAM:
1188 $result = $this->hasRole(Profile_role::MODERATOR);
1190 case Right::CONFIGURESITE:
1191 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1193 case Right::GRANTROLE:
1194 case Right::REVOKEROLE:
1195 $result = $this->hasRole(Profile_role::OWNER);
1197 case Right::NEWNOTICE:
1198 case Right::NEWMESSAGE:
1199 case Right::SUBSCRIBE:
1200 case Right::CREATEGROUP:
1201 $result = !$this->isSilenced();
1203 case Right::PUBLICNOTICE:
1204 case Right::EMAILONREPLY:
1205 case Right::EMAILONSUBSCRIBE:
1206 case Right::EMAILONFAVE:
1207 $result = !$this->isSandboxed();
1209 case Right::WEBLOGIN:
1210 $result = !$this->isSilenced();
1213 $result = !$this->isSilenced();
1215 case Right::BACKUPACCOUNT:
1216 $result = common_config('profile', 'backup');
1218 case Right::RESTOREACCOUNT:
1219 $result = common_config('profile', 'restore');
1221 case Right::DELETEACCOUNT:
1222 $result = common_config('profile', 'delete');
1224 case Right::MOVEACCOUNT:
1225 $result = common_config('profile', 'move');
1235 function hasRepeated($notice_id)
1237 // XXX: not really a pkey, but should work
1239 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1240 'repeat_of' => $notice_id));
1242 return !empty($notice);
1246 * Returns an XML string fragment with limited profile information
1247 * as an Atom <author> element.
1249 * Assumes that Atom has been previously set up as the base namespace.
1251 * @param Profile $cur the current authenticated user
1255 function asAtomAuthor($cur = null)
1257 $xs = new XMLStringer(true);
1259 $xs->elementStart('author');
1260 $xs->element('name', null, $this->nickname);
1261 $xs->element('uri', null, $this->getUri());
1264 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1265 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1266 $xs->element('statusnet:profile_info', $attrs, null);
1268 $xs->elementEnd('author');
1270 return $xs->getString();
1274 * Extra profile info for atom entries
1276 * Clients use some extra profile info in the atom stream.
1277 * This gives it to them.
1279 * @param User $cur Current user
1281 * @return array representation of <statusnet:profile_info> element or null
1284 function profileInfo($cur)
1286 $profileInfoAttr = array('local_id' => $this->id);
1289 // Whether the current user is a subscribed to this profile
1290 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1291 // Whether the current user is has blocked this profile
1292 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1295 return array('statusnet:profile_info', $profileInfoAttr, null);
1299 * Returns an XML string fragment with profile information as an
1300 * Activity Streams <activity:actor> element.
1302 * Assumes that 'activity' namespace has been previously defined.
1306 function asActivityActor()
1308 return $this->asActivityNoun('actor');
1312 * Returns an XML string fragment with profile information as an
1313 * Activity Streams noun object with the given element type.
1315 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1316 * previously defined.
1318 * @param string $element one of 'actor', 'subject', 'object', 'target'
1322 function asActivityNoun($element)
1324 $noun = ActivityObject::fromProfile($this);
1325 return $noun->asString('activity:' . $element);
1329 * Returns the profile's canonical url, not necessarily a uri/unique id
1331 * @return string $profileurl
1333 public function getUrl()
1335 if (empty($this->profileurl) ||
1336 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1337 throw new InvalidUrlException($this->profileurl);
1339 return $this->profileurl;
1343 * Returns the best URI for a profile. Plugins may override.
1345 * @return string $uri
1347 public function getUri()
1351 // give plugins a chance to set the URI
1352 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1354 // check for a local user first
1355 $user = User::getKV('id', $this->id);
1357 if (!empty($user)) {
1361 Event::handle('EndGetProfileUri', array($this, &$uri));
1367 function hasBlocked($other)
1369 $block = Profile_block::exists($this, $other);
1370 return !empty($block);
1373 function getAtomFeed()
1377 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1378 $user = User::getKV('id', $this->id);
1379 if (!empty($user)) {
1380 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1381 'format' => 'atom'));
1383 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1389 static function fromURI($uri)
1393 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1394 // Get a local user or remote (OMB 0.1) profile
1395 $user = User::getKV('uri', $uri);
1396 if (!empty($user)) {
1397 $profile = $user->getProfile();
1399 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1405 function canRead(Notice $notice)
1407 if ($notice->scope & Notice::SITE_SCOPE) {
1408 $user = $this->getUser();
1414 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1415 $replies = $notice->getReplies();
1417 if (!in_array($this->id, $replies)) {
1418 $groups = $notice->getGroups();
1422 foreach ($groups as $group) {
1423 if ($this->isMember($group)) {
1435 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1436 $author = $notice->getProfile();
1437 if (!Subscription::exists($this, $author)) {
1445 static function current()
1447 $user = common_current_user();
1451 $profile = $user->getProfile();
1457 * Magic function called at serialize() time.
1459 * We use this to drop a couple process-specific references
1460 * from DB_DataObject which can cause trouble in future
1463 * @return array of variable names to include in serialization.
1468 $vars = parent::__sleep();
1469 $skip = array('_user', '_avatars');
1470 return array_diff($vars, $skip);
1473 static function fillAvatars(&$profiles, $width)
1476 foreach ($profiles as $profile) {
1477 if (!empty($profile)) {
1478 $ids[] = $profile->id;
1482 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1483 'height' => $width));
1485 foreach ($profiles as $profile) {
1486 if (!empty($profile)) { // ???
1487 $profile->_fillAvatar($width, $avatars[$profile->id]);
1492 // Can't seem to find how to fix this.
1494 function getProfile()