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
48 function staticGet($k,$v=NULL) {
49 return Memcached_DataObject::staticGet('Profile',$k,$v);
52 public static function schemaDef()
55 'description' => 'local and remote users have profiles',
57 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
58 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
59 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
60 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
61 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
62 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
63 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
64 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
65 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
66 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
67 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
69 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
70 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
72 'primary key' => array('id'),
74 'profile_nickname_idx' => array('nickname'),
78 // Add a fulltext index
80 if (common_config('search', 'type') == 'fulltext') {
81 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
87 function multiGet($keyCol, $keyVals, $skipNulls=true)
89 return parent::multiGet('Profile', $keyCol, $keyVals, $skipNulls);
92 /* the code above is auto generated do not remove the tag below */
95 protected $_user = -1; // Uninitialized value distinct from null
99 if (is_int($this->_user) && $this->_user == -1) {
100 $this->_user = User::staticGet('id', $this->id);
108 function getAvatar($width, $height=null)
110 if (is_null($height)) {
114 $avatar = $this->_getAvatar($width);
116 if (empty($avatar)) {
118 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
119 $avatar = Avatar::pkeyGet(
121 'profile_id' => $this->id,
126 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
129 $this->_fillAvatar($width, $avatar);
135 // XXX: @Fix me gargargar
136 function _getAvatar($width)
138 if (empty($this->_avatars)) {
139 $this->_avatars = array();
142 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
143 // the previously used profile! Please shoot me now! --Zach
144 if (array_key_exists($width, $this->_avatars)) {
145 // Don't return cached avatar unless it's really for this profile
146 if ($this->_avatars[$width]->profile_id == $this->id) {
147 return $this->_avatars[$width];
154 function _fillAvatar($width, $avatar)
156 //common_debug("Storing avatar of width: {$avatar->width} and profile_id {$avatar->profile_id} in profile {$this->id}.");
157 $this->_avatars[$width] = $avatar;
161 function getOriginalAvatar()
163 $avatar = DB_DataObject::factory('avatar');
164 $avatar->profile_id = $this->id;
165 $avatar->original = true;
166 if ($avatar->find(true)) {
173 function setOriginal($filename)
175 $imagefile = new ImageFile($this->id, Avatar::path($filename));
177 $avatar = new Avatar();
178 $avatar->profile_id = $this->id;
179 $avatar->width = $imagefile->width;
180 $avatar->height = $imagefile->height;
181 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
182 $avatar->filename = $filename;
183 $avatar->original = true;
184 $avatar->url = Avatar::url($filename);
185 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
187 // XXX: start a transaction here
189 if (!$this->delete_avatars() || !$avatar->insert()) {
190 @unlink(Avatar::path($filename));
194 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
195 // We don't do a scaled one if original is our scaled size
196 if (!($avatar->width == $size && $avatar->height == $size)) {
197 $scaled_filename = $imagefile->resize($size);
199 //$scaled = DB_DataObject::factory('avatar');
200 $scaled = new Avatar();
201 $scaled->profile_id = $this->id;
202 $scaled->width = $size;
203 $scaled->height = $size;
204 $scaled->original = false;
205 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
206 $scaled->filename = $scaled_filename;
207 $scaled->url = Avatar::url($scaled_filename);
208 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
210 if (!$scaled->insert()) {
220 * Delete attached avatars for this user from the database and filesystem.
221 * This should be used instead of a batch delete() to ensure that files
222 * get removed correctly.
224 * @param boolean $original true to delete only the original-size file
227 function delete_avatars($original=true)
229 $avatar = new Avatar();
230 $avatar->profile_id = $this->id;
232 while ($avatar->fetch()) {
233 if ($avatar->original) {
234 if ($original == false) {
244 * Gets either the full name (if filled) or the nickname.
248 function getBestName()
250 return ($this->fullname) ? $this->fullname : $this->nickname;
254 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
255 * if no fullname is provided.
259 function getFancyName()
261 if ($this->fullname) {
262 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
263 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
265 return $this->nickname;
270 * Get the most recent notice posted by this user, if any.
272 * @return mixed Notice or null
274 function getCurrentNotice()
276 $notice = $this->getNotices(0, 1);
278 if ($notice->fetch()) {
279 if ($notice instanceof ArrayWrapper) {
280 // hack for things trying to work with single notices
281 return $notice->_items[0];
289 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
291 $stream = new TaggedProfileNoticeStream($this, $tag);
293 return $stream->getNotices($offset, $limit, $since_id, $max_id);
296 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
298 $stream = new ProfileNoticeStream($this);
300 return $stream->getNotices($offset, $limit, $since_id, $max_id);
303 function isMember($group)
305 $groups = $this->getGroups(0, null);
306 $gs = $groups->fetchAll();
307 foreach ($gs as $g) {
308 if ($group->id == $g->id) {
315 function isAdmin($group)
317 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
318 'group_id' => $group->id));
319 return (!empty($gm) && $gm->is_admin);
322 function isPendingMember($group)
324 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
325 'group_id' => $group->id));
326 return !empty($request);
329 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
333 $keypart = sprintf('profile:groups:%d', $this->id);
335 $idstring = self::cacheGet($keypart);
337 if ($idstring !== false) {
338 $ids = explode(',', $idstring);
340 $gm = new Group_member();
342 $gm->profile_id = $this->id;
345 while ($gm->fetch()) {
346 $ids[] = $gm->group_id;
350 self::cacheSet($keypart, implode(',', $ids));
353 if (!is_null($offset) && !is_null($limit)) {
354 $ids = array_slice($ids, $offset, $limit);
357 return User_group::multiGet('id', $ids);
360 function isTagged($peopletag)
362 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
363 'tagged' => $this->id,
364 'tag' => $peopletag->tag));
368 function canTag($tagged)
370 if (empty($tagged)) {
374 if ($tagged->id == $this->id) {
378 $all = common_config('peopletag', 'allow_tagging', 'all');
379 $local = common_config('peopletag', 'allow_tagging', 'local');
380 $remote = common_config('peopletag', 'allow_tagging', 'remote');
381 $subs = common_config('peopletag', 'allow_tagging', 'subs');
387 $tagged_user = $tagged->getUser();
388 if (!empty($tagged_user)) {
393 return (Subscription::exists($this, $tagged) ||
394 Subscription::exists($tagged, $this));
395 } else if ($remote) {
401 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
405 $keypart = sprintf('profile:lists:%d', $this->id);
407 $idstr = self::cacheGet($keypart);
409 if ($idstr !== false) {
410 $ids = explode(',', $idstr);
412 $list = new Profile_list();
414 $list->selectAdd('id');
415 $list->tagger = $this->id;
416 $list->selectAdd('id as "cursor"');
419 $list->whereAdd('id > '.$since_id);
423 $list->whereAdd('id <= '.$max_id);
426 if($offset>=0 && !is_null($limit)) {
427 $list->limit($offset, $limit);
430 $list->orderBy('id DESC');
433 while ($list->fetch()) {
438 self::cacheSet($keypart, implode(',', $ids));
441 $showPrivate = (($auth_user instanceof User ||
442 $auth_user instanceof Profile) &&
443 $auth_user->id === $this->id);
447 foreach ($ids as $id) {
448 $list = Profile_list::staticGet('id', $id);
450 ($showPrivate || !$list->private)) {
452 if (!isset($list->cursor)) {
453 $list->cursor = $list->id;
460 return new ArrayWrapper($lists);
464 * Get tags that other people put on this profile, in reverse-chron order
466 * @param (Profile|User) $auth_user Authorized user (used for privacy)
467 * @param int $offset Offset from latest
468 * @param int $limit Max number to get
469 * @param datetime $since_id max date
470 * @param datetime $max_id min date
472 * @return Profile_list resulting lists
475 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
477 $list = new Profile_list();
479 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
480 'from profile_tag join profile_list '.
481 'on (profile_tag.tagger = profile_list.tagger ' .
482 ' and profile_tag.tag = profile_list.tag) ' .
483 'where profile_tag.tagged = %d ',
487 if ($auth_user instanceof User || $auth_user instanceof Profile) {
488 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
489 'OR ( profile_list.tagger = %d AND ' .
490 'profile_list.private = true ) )',
493 $qry .= 'AND profile_list.private = 0 ';
497 $qry .= sprintf('AND (cursor > %d) ', $since_id);
501 $qry .= sprintf('AND (cursor < %d) ', $max_id);
504 $qry .= 'ORDER BY profile_tag.modified DESC ';
506 if ($offset >= 0 && !is_null($limit)) {
507 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
514 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
516 $tags = new Profile_list();
517 $tags->private = true;
518 $tags->tagger = $this->id;
521 $tags->whereAdd('id > '.$since_id);
525 $tags->whereAdd('id <= '.$max_id);
528 if($offset>=0 && !is_null($limit)) {
529 $tags->limit($offset, $limit);
532 $tags->orderBy('id DESC');
538 function hasLocalTags()
540 $tags = new Profile_tag();
542 $tags->joinAdd(array('tagger', 'user:id'));
543 $tags->whereAdd('tagged = '.$this->id);
544 $tags->whereAdd('tagger != '.$this->id);
549 return ($tags->N == 0) ? false : true;
552 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
554 $lists = new Profile_list();
555 $subs = new Profile_tag_subscription();
557 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
559 #@fixme: postgres (round(date_part('epoch', my_date)))
560 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
562 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
565 $lists->whereAdd('cursor > '.$since_id);
569 $lists->whereAdd('cursor <= '.$max_id);
572 if($offset>=0 && !is_null($limit)) {
573 $lists->limit($offset, $limit);
576 $lists->orderBy('"cursor" DESC');
583 * Request to join the given group.
584 * May throw exceptions on failure.
586 * @param User_group $group
587 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
589 function joinGroup(User_group $group)
592 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
593 $join = Group_join_queue::saveNew($this, $group);
595 if (Event::handle('StartJoinGroup', array($group, $this))) {
596 $join = Group_member::join($group->id, $this->id);
597 self::blow('profile:groups:%d', $this->id);
598 Event::handle('EndJoinGroup', array($group, $this));
602 // Send any applicable notifications...
609 * Leave a group that this profile is a member of.
611 * @param User_group $group
613 function leaveGroup(User_group $group)
615 if (Event::handle('StartLeaveGroup', array($group, $this))) {
616 Group_member::leave($group->id, $this->id);
617 self::blow('profile:groups:%d', $this->id);
618 Event::handle('EndLeaveGroup', array($group, $this));
622 function avatarUrl($size=AVATAR_PROFILE_SIZE)
624 $avatar = $this->getAvatar($size);
626 return $avatar->displayUrl();
628 return Avatar::defaultImage($size);
632 function getSubscriptions($offset=0, $limit=null)
634 $subs = Subscription::bySubscriber($this->id,
640 while ($subs->fetch()) {
641 $profile = Profile::staticGet($subs->subscribed);
643 $profiles[] = $profile;
647 return new ArrayWrapper($profiles);
650 function getSubscribers($offset=0, $limit=null)
652 $subs = Subscription::bySubscribed($this->id,
658 while ($subs->fetch()) {
659 $profile = Profile::staticGet($subs->subscriber);
661 $profiles[] = $profile;
665 return new ArrayWrapper($profiles);
668 function getTaggedSubscribers($tag)
671 'SELECT profile.* ' .
672 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
673 'ON profile.id = subscription.subscriber ' .
674 'AND profile.id = profile_tag.tagged ' .
675 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
676 'WHERE subscription.subscribed = %d ' .
677 'AND subscription.subscribed != subscription.subscriber ' .
678 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
679 'AND profile_list.private = false ' .
680 'ORDER BY subscription.created DESC';
682 $profile = new Profile();
685 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
687 while ($profile->fetch()) {
688 $tagged[] = clone($profile);
694 * Get pending subscribers, who have not yet been approved.
700 function getRequests($offset=0, $limit=null)
703 'SELECT profile.* ' .
704 'FROM profile JOIN subscription_queue '.
705 'ON profile.id = subscription_queue.subscriber ' .
706 'WHERE subscription_queue.subscribed = %d ' .
707 'ORDER BY subscription_queue.created DESC ';
709 if ($limit != null) {
710 if (common_config('db','type') == 'pgsql') {
711 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
713 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
717 $members = new Profile();
719 $members->query(sprintf($qry, $this->id));
723 function subscriptionCount()
725 $c = Cache::instance();
728 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
729 if (is_integer($cnt)) {
734 $sub = new Subscription();
735 $sub->subscriber = $this->id;
737 $cnt = (int) $sub->count('distinct subscribed');
739 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
742 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
748 function subscriberCount()
750 $c = Cache::instance();
752 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
753 if (is_integer($cnt)) {
758 $sub = new Subscription();
759 $sub->subscribed = $this->id;
760 $sub->whereAdd('subscriber != subscribed');
761 $cnt = (int) $sub->count('distinct subscriber');
764 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
771 * Is this profile subscribed to another profile?
773 * @param Profile $other
776 function isSubscribed($other)
778 return Subscription::exists($this, $other);
782 * Check if a pending subscription request is outstanding for this...
784 * @param Profile $other
787 function hasPendingSubscription($other)
789 return Subscription_queue::exists($this, $other);
793 * Are these two profiles subscribed to each other?
795 * @param Profile $other
798 function mutuallySubscribed($other)
800 return $this->isSubscribed($other) &&
801 $other->isSubscribed($this);
804 function hasFave($notice)
806 $fave = Fave::pkeyGet(array('user_id' => $this->id,
807 'notice_id' => $notice->id));
808 return ((is_null($fave)) ? false : true);
813 $c = Cache::instance();
815 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
816 if (is_integer($cnt)) {
822 $faves->user_id = $this->id;
823 $cnt = (int) $faves->count('notice_id');
826 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
832 function noticeCount()
834 $c = Cache::instance();
837 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
838 if (is_integer($cnt)) {
843 $notices = new Notice();
844 $notices->profile_id = $this->id;
845 $cnt = (int) $notices->count('distinct id');
848 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
854 function blowFavesCache()
856 $cache = Cache::instance();
858 // Faves don't happen chronologically, so we need to blow
860 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
861 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
862 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
863 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
865 $this->blowFaveCount();
868 function blowSubscriberCount()
870 $c = Cache::instance();
872 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
876 function blowSubscriptionCount()
878 $c = Cache::instance();
880 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
884 function blowFaveCount()
886 $c = Cache::instance();
888 $c->delete(Cache::key('profile:fave_count:'.$this->id));
892 function blowNoticeCount()
894 $c = Cache::instance();
896 $c->delete(Cache::key('profile:notice_count:'.$this->id));
900 static function maxBio()
902 $biolimit = common_config('profile', 'biolimit');
903 // null => use global limit (distinct from 0!)
904 if (is_null($biolimit)) {
905 $biolimit = common_config('site', 'textlimit');
910 static function bioTooLong($bio)
912 $biolimit = self::maxBio();
913 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
918 $this->_deleteNotices();
919 $this->_deleteSubscriptions();
920 $this->_deleteMessages();
921 $this->_deleteTags();
922 $this->_deleteBlocks();
923 $this->delete_avatars();
925 // Warning: delete() will run on the batch objects,
926 // not on individual objects.
927 $related = array('Reply',
930 Event::handle('ProfileDeleteRelated', array($this, &$related));
932 foreach ($related as $cls) {
934 $inst->profile_id = $this->id;
941 function _deleteNotices()
943 $notice = new Notice();
944 $notice->profile_id = $this->id;
946 if ($notice->find()) {
947 while ($notice->fetch()) {
948 $other = clone($notice);
954 function _deleteSubscriptions()
956 $sub = new Subscription();
957 $sub->subscriber = $this->id;
961 while ($sub->fetch()) {
962 $other = Profile::staticGet('id', $sub->subscribed);
966 if ($other->id == $this->id) {
969 Subscription::cancel($this, $other);
972 $subd = new Subscription();
973 $subd->subscribed = $this->id;
976 while ($subd->fetch()) {
977 $other = Profile::staticGet('id', $subd->subscriber);
981 if ($other->id == $this->id) {
984 Subscription::cancel($other, $this);
987 $self = new Subscription();
989 $self->subscriber = $this->id;
990 $self->subscribed = $this->id;
995 function _deleteMessages()
997 $msg = new Message();
998 $msg->from_profile = $this->id;
1001 $msg = new Message();
1002 $msg->to_profile = $this->id;
1006 function _deleteTags()
1008 $tag = new Profile_tag();
1009 $tag->tagged = $this->id;
1013 function _deleteBlocks()
1015 $block = new Profile_block();
1016 $block->blocked = $this->id;
1019 $block = new Group_block();
1020 $block->blocked = $this->id;
1024 // XXX: identical to Notice::getLocation.
1026 function getLocation()
1030 if (!empty($this->location_id) && !empty($this->location_ns)) {
1031 $location = Location::fromId($this->location_id, $this->location_ns);
1034 if (is_null($location)) { // no ID, or Location::fromId() failed
1035 if (!empty($this->lat) && !empty($this->lon)) {
1036 $location = Location::fromLatLon($this->lat, $this->lon);
1040 if (is_null($location)) { // still haven't found it!
1041 if (!empty($this->location)) {
1042 $location = Location::fromName($this->location);
1049 function hasRole($name)
1052 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1053 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1055 $has_role = !empty($role);
1056 Event::handle('EndHasRole', array($this, $name, $has_role));
1061 function grantRole($name)
1063 if (Event::handle('StartGrantRole', array($this, $name))) {
1065 $role = new Profile_role();
1067 $role->profile_id = $this->id;
1068 $role->role = $name;
1069 $role->created = common_sql_now();
1071 $result = $role->insert();
1074 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1077 if ($name == 'owner') {
1078 User::blow('user:site_owner');
1081 Event::handle('EndGrantRole', array($this, $name));
1087 function revokeRole($name)
1089 if (Event::handle('StartRevokeRole', array($this, $name))) {
1091 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1095 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1096 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1097 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1100 $result = $role->delete();
1103 common_log_db_error($role, 'DELETE', __FILE__);
1104 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1105 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1106 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1109 if ($name == 'owner') {
1110 User::blow('user:site_owner');
1113 Event::handle('EndRevokeRole', array($this, $name));
1119 function isSandboxed()
1121 return $this->hasRole(Profile_role::SANDBOXED);
1124 function isSilenced()
1126 return $this->hasRole(Profile_role::SILENCED);
1131 $this->grantRole(Profile_role::SANDBOXED);
1134 function unsandbox()
1136 $this->revokeRole(Profile_role::SANDBOXED);
1141 $this->grantRole(Profile_role::SILENCED);
1144 function unsilence()
1146 $this->revokeRole(Profile_role::SILENCED);
1150 * Does this user have the right to do X?
1152 * With our role-based authorization, this is merely a lookup for whether the user
1153 * has a particular role. The implementation currently uses a switch statement
1154 * to determine if the user has the pre-defined role to exercise the right. Future
1155 * implementations may allow per-site roles, and different mappings of roles to rights.
1157 * @param $right string Name of the right, usually a constant in class Right
1158 * @return boolean whether the user has the right in question
1160 function hasRight($right)
1164 if ($this->hasRole(Profile_role::DELETED)) {
1168 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1171 case Right::DELETEOTHERSNOTICE:
1172 case Right::MAKEGROUPADMIN:
1173 case Right::SANDBOXUSER:
1174 case Right::SILENCEUSER:
1175 case Right::DELETEUSER:
1176 case Right::DELETEGROUP:
1177 $result = $this->hasRole(Profile_role::MODERATOR);
1179 case Right::CONFIGURESITE:
1180 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1182 case Right::GRANTROLE:
1183 case Right::REVOKEROLE:
1184 $result = $this->hasRole(Profile_role::OWNER);
1186 case Right::NEWNOTICE:
1187 case Right::NEWMESSAGE:
1188 case Right::SUBSCRIBE:
1189 case Right::CREATEGROUP:
1190 $result = !$this->isSilenced();
1192 case Right::PUBLICNOTICE:
1193 case Right::EMAILONREPLY:
1194 case Right::EMAILONSUBSCRIBE:
1195 case Right::EMAILONFAVE:
1196 $result = !$this->isSandboxed();
1198 case Right::WEBLOGIN:
1199 $result = !$this->isSilenced();
1202 $result = !$this->isSilenced();
1204 case Right::BACKUPACCOUNT:
1205 $result = common_config('profile', 'backup');
1207 case Right::RESTOREACCOUNT:
1208 $result = common_config('profile', 'restore');
1210 case Right::DELETEACCOUNT:
1211 $result = common_config('profile', 'delete');
1213 case Right::MOVEACCOUNT:
1214 $result = common_config('profile', 'move');
1224 function hasRepeated($notice_id)
1226 // XXX: not really a pkey, but should work
1228 $notice = Memcached_DataObject::pkeyGet('Notice',
1229 array('profile_id' => $this->id,
1230 'repeat_of' => $notice_id));
1232 return !empty($notice);
1236 * Returns an XML string fragment with limited profile information
1237 * as an Atom <author> element.
1239 * Assumes that Atom has been previously set up as the base namespace.
1241 * @param Profile $cur the current authenticated user
1245 function asAtomAuthor($cur = null)
1247 $xs = new XMLStringer(true);
1249 $xs->elementStart('author');
1250 $xs->element('name', null, $this->nickname);
1251 $xs->element('uri', null, $this->getUri());
1254 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1255 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1256 $xs->element('statusnet:profile_info', $attrs, null);
1258 $xs->elementEnd('author');
1260 return $xs->getString();
1264 * Extra profile info for atom entries
1266 * Clients use some extra profile info in the atom stream.
1267 * This gives it to them.
1269 * @param User $cur Current user
1271 * @return array representation of <statusnet:profile_info> element or null
1274 function profileInfo($cur)
1276 $profileInfoAttr = array('local_id' => $this->id);
1279 // Whether the current user is a subscribed to this profile
1280 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1281 // Whether the current user is has blocked this profile
1282 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1285 return array('statusnet:profile_info', $profileInfoAttr, null);
1289 * Returns an XML string fragment with profile information as an
1290 * Activity Streams <activity:actor> element.
1292 * Assumes that 'activity' namespace has been previously defined.
1296 function asActivityActor()
1298 return $this->asActivityNoun('actor');
1302 * Returns an XML string fragment with profile information as an
1303 * Activity Streams noun object with the given element type.
1305 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1306 * previously defined.
1308 * @param string $element one of 'actor', 'subject', 'object', 'target'
1312 function asActivityNoun($element)
1314 $noun = ActivityObject::fromProfile($this);
1315 return $noun->asString('activity:' . $element);
1319 * Returns the best URI for a profile. Plugins may override.
1321 * @return string $uri
1327 // give plugins a chance to set the URI
1328 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1330 // check for a local user first
1331 $user = User::staticGet('id', $this->id);
1333 if (!empty($user)) {
1337 Event::handle('EndGetProfileUri', array($this, &$uri));
1343 function hasBlocked($other)
1345 $block = Profile_block::get($this->id, $other->id);
1347 if (empty($block)) {
1356 function getAtomFeed()
1360 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1361 $user = User::staticGet('id', $this->id);
1362 if (!empty($user)) {
1363 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1364 'format' => 'atom'));
1366 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1372 static function fromURI($uri)
1376 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1377 // Get a local user or remote (OMB 0.1) profile
1378 $user = User::staticGet('uri', $uri);
1379 if (!empty($user)) {
1380 $profile = $user->getProfile();
1382 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1388 function canRead(Notice $notice)
1390 if ($notice->scope & Notice::SITE_SCOPE) {
1391 $user = $this->getUser();
1397 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1398 $replies = $notice->getReplies();
1400 if (!in_array($this->id, $replies)) {
1401 $groups = $notice->getGroups();
1405 foreach ($groups as $group) {
1406 if ($this->isMember($group)) {
1418 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1419 $author = $notice->getProfile();
1420 if (!Subscription::exists($this, $author)) {
1428 static function current()
1430 $user = common_current_user();
1434 $profile = $user->getProfile();
1440 * Magic function called at serialize() time.
1442 * We use this to drop a couple process-specific references
1443 * from DB_DataObject which can cause trouble in future
1446 * @return array of variable names to include in serialization.
1451 $vars = parent::__sleep();
1452 $skip = array('_user', '_avatars');
1453 return array_diff($vars, $skip);
1456 static function fillAvatars(&$profiles, $width)
1459 foreach ($profiles as $profile) {
1460 if (!empty($profile)) {
1461 $ids[] = $profile->id;
1465 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1466 'height' => $width));
1468 foreach ($profiles as $profile) {
1469 if (!empty($profile)) { // ???
1470 $profile->_fillAvatar($width, $avatars[$profile->id]);
1475 // Can't seem to find how to fix this.
1477 function getProfile()
1482 static function pivotGet($key, $values, $otherCols=array()) {
1483 return Memcached_DataObject::pivotGet('Profile', $key, $values, $otherCols);