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 protected $_user = -1; // Uninitialized value distinct from null
89 if (is_int($this->_user) && $this->_user == -1) {
90 $this->_user = User::getKV('id', $this->id);
98 function getAvatar($width, $height=null)
100 if (is_null($height)) {
104 $avatar = $this->_getAvatar($width);
106 if (empty($avatar)) {
108 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
109 $avatar = Avatar::pkeyGet(
111 'profile_id' => $this->id,
116 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
119 $this->_fillAvatar($width, $avatar);
125 // XXX: @Fix me gargargar
126 function _getAvatar($width)
128 if (empty($this->_avatars)) {
129 $this->_avatars = array();
132 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
133 // the previously used profile! Please shoot me now! --Zach
134 if (array_key_exists($width, $this->_avatars)) {
135 // Don't return cached avatar unless it's really for this profile
136 if ($this->_avatars[$width]->profile_id == $this->id) {
137 return $this->_avatars[$width];
144 function _fillAvatar($width, $avatar)
146 //common_debug("Storing avatar of width: {$avatar->width} and profile_id {$avatar->profile_id} in profile {$this->id}.");
147 $this->_avatars[$width] = $avatar;
151 function getOriginalAvatar()
153 $pkey = array('profile_id' => $this->id,
155 $avatar = Avatar::pkeyGet($pkey);
156 if (!empty($avatar)) {
163 function setOriginal($filename)
165 $imagefile = new ImageFile($this->id, Avatar::path($filename));
167 $avatar = new Avatar();
168 $avatar->profile_id = $this->id;
169 $avatar->width = $imagefile->width;
170 $avatar->height = $imagefile->height;
171 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
172 $avatar->filename = $filename;
173 $avatar->original = true;
174 $avatar->url = Avatar::url($filename);
175 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
177 // XXX: start a transaction here
179 if (!$this->delete_avatars() || !$avatar->insert()) {
180 @unlink(Avatar::path($filename));
184 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
185 // We don't do a scaled one if original is our scaled size
186 if (!($avatar->width == $size && $avatar->height == $size)) {
187 $scaled_filename = $imagefile->resize($size);
189 //$scaled = DB_DataObject::factory('avatar');
190 $scaled = new Avatar();
191 $scaled->profile_id = $this->id;
192 $scaled->width = $size;
193 $scaled->height = $size;
194 $scaled->original = false;
195 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
196 $scaled->filename = $scaled_filename;
197 $scaled->url = Avatar::url($scaled_filename);
198 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
200 if (!$scaled->insert()) {
210 * Delete attached avatars for this user from the database and filesystem.
211 * This should be used instead of a batch delete() to ensure that files
212 * get removed correctly.
214 * @param boolean $original true to delete only the original-size file
217 function delete_avatars($original=true)
219 $avatar = new Avatar();
220 $avatar->profile_id = $this->id;
222 while ($avatar->fetch()) {
223 if ($avatar->original) {
224 if ($original == false) {
234 * Gets either the full name (if filled) or the nickname.
238 function getBestName()
240 return ($this->fullname) ? $this->fullname : $this->nickname;
244 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
245 * if no fullname is provided.
249 function getFancyName()
251 if ($this->fullname) {
252 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
253 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
255 return $this->nickname;
260 * Get the most recent notice posted by this user, if any.
262 * @return mixed Notice or null
264 function getCurrentNotice()
266 $notice = $this->getNotices(0, 1);
268 if ($notice->fetch()) {
269 if ($notice instanceof ArrayWrapper) {
270 // hack for things trying to work with single notices
271 return $notice->_items[0];
279 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
281 $stream = new TaggedProfileNoticeStream($this, $tag);
283 return $stream->getNotices($offset, $limit, $since_id, $max_id);
286 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
288 $stream = new ProfileNoticeStream($this);
290 return $stream->getNotices($offset, $limit, $since_id, $max_id);
293 function isMember($group)
295 $groups = $this->getGroups(0, null);
296 $gs = $groups->fetchAll();
297 foreach ($gs as $g) {
298 if ($group->id == $g->id) {
305 function isAdmin($group)
307 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
308 'group_id' => $group->id));
309 return (!empty($gm) && $gm->is_admin);
312 function isPendingMember($group)
314 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
315 'group_id' => $group->id));
316 return !empty($request);
319 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
323 $keypart = sprintf('profile:groups:%d', $this->id);
325 $idstring = self::cacheGet($keypart);
327 if ($idstring !== false) {
328 $ids = explode(',', $idstring);
330 $gm = new Group_member();
332 $gm->profile_id = $this->id;
335 while ($gm->fetch()) {
336 $ids[] = $gm->group_id;
340 self::cacheSet($keypart, implode(',', $ids));
343 if (!is_null($offset) && !is_null($limit)) {
344 $ids = array_slice($ids, $offset, $limit);
347 return User_group::multiGet('id', $ids);
350 function isTagged($peopletag)
352 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
353 'tagged' => $this->id,
354 'tag' => $peopletag->tag));
358 function canTag($tagged)
360 if (empty($tagged)) {
364 if ($tagged->id == $this->id) {
368 $all = common_config('peopletag', 'allow_tagging', 'all');
369 $local = common_config('peopletag', 'allow_tagging', 'local');
370 $remote = common_config('peopletag', 'allow_tagging', 'remote');
371 $subs = common_config('peopletag', 'allow_tagging', 'subs');
377 $tagged_user = $tagged->getUser();
378 if (!empty($tagged_user)) {
383 return (Subscription::exists($this, $tagged) ||
384 Subscription::exists($tagged, $this));
385 } else if ($remote) {
391 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
395 $keypart = sprintf('profile:lists:%d', $this->id);
397 $idstr = self::cacheGet($keypart);
399 if ($idstr !== false) {
400 $ids = explode(',', $idstr);
402 $list = new Profile_list();
404 $list->selectAdd('id');
405 $list->tagger = $this->id;
406 $list->selectAdd('id as "cursor"');
409 $list->whereAdd('id > '.$since_id);
413 $list->whereAdd('id <= '.$max_id);
416 if($offset>=0 && !is_null($limit)) {
417 $list->limit($offset, $limit);
420 $list->orderBy('id DESC');
423 while ($list->fetch()) {
428 self::cacheSet($keypart, implode(',', $ids));
431 $showPrivate = (($auth_user instanceof User ||
432 $auth_user instanceof Profile) &&
433 $auth_user->id === $this->id);
437 foreach ($ids as $id) {
438 $list = Profile_list::getKV('id', $id);
440 ($showPrivate || !$list->private)) {
442 if (!isset($list->cursor)) {
443 $list->cursor = $list->id;
450 return new ArrayWrapper($lists);
454 * Get tags that other people put on this profile, in reverse-chron order
456 * @param (Profile|User) $auth_user Authorized user (used for privacy)
457 * @param int $offset Offset from latest
458 * @param int $limit Max number to get
459 * @param datetime $since_id max date
460 * @param datetime $max_id min date
462 * @return Profile_list resulting lists
465 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
467 $list = new Profile_list();
469 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
470 'from profile_tag join profile_list '.
471 'on (profile_tag.tagger = profile_list.tagger ' .
472 ' and profile_tag.tag = profile_list.tag) ' .
473 'where profile_tag.tagged = %d ',
477 if ($auth_user instanceof User || $auth_user instanceof Profile) {
478 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
479 'OR ( profile_list.tagger = %d AND ' .
480 'profile_list.private = true ) )',
483 $qry .= 'AND profile_list.private = 0 ';
487 $qry .= sprintf('AND (cursor > %d) ', $since_id);
491 $qry .= sprintf('AND (cursor < %d) ', $max_id);
494 $qry .= 'ORDER BY profile_tag.modified DESC ';
496 if ($offset >= 0 && !is_null($limit)) {
497 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
504 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
506 $tags = new Profile_list();
507 $tags->private = true;
508 $tags->tagger = $this->id;
511 $tags->whereAdd('id > '.$since_id);
515 $tags->whereAdd('id <= '.$max_id);
518 if($offset>=0 && !is_null($limit)) {
519 $tags->limit($offset, $limit);
522 $tags->orderBy('id DESC');
528 function hasLocalTags()
530 $tags = new Profile_tag();
532 $tags->joinAdd(array('tagger', 'user:id'));
533 $tags->whereAdd('tagged = '.$this->id);
534 $tags->whereAdd('tagger != '.$this->id);
539 return ($tags->N == 0) ? false : true;
542 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
544 $lists = new Profile_list();
545 $subs = new Profile_tag_subscription();
547 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
549 #@fixme: postgres (round(date_part('epoch', my_date)))
550 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
552 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
555 $lists->whereAdd('cursor > '.$since_id);
559 $lists->whereAdd('cursor <= '.$max_id);
562 if($offset>=0 && !is_null($limit)) {
563 $lists->limit($offset, $limit);
566 $lists->orderBy('"cursor" DESC');
573 * Request to join the given group.
574 * May throw exceptions on failure.
576 * @param User_group $group
577 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
579 function joinGroup(User_group $group)
582 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
583 $join = Group_join_queue::saveNew($this, $group);
585 if (Event::handle('StartJoinGroup', array($group, $this))) {
586 $join = Group_member::join($group->id, $this->id);
587 self::blow('profile:groups:%d', $this->id);
588 self::blow('group:member_ids:%d', $group->id);
589 self::blow('group:member_count:%d', $group->id);
590 Event::handle('EndJoinGroup', array($group, $this));
594 // Send any applicable notifications...
601 * Leave a group that this profile is a member of.
603 * @param User_group $group
605 function leaveGroup(User_group $group)
607 if (Event::handle('StartLeaveGroup', array($group, $this))) {
608 Group_member::leave($group->id, $this->id);
609 self::blow('profile:groups:%d', $this->id);
610 self::blow('group:member_ids:%d', $group->id);
611 self::blow('group:member_count:%d', $group->id);
612 Event::handle('EndLeaveGroup', array($group, $this));
616 function avatarUrl($size=AVATAR_PROFILE_SIZE)
618 $avatar = $this->getAvatar($size);
620 return $avatar->displayUrl();
622 return Avatar::defaultImage($size);
626 function getSubscriptions($offset=0, $limit=null)
628 $subs = Subscription::bySubscriber($this->id,
634 while ($subs->fetch()) {
635 $profile = Profile::getKV($subs->subscribed);
637 $profiles[] = $profile;
641 return new ArrayWrapper($profiles);
644 function getSubscribers($offset=0, $limit=null)
646 $subs = Subscription::bySubscribed($this->id,
652 while ($subs->fetch()) {
653 $profile = Profile::getKV($subs->subscriber);
655 $profiles[] = $profile;
659 return new ArrayWrapper($profiles);
662 function getTaggedSubscribers($tag)
665 'SELECT profile.* ' .
666 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
667 'ON profile.id = subscription.subscriber ' .
668 'AND profile.id = profile_tag.tagged ' .
669 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
670 'WHERE subscription.subscribed = %d ' .
671 'AND subscription.subscribed != subscription.subscriber ' .
672 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
673 'AND profile_list.private = false ' .
674 'ORDER BY subscription.created DESC';
676 $profile = new Profile();
679 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
681 while ($profile->fetch()) {
682 $tagged[] = clone($profile);
688 * Get pending subscribers, who have not yet been approved.
694 function getRequests($offset=0, $limit=null)
697 'SELECT profile.* ' .
698 'FROM profile JOIN subscription_queue '.
699 'ON profile.id = subscription_queue.subscriber ' .
700 'WHERE subscription_queue.subscribed = %d ' .
701 'ORDER BY subscription_queue.created DESC ';
703 if ($limit != null) {
704 if (common_config('db','type') == 'pgsql') {
705 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
707 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
711 $members = new Profile();
713 $members->query(sprintf($qry, $this->id));
717 function subscriptionCount()
719 $c = Cache::instance();
722 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
723 if (is_integer($cnt)) {
728 $sub = new Subscription();
729 $sub->subscriber = $this->id;
731 $cnt = (int) $sub->count('distinct subscribed');
733 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
736 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
742 function subscriberCount()
744 $c = Cache::instance();
746 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
747 if (is_integer($cnt)) {
752 $sub = new Subscription();
753 $sub->subscribed = $this->id;
754 $sub->whereAdd('subscriber != subscribed');
755 $cnt = (int) $sub->count('distinct subscriber');
758 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
765 * Is this profile subscribed to another profile?
767 * @param Profile $other
770 function isSubscribed($other)
772 return Subscription::exists($this, $other);
776 * Check if a pending subscription request is outstanding for this...
778 * @param Profile $other
781 function hasPendingSubscription($other)
783 return Subscription_queue::exists($this, $other);
787 * Are these two profiles subscribed to each other?
789 * @param Profile $other
792 function mutuallySubscribed($other)
794 return $this->isSubscribed($other) &&
795 $other->isSubscribed($this);
798 function hasFave($notice)
800 $fave = Fave::pkeyGet(array('user_id' => $this->id,
801 'notice_id' => $notice->id));
802 return ((is_null($fave)) ? false : true);
807 $c = Cache::instance();
809 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
810 if (is_integer($cnt)) {
816 $faves->user_id = $this->id;
817 $cnt = (int) $faves->count('notice_id');
820 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
826 function noticeCount()
828 $c = Cache::instance();
831 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
832 if (is_integer($cnt)) {
837 $notices = new Notice();
838 $notices->profile_id = $this->id;
839 $cnt = (int) $notices->count('distinct id');
842 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
848 function blowFavesCache()
850 $cache = Cache::instance();
852 // Faves don't happen chronologically, so we need to blow
854 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
855 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
856 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
857 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
859 $this->blowFaveCount();
862 function blowSubscriberCount()
864 $c = Cache::instance();
866 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
870 function blowSubscriptionCount()
872 $c = Cache::instance();
874 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
878 function blowFaveCount()
880 $c = Cache::instance();
882 $c->delete(Cache::key('profile:fave_count:'.$this->id));
886 function blowNoticeCount()
888 $c = Cache::instance();
890 $c->delete(Cache::key('profile:notice_count:'.$this->id));
894 static function maxBio()
896 $biolimit = common_config('profile', 'biolimit');
897 // null => use global limit (distinct from 0!)
898 if (is_null($biolimit)) {
899 $biolimit = common_config('site', 'textlimit');
904 static function bioTooLong($bio)
906 $biolimit = self::maxBio();
907 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
912 $this->_deleteNotices();
913 $this->_deleteSubscriptions();
914 $this->_deleteMessages();
915 $this->_deleteTags();
916 $this->_deleteBlocks();
917 $this->delete_avatars();
919 // Warning: delete() will run on the batch objects,
920 // not on individual objects.
921 $related = array('Reply',
924 Event::handle('ProfileDeleteRelated', array($this, &$related));
926 foreach ($related as $cls) {
928 $inst->profile_id = $this->id;
935 function _deleteNotices()
937 $notice = new Notice();
938 $notice->profile_id = $this->id;
940 if ($notice->find()) {
941 while ($notice->fetch()) {
942 $other = clone($notice);
948 function _deleteSubscriptions()
950 $sub = new Subscription();
951 $sub->subscriber = $this->id;
955 while ($sub->fetch()) {
956 $other = Profile::getKV('id', $sub->subscribed);
960 if ($other->id == $this->id) {
963 Subscription::cancel($this, $other);
966 $subd = new Subscription();
967 $subd->subscribed = $this->id;
970 while ($subd->fetch()) {
971 $other = Profile::getKV('id', $subd->subscriber);
975 if ($other->id == $this->id) {
978 Subscription::cancel($other, $this);
981 $self = new Subscription();
983 $self->subscriber = $this->id;
984 $self->subscribed = $this->id;
989 function _deleteMessages()
991 $msg = new Message();
992 $msg->from_profile = $this->id;
995 $msg = new Message();
996 $msg->to_profile = $this->id;
1000 function _deleteTags()
1002 $tag = new Profile_tag();
1003 $tag->tagged = $this->id;
1007 function _deleteBlocks()
1009 $block = new Profile_block();
1010 $block->blocked = $this->id;
1013 $block = new Group_block();
1014 $block->blocked = $this->id;
1018 // XXX: identical to Notice::getLocation.
1020 function getLocation()
1024 if (!empty($this->location_id) && !empty($this->location_ns)) {
1025 $location = Location::fromId($this->location_id, $this->location_ns);
1028 if (is_null($location)) { // no ID, or Location::fromId() failed
1029 if (!empty($this->lat) && !empty($this->lon)) {
1030 $location = Location::fromLatLon($this->lat, $this->lon);
1034 if (is_null($location)) { // still haven't found it!
1035 if (!empty($this->location)) {
1036 $location = Location::fromName($this->location);
1043 function hasRole($name)
1046 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1047 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1049 $has_role = !empty($role);
1050 Event::handle('EndHasRole', array($this, $name, $has_role));
1055 function grantRole($name)
1057 if (Event::handle('StartGrantRole', array($this, $name))) {
1059 $role = new Profile_role();
1061 $role->profile_id = $this->id;
1062 $role->role = $name;
1063 $role->created = common_sql_now();
1065 $result = $role->insert();
1068 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1071 if ($name == 'owner') {
1072 User::blow('user:site_owner');
1075 Event::handle('EndGrantRole', array($this, $name));
1081 function revokeRole($name)
1083 if (Event::handle('StartRevokeRole', array($this, $name))) {
1085 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1089 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1090 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1091 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1094 $result = $role->delete();
1097 common_log_db_error($role, 'DELETE', __FILE__);
1098 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1099 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1100 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1103 if ($name == 'owner') {
1104 User::blow('user:site_owner');
1107 Event::handle('EndRevokeRole', array($this, $name));
1113 function isSandboxed()
1115 return $this->hasRole(Profile_role::SANDBOXED);
1118 function isSilenced()
1120 return $this->hasRole(Profile_role::SILENCED);
1125 $this->grantRole(Profile_role::SANDBOXED);
1128 function unsandbox()
1130 $this->revokeRole(Profile_role::SANDBOXED);
1135 $this->grantRole(Profile_role::SILENCED);
1136 if (common_config('notice', 'hidespam')) {
1137 $this->flushVisibility();
1141 function unsilence()
1143 $this->revokeRole(Profile_role::SILENCED);
1144 if (common_config('notice', 'hidespam')) {
1145 $this->flushVisibility();
1149 function flushVisibility()
1152 $stream = new ProfileNoticeStream($this, $this);
1153 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1154 foreach ($ids as $id) {
1155 self::blow('notice:in-scope-for:%d:null', $id);
1160 * Does this user have the right to do X?
1162 * With our role-based authorization, this is merely a lookup for whether the user
1163 * has a particular role. The implementation currently uses a switch statement
1164 * to determine if the user has the pre-defined role to exercise the right. Future
1165 * implementations may allow per-site roles, and different mappings of roles to rights.
1167 * @param $right string Name of the right, usually a constant in class Right
1168 * @return boolean whether the user has the right in question
1170 function hasRight($right)
1174 if ($this->hasRole(Profile_role::DELETED)) {
1178 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1181 case Right::DELETEOTHERSNOTICE:
1182 case Right::MAKEGROUPADMIN:
1183 case Right::SANDBOXUSER:
1184 case Right::SILENCEUSER:
1185 case Right::DELETEUSER:
1186 case Right::DELETEGROUP:
1187 case Right::TRAINSPAM:
1188 case Right::REVIEWSPAM:
1189 $result = $this->hasRole(Profile_role::MODERATOR);
1191 case Right::CONFIGURESITE:
1192 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1194 case Right::GRANTROLE:
1195 case Right::REVOKEROLE:
1196 $result = $this->hasRole(Profile_role::OWNER);
1198 case Right::NEWNOTICE:
1199 case Right::NEWMESSAGE:
1200 case Right::SUBSCRIBE:
1201 case Right::CREATEGROUP:
1202 $result = !$this->isSilenced();
1204 case Right::PUBLICNOTICE:
1205 case Right::EMAILONREPLY:
1206 case Right::EMAILONSUBSCRIBE:
1207 case Right::EMAILONFAVE:
1208 $result = !$this->isSandboxed();
1210 case Right::WEBLOGIN:
1211 $result = !$this->isSilenced();
1214 $result = !$this->isSilenced();
1216 case Right::BACKUPACCOUNT:
1217 $result = common_config('profile', 'backup');
1219 case Right::RESTOREACCOUNT:
1220 $result = common_config('profile', 'restore');
1222 case Right::DELETEACCOUNT:
1223 $result = common_config('profile', 'delete');
1225 case Right::MOVEACCOUNT:
1226 $result = common_config('profile', 'move');
1236 function hasRepeated($notice_id)
1238 // XXX: not really a pkey, but should work
1240 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1241 'repeat_of' => $notice_id));
1243 return !empty($notice);
1247 * Returns an XML string fragment with limited profile information
1248 * as an Atom <author> element.
1250 * Assumes that Atom has been previously set up as the base namespace.
1252 * @param Profile $cur the current authenticated user
1256 function asAtomAuthor($cur = null)
1258 $xs = new XMLStringer(true);
1260 $xs->elementStart('author');
1261 $xs->element('name', null, $this->nickname);
1262 $xs->element('uri', null, $this->getUri());
1265 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1266 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1267 $xs->element('statusnet:profile_info', $attrs, null);
1269 $xs->elementEnd('author');
1271 return $xs->getString();
1275 * Extra profile info for atom entries
1277 * Clients use some extra profile info in the atom stream.
1278 * This gives it to them.
1280 * @param User $cur Current user
1282 * @return array representation of <statusnet:profile_info> element or null
1285 function profileInfo($cur)
1287 $profileInfoAttr = array('local_id' => $this->id);
1290 // Whether the current user is a subscribed to this profile
1291 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1292 // Whether the current user is has blocked this profile
1293 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1296 return array('statusnet:profile_info', $profileInfoAttr, null);
1300 * Returns an XML string fragment with profile information as an
1301 * Activity Streams <activity:actor> element.
1303 * Assumes that 'activity' namespace has been previously defined.
1307 function asActivityActor()
1309 return $this->asActivityNoun('actor');
1313 * Returns an XML string fragment with profile information as an
1314 * Activity Streams noun object with the given element type.
1316 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1317 * previously defined.
1319 * @param string $element one of 'actor', 'subject', 'object', 'target'
1323 function asActivityNoun($element)
1325 $noun = ActivityObject::fromProfile($this);
1326 return $noun->asString('activity:' . $element);
1330 * Returns the best URI for a profile. Plugins may override.
1332 * @return string $uri
1338 // give plugins a chance to set the URI
1339 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1341 // check for a local user first
1342 $user = User::getKV('id', $this->id);
1344 if (!empty($user)) {
1348 Event::handle('EndGetProfileUri', array($this, &$uri));
1354 function hasBlocked($other)
1356 $block = Profile_block::get($this->id, $other->id);
1358 if (empty($block)) {
1367 function getAtomFeed()
1371 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1372 $user = User::getKV('id', $this->id);
1373 if (!empty($user)) {
1374 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1375 'format' => 'atom'));
1377 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1383 static function fromURI($uri)
1387 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1388 // Get a local user or remote (OMB 0.1) profile
1389 $user = User::getKV('uri', $uri);
1390 if (!empty($user)) {
1391 $profile = $user->getProfile();
1393 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1399 function canRead(Notice $notice)
1401 if ($notice->scope & Notice::SITE_SCOPE) {
1402 $user = $this->getUser();
1408 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1409 $replies = $notice->getReplies();
1411 if (!in_array($this->id, $replies)) {
1412 $groups = $notice->getGroups();
1416 foreach ($groups as $group) {
1417 if ($this->isMember($group)) {
1429 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1430 $author = $notice->getProfile();
1431 if (!Subscription::exists($this, $author)) {
1439 static function current()
1441 $user = common_current_user();
1445 $profile = $user->getProfile();
1451 * Magic function called at serialize() time.
1453 * We use this to drop a couple process-specific references
1454 * from DB_DataObject which can cause trouble in future
1457 * @return array of variable names to include in serialization.
1462 $vars = parent::__sleep();
1463 $skip = array('_user', '_avatars');
1464 return array_diff($vars, $skip);
1467 static function fillAvatars(&$profiles, $width)
1470 foreach ($profiles as $profile) {
1471 if (!empty($profile)) {
1472 $ids[] = $profile->id;
1476 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1477 'height' => $width));
1479 foreach ($profiles as $profile) {
1480 if (!empty($profile)) { // ???
1481 $profile->_fillAvatar($width, $avatars[$profile->id]);
1486 // Can't seem to find how to fix this.
1488 function getProfile()