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'),
79 function multiGet($keyCol, $keyVals, $skipNulls=true)
81 return parent::multiGet('Profile', $keyCol, $keyVals, $skipNulls);
84 /* the code above is auto generated do not remove the tag below */
87 protected $_user = -1; // Uninitialized value distinct from null
91 if (is_int($this->_user) && $this->_user == -1) {
92 $this->_user = User::staticGet('id', $this->id);
100 function getAvatar($width, $height=null)
102 if (is_null($height)) {
106 if (!isset($this->_avatars)) {
107 $this->_avatars = array();
110 if (array_key_exists($width, $this->_avatars)) {
111 return $this->_avatars[$width];
116 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
117 $avatar = Avatar::pkeyGet(array('profile_id' => $this->id,
119 'height' => $height));
120 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
123 $this->_avatars[$width] = $avatar;
128 function _fillAvatar($width, $avatar)
130 $this->_avatars[$width] = $avatar;
133 function getOriginalAvatar()
135 $avatar = DB_DataObject::factory('avatar');
136 $avatar->profile_id = $this->id;
137 $avatar->original = true;
138 if ($avatar->find(true)) {
145 function setOriginal($filename)
147 $imagefile = new ImageFile($this->id, Avatar::path($filename));
149 $avatar = new Avatar();
150 $avatar->profile_id = $this->id;
151 $avatar->width = $imagefile->width;
152 $avatar->height = $imagefile->height;
153 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
154 $avatar->filename = $filename;
155 $avatar->original = true;
156 $avatar->url = Avatar::url($filename);
157 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
159 // XXX: start a transaction here
161 if (!$this->delete_avatars() || !$avatar->insert()) {
162 @unlink(Avatar::path($filename));
166 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
167 // We don't do a scaled one if original is our scaled size
168 if (!($avatar->width == $size && $avatar->height == $size)) {
169 $scaled_filename = $imagefile->resize($size);
171 //$scaled = DB_DataObject::factory('avatar');
172 $scaled = new Avatar();
173 $scaled->profile_id = $this->id;
174 $scaled->width = $size;
175 $scaled->height = $size;
176 $scaled->original = false;
177 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
178 $scaled->filename = $scaled_filename;
179 $scaled->url = Avatar::url($scaled_filename);
180 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
182 if (!$scaled->insert()) {
192 * Delete attached avatars for this user from the database and filesystem.
193 * This should be used instead of a batch delete() to ensure that files
194 * get removed correctly.
196 * @param boolean $original true to delete only the original-size file
199 function delete_avatars($original=true)
201 $avatar = new Avatar();
202 $avatar->profile_id = $this->id;
204 while ($avatar->fetch()) {
205 if ($avatar->original) {
206 if ($original == false) {
216 * Gets either the full name (if filled) or the nickname.
220 function getBestName()
222 return ($this->fullname) ? $this->fullname : $this->nickname;
226 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
227 * if no fullname is provided.
231 function getFancyName()
233 if ($this->fullname) {
234 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
235 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
237 return $this->nickname;
242 * Get the most recent notice posted by this user, if any.
244 * @return mixed Notice or null
246 function getCurrentNotice()
248 $notice = $this->getNotices(0, 1);
250 if ($notice->fetch()) {
251 if ($notice instanceof ArrayWrapper) {
252 // hack for things trying to work with single notices
253 return $notice->_items[0];
261 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
263 $stream = new TaggedProfileNoticeStream($this, $tag);
265 return $stream->getNotices($offset, $limit, $since_id, $max_id);
268 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
270 $stream = new ProfileNoticeStream($this);
272 return $stream->getNotices($offset, $limit, $since_id, $max_id);
275 function isMember($group)
277 $groups = $this->getGroups(0, null);
278 $gs = $groups->fetchAll();
279 foreach ($gs as $g) {
280 if ($group->id == $g->id) {
287 function isAdmin($group)
289 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
290 'group_id' => $group->id));
291 return (!empty($gm) && $gm->is_admin);
294 function isPendingMember($group)
296 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
297 'group_id' => $group->id));
298 return !empty($request);
301 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
305 $keypart = sprintf('profile:groups:%d', $this->id);
307 $idstring = self::cacheGet($keypart);
309 if ($idstring !== false) {
310 $ids = explode(',', $idstring);
312 $gm = new Group_member();
314 $gm->profile_id = $this->id;
317 while ($gm->fetch()) {
318 $ids[] = $gm->group_id;
322 self::cacheSet($keypart, implode(',', $ids));
325 return User_group::multiGet('id', $ids);
328 function isTagged($peopletag)
330 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
331 'tagged' => $this->id,
332 'tag' => $peopletag->tag));
336 function canTag($tagged)
338 if (empty($tagged)) {
342 if ($tagged->id == $this->id) {
346 $all = common_config('peopletag', 'allow_tagging', 'all');
347 $local = common_config('peopletag', 'allow_tagging', 'local');
348 $remote = common_config('peopletag', 'allow_tagging', 'remote');
349 $subs = common_config('peopletag', 'allow_tagging', 'subs');
355 $tagged_user = $tagged->getUser();
356 if (!empty($tagged_user)) {
361 return (Subscription::exists($this, $tagged) ||
362 Subscription::exists($tagged, $this));
363 } else if ($remote) {
369 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
373 $keypart = sprintf('profile:lists:%d', $this->id);
375 $idstr = self::cacheGet($keypart);
377 if ($idstr !== false) {
378 $ids = explode(',', $idstr);
380 $list = new Profile_list();
382 $list->selectAdd('id');
383 $list->tagger = $this->id;
384 $list->selectAdd('id as "cursor"');
387 $list->whereAdd('id > '.$since_id);
391 $list->whereAdd('id <= '.$max_id);
394 if($offset>=0 && !is_null($limit)) {
395 $list->limit($offset, $limit);
398 $list->orderBy('id DESC');
401 while ($list->fetch()) {
406 self::cacheSet($keypart, implode(',', $ids));
409 $showPrivate = (($auth_user instanceof User ||
410 $auth_user instanceof Profile) &&
411 $auth_user->id === $this->id);
415 foreach ($ids as $id) {
416 $list = Profile_list::staticGet('id', $id);
418 ($showPrivate || !$list->private)) {
420 if (!isset($list->cursor)) {
421 $list->cursor = $list->id;
428 return new ArrayWrapper($lists);
431 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
433 $lists = new Profile_list();
435 $tags = new Profile_tag();
436 $tags->tagged = $this->id;
438 $lists->joinAdd($tags);
440 #@fixme: postgres (round(date_part('epoch', my_date)))
441 $lists->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
443 if ($auth_user instanceof User || $auth_user instanceof Profile) {
444 $lists->whereAdd('( ( profile_list.private = false ) ' .
445 'OR ( profile_list.tagger = ' . $auth_user->id . ' AND ' .
446 'profile_list.private = true ) )');
448 $lists->private = false;
452 $lists->whereAdd('cursor > '.$since_id);
456 $lists->whereAdd('cursor <= '.$max_id);
459 if($offset>=0 && !is_null($limit)) {
460 $lists->limit($offset, $limit);
463 $lists->orderBy('profile_tag.modified DESC');
469 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
471 $tags = new Profile_list();
472 $tags->private = true;
473 $tags->tagger = $this->id;
476 $tags->whereAdd('id > '.$since_id);
480 $tags->whereAdd('id <= '.$max_id);
483 if($offset>=0 && !is_null($limit)) {
484 $tags->limit($offset, $limit);
487 $tags->orderBy('id DESC');
493 function hasLocalTags()
495 $tags = new Profile_tag();
497 $tags->joinAdd(array('tagger', 'user:id'));
498 $tags->whereAdd('tagged = '.$this->id);
499 $tags->whereAdd('tagger != '.$this->id);
504 return ($tags->N == 0) ? false : true;
507 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
509 $lists = new Profile_list();
510 $subs = new Profile_tag_subscription();
512 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
514 #@fixme: postgres (round(date_part('epoch', my_date)))
515 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
517 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
520 $lists->whereAdd('cursor > '.$since_id);
524 $lists->whereAdd('cursor <= '.$max_id);
527 if($offset>=0 && !is_null($limit)) {
528 $lists->limit($offset, $limit);
531 $lists->orderBy('"cursor" DESC');
538 * Request to join the given group.
539 * May throw exceptions on failure.
541 * @param User_group $group
542 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
544 function joinGroup(User_group $group)
547 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
548 $join = Group_join_queue::saveNew($this, $group);
550 if (Event::handle('StartJoinGroup', array($group, $this))) {
551 $join = Group_member::join($group->id, $this->id);
552 self::blow('profile:groups:%d', $this->id);
553 Event::handle('EndJoinGroup', array($group, $this));
557 // Send any applicable notifications...
564 * Leave a group that this profile is a member of.
566 * @param User_group $group
568 function leaveGroup(User_group $group)
570 if (Event::handle('StartLeaveGroup', array($group, $this))) {
571 Group_member::leave($group->id, $this->id);
572 self::blow('profile:groups:%d', $this->id);
573 Event::handle('EndLeaveGroup', array($group, $this));
577 function avatarUrl($size=AVATAR_PROFILE_SIZE)
579 $avatar = $this->getAvatar($size);
581 return $avatar->displayUrl();
583 return Avatar::defaultImage($size);
587 function getSubscriptions($offset=0, $limit=null)
589 $subs = Subscription::bySubscriber($this->id,
595 while ($subs->fetch()) {
596 $profile = Profile::staticGet($subs->subscribed);
598 $profiles[] = $profile;
602 return new ArrayWrapper($profiles);
605 function getSubscribers($offset=0, $limit=null)
607 $subs = Subscription::bySubscribed($this->id,
613 while ($subs->fetch()) {
614 $profile = Profile::staticGet($subs->subscriber);
616 $profiles[] = $profile;
620 return new ArrayWrapper($profiles);
623 function getTaggedSubscribers($tag)
626 'SELECT profile.* ' .
627 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
628 'ON profile.id = subscription.subscriber ' .
629 'AND profile.id = profile_tag.tagged ' .
630 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
631 'WHERE subscription.subscribed = %d ' .
632 'AND subscription.subscribed != subscription.subscriber ' .
633 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
634 'AND profile_list.private = false ' .
635 'ORDER BY subscription.created DESC';
637 $profile = new Profile();
640 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
642 while ($profile->fetch()) {
643 $tagged[] = clone($profile);
649 * Get pending subscribers, who have not yet been approved.
655 function getRequests($offset=0, $limit=null)
658 'SELECT profile.* ' .
659 'FROM profile JOIN subscription_queue '.
660 'ON profile.id = subscription_queue.subscriber ' .
661 'WHERE subscription_queue.subscribed = %d ' .
662 'ORDER BY subscription_queue.created DESC ';
664 if ($limit != null) {
665 if (common_config('db','type') == 'pgsql') {
666 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
668 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
672 $members = new Profile();
674 $members->query(sprintf($qry, $this->id));
678 function subscriptionCount()
680 $c = Cache::instance();
683 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
684 if (is_integer($cnt)) {
689 $sub = new Subscription();
690 $sub->subscriber = $this->id;
692 $cnt = (int) $sub->count('distinct subscribed');
694 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
697 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
703 function subscriberCount()
705 $c = Cache::instance();
707 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
708 if (is_integer($cnt)) {
713 $sub = new Subscription();
714 $sub->subscribed = $this->id;
715 $sub->whereAdd('subscriber != subscribed');
716 $cnt = (int) $sub->count('distinct subscriber');
719 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
726 * Is this profile subscribed to another profile?
728 * @param Profile $other
731 function isSubscribed($other)
733 return Subscription::exists($this, $other);
737 * Check if a pending subscription request is outstanding for this...
739 * @param Profile $other
742 function hasPendingSubscription($other)
744 return Subscription_queue::exists($this, $other);
748 * Are these two profiles subscribed to each other?
750 * @param Profile $other
753 function mutuallySubscribed($other)
755 return $this->isSubscribed($other) &&
756 $other->isSubscribed($this);
759 function hasFave($notice)
761 $fave = Fave::pkeyGet(array('user_id' => $this->id,
762 'notice_id' => $notice->id));
763 return ((is_null($fave)) ? false : true);
768 $c = Cache::instance();
770 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
771 if (is_integer($cnt)) {
777 $faves->user_id = $this->id;
778 $cnt = (int) $faves->count('notice_id');
781 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
787 function noticeCount()
789 $c = Cache::instance();
792 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
793 if (is_integer($cnt)) {
798 $notices = new Notice();
799 $notices->profile_id = $this->id;
800 $cnt = (int) $notices->count('distinct id');
803 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
809 function blowFavesCache()
811 $cache = Cache::instance();
813 // Faves don't happen chronologically, so we need to blow
815 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
816 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
817 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
818 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
820 $this->blowFaveCount();
823 function blowSubscriberCount()
825 $c = Cache::instance();
827 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
831 function blowSubscriptionCount()
833 $c = Cache::instance();
835 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
839 function blowFaveCount()
841 $c = Cache::instance();
843 $c->delete(Cache::key('profile:fave_count:'.$this->id));
847 function blowNoticeCount()
849 $c = Cache::instance();
851 $c->delete(Cache::key('profile:notice_count:'.$this->id));
855 static function maxBio()
857 $biolimit = common_config('profile', 'biolimit');
858 // null => use global limit (distinct from 0!)
859 if (is_null($biolimit)) {
860 $biolimit = common_config('site', 'textlimit');
865 static function bioTooLong($bio)
867 $biolimit = self::maxBio();
868 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
873 $this->_deleteNotices();
874 $this->_deleteSubscriptions();
875 $this->_deleteMessages();
876 $this->_deleteTags();
877 $this->_deleteBlocks();
878 $this->delete_avatars();
880 // Warning: delete() will run on the batch objects,
881 // not on individual objects.
882 $related = array('Reply',
885 Event::handle('ProfileDeleteRelated', array($this, &$related));
887 foreach ($related as $cls) {
889 $inst->profile_id = $this->id;
896 function _deleteNotices()
898 $notice = new Notice();
899 $notice->profile_id = $this->id;
901 if ($notice->find()) {
902 while ($notice->fetch()) {
903 $other = clone($notice);
909 function _deleteSubscriptions()
911 $sub = new Subscription();
912 $sub->subscriber = $this->id;
916 while ($sub->fetch()) {
917 $other = Profile::staticGet('id', $sub->subscribed);
921 if ($other->id == $this->id) {
924 Subscription::cancel($this, $other);
927 $subd = new Subscription();
928 $subd->subscribed = $this->id;
931 while ($subd->fetch()) {
932 $other = Profile::staticGet('id', $subd->subscriber);
936 if ($other->id == $this->id) {
939 Subscription::cancel($other, $this);
942 $self = new Subscription();
944 $self->subscriber = $this->id;
945 $self->subscribed = $this->id;
950 function _deleteMessages()
952 $msg = new Message();
953 $msg->from_profile = $this->id;
956 $msg = new Message();
957 $msg->to_profile = $this->id;
961 function _deleteTags()
963 $tag = new Profile_tag();
964 $tag->tagged = $this->id;
968 function _deleteBlocks()
970 $block = new Profile_block();
971 $block->blocked = $this->id;
974 $block = new Group_block();
975 $block->blocked = $this->id;
979 // XXX: identical to Notice::getLocation.
981 function getLocation()
985 if (!empty($this->location_id) && !empty($this->location_ns)) {
986 $location = Location::fromId($this->location_id, $this->location_ns);
989 if (is_null($location)) { // no ID, or Location::fromId() failed
990 if (!empty($this->lat) && !empty($this->lon)) {
991 $location = Location::fromLatLon($this->lat, $this->lon);
995 if (is_null($location)) { // still haven't found it!
996 if (!empty($this->location)) {
997 $location = Location::fromName($this->location);
1004 function hasRole($name)
1007 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1008 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1010 $has_role = !empty($role);
1011 Event::handle('EndHasRole', array($this, $name, $has_role));
1016 function grantRole($name)
1018 if (Event::handle('StartGrantRole', array($this, $name))) {
1020 $role = new Profile_role();
1022 $role->profile_id = $this->id;
1023 $role->role = $name;
1024 $role->created = common_sql_now();
1026 $result = $role->insert();
1029 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1032 if ($name == 'owner') {
1033 User::blow('user:site_owner');
1036 Event::handle('EndGrantRole', array($this, $name));
1042 function revokeRole($name)
1044 if (Event::handle('StartRevokeRole', array($this, $name))) {
1046 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1050 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1051 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1052 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1055 $result = $role->delete();
1058 common_log_db_error($role, 'DELETE', __FILE__);
1059 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1060 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1061 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1064 if ($name == 'owner') {
1065 User::blow('user:site_owner');
1068 Event::handle('EndRevokeRole', array($this, $name));
1074 function isSandboxed()
1076 return $this->hasRole(Profile_role::SANDBOXED);
1079 function isSilenced()
1081 return $this->hasRole(Profile_role::SILENCED);
1086 $this->grantRole(Profile_role::SANDBOXED);
1089 function unsandbox()
1091 $this->revokeRole(Profile_role::SANDBOXED);
1096 $this->grantRole(Profile_role::SILENCED);
1099 function unsilence()
1101 $this->revokeRole(Profile_role::SILENCED);
1105 * Does this user have the right to do X?
1107 * With our role-based authorization, this is merely a lookup for whether the user
1108 * has a particular role. The implementation currently uses a switch statement
1109 * to determine if the user has the pre-defined role to exercise the right. Future
1110 * implementations may allow per-site roles, and different mappings of roles to rights.
1112 * @param $right string Name of the right, usually a constant in class Right
1113 * @return boolean whether the user has the right in question
1115 function hasRight($right)
1119 if ($this->hasRole(Profile_role::DELETED)) {
1123 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1126 case Right::DELETEOTHERSNOTICE:
1127 case Right::MAKEGROUPADMIN:
1128 case Right::SANDBOXUSER:
1129 case Right::SILENCEUSER:
1130 case Right::DELETEUSER:
1131 case Right::DELETEGROUP:
1132 $result = $this->hasRole(Profile_role::MODERATOR);
1134 case Right::CONFIGURESITE:
1135 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1137 case Right::GRANTROLE:
1138 case Right::REVOKEROLE:
1139 $result = $this->hasRole(Profile_role::OWNER);
1141 case Right::NEWNOTICE:
1142 case Right::NEWMESSAGE:
1143 case Right::SUBSCRIBE:
1144 case Right::CREATEGROUP:
1145 $result = !$this->isSilenced();
1147 case Right::PUBLICNOTICE:
1148 case Right::EMAILONREPLY:
1149 case Right::EMAILONSUBSCRIBE:
1150 case Right::EMAILONFAVE:
1151 $result = !$this->isSandboxed();
1153 case Right::WEBLOGIN:
1154 $result = !$this->isSilenced();
1157 $result = !$this->isSilenced();
1159 case Right::BACKUPACCOUNT:
1160 $result = common_config('profile', 'backup');
1162 case Right::RESTOREACCOUNT:
1163 $result = common_config('profile', 'restore');
1165 case Right::DELETEACCOUNT:
1166 $result = common_config('profile', 'delete');
1168 case Right::MOVEACCOUNT:
1169 $result = common_config('profile', 'move');
1179 function hasRepeated($notice_id)
1181 // XXX: not really a pkey, but should work
1183 $notice = Memcached_DataObject::pkeyGet('Notice',
1184 array('profile_id' => $this->id,
1185 'repeat_of' => $notice_id));
1187 return !empty($notice);
1191 * Returns an XML string fragment with limited profile information
1192 * as an Atom <author> element.
1194 * Assumes that Atom has been previously set up as the base namespace.
1196 * @param Profile $cur the current authenticated user
1200 function asAtomAuthor($cur = null)
1202 $xs = new XMLStringer(true);
1204 $xs->elementStart('author');
1205 $xs->element('name', null, $this->nickname);
1206 $xs->element('uri', null, $this->getUri());
1209 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1210 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1211 $xs->element('statusnet:profile_info', $attrs, null);
1213 $xs->elementEnd('author');
1215 return $xs->getString();
1219 * Extra profile info for atom entries
1221 * Clients use some extra profile info in the atom stream.
1222 * This gives it to them.
1224 * @param User $cur Current user
1226 * @return array representation of <statusnet:profile_info> element or null
1229 function profileInfo($cur)
1231 $profileInfoAttr = array('local_id' => $this->id);
1234 // Whether the current user is a subscribed to this profile
1235 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1236 // Whether the current user is has blocked this profile
1237 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1240 return array('statusnet:profile_info', $profileInfoAttr, null);
1244 * Returns an XML string fragment with profile information as an
1245 * Activity Streams <activity:actor> element.
1247 * Assumes that 'activity' namespace has been previously defined.
1251 function asActivityActor()
1253 return $this->asActivityNoun('actor');
1257 * Returns an XML string fragment with profile information as an
1258 * Activity Streams noun object with the given element type.
1260 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1261 * previously defined.
1263 * @param string $element one of 'actor', 'subject', 'object', 'target'
1267 function asActivityNoun($element)
1269 $noun = ActivityObject::fromProfile($this);
1270 return $noun->asString('activity:' . $element);
1274 * Returns the best URI for a profile. Plugins may override.
1276 * @return string $uri
1282 // give plugins a chance to set the URI
1283 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1285 // check for a local user first
1286 $user = User::staticGet('id', $this->id);
1288 if (!empty($user)) {
1292 Event::handle('EndGetProfileUri', array($this, &$uri));
1298 function hasBlocked($other)
1300 $block = Profile_block::get($this->id, $other->id);
1302 if (empty($block)) {
1311 function getAtomFeed()
1315 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1316 $user = User::staticGet('id', $this->id);
1317 if (!empty($user)) {
1318 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1319 'format' => 'atom'));
1321 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1327 static function fromURI($uri)
1331 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1332 // Get a local user or remote (OMB 0.1) profile
1333 $user = User::staticGet('uri', $uri);
1334 if (!empty($user)) {
1335 $profile = $user->getProfile();
1337 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1343 function canRead(Notice $notice)
1345 if ($notice->scope & Notice::SITE_SCOPE) {
1346 $user = $this->getUser();
1352 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1353 $replies = $notice->getReplies();
1355 if (!in_array($this->id, $replies)) {
1356 $groups = $notice->getGroups();
1360 foreach ($groups as $group) {
1361 if ($this->isMember($group)) {
1373 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1374 $author = $notice->getProfile();
1375 if (!Subscription::exists($this, $author)) {
1383 static function current()
1385 $user = common_current_user();
1389 $profile = $user->getProfile();
1395 * Magic function called at serialize() time.
1397 * We use this to drop a couple process-specific references
1398 * from DB_DataObject which can cause trouble in future
1401 * @return array of variable names to include in serialization.
1406 $vars = parent::__sleep();
1407 $skip = array('_user', '_avatars');
1408 return array_diff($vars, $skip);
1411 static function fillAvatars(&$profiles, $width)
1414 foreach ($profiles as $profile) {
1415 $ids[] = $profile->id;
1418 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1419 'height' => $width));
1421 foreach ($profiles as $profile) {
1422 $profile->_fillAvatar($width, $avatars[$profile->id]);