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'),
59 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name'),
60 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
61 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL'),
62 'bio' => array('type' => 'text', 'description' => 'descriptive biography'),
63 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location'),
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'),
76 'fulltext indexes' => array(
77 'nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage')
82 function multiGet($keyCol, $keyVals, $skipNulls=true)
84 return parent::multiGet('Profile', $keyCol, $keyVals, $skipNulls);
87 /* the code above is auto generated do not remove the tag below */
90 protected $_user = -1; // Uninitialized value distinct from null
94 if (is_int($this->_user) && $this->_user == -1) {
95 $this->_user = User::staticGet('id', $this->id);
101 protected $_avatars = array();
103 function getAvatar($width, $height=null)
105 if (is_null($height)) {
109 if (array_key_exists($width, $this->_avatars)) {
110 return $this->_avatars[$width];
115 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
116 $avatar = Avatar::pkeyGet(array('profile_id' => $this->id,
118 'height' => $height));
119 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
122 $this->_avatars[$width] = $avatar;
127 function _fillAvatar($width, $avatar)
129 $this->_avatars[$width] = $avatar;
132 function getOriginalAvatar()
134 $avatar = DB_DataObject::factory('avatar');
135 $avatar->profile_id = $this->id;
136 $avatar->original = true;
137 if ($avatar->find(true)) {
144 function setOriginal($filename)
146 $imagefile = new ImageFile($this->id, Avatar::path($filename));
148 $avatar = new Avatar();
149 $avatar->profile_id = $this->id;
150 $avatar->width = $imagefile->width;
151 $avatar->height = $imagefile->height;
152 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
153 $avatar->filename = $filename;
154 $avatar->original = true;
155 $avatar->url = Avatar::url($filename);
156 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
158 // XXX: start a transaction here
160 if (!$this->delete_avatars() || !$avatar->insert()) {
161 @unlink(Avatar::path($filename));
165 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
166 // We don't do a scaled one if original is our scaled size
167 if (!($avatar->width == $size && $avatar->height == $size)) {
168 $scaled_filename = $imagefile->resize($size);
170 //$scaled = DB_DataObject::factory('avatar');
171 $scaled = new Avatar();
172 $scaled->profile_id = $this->id;
173 $scaled->width = $size;
174 $scaled->height = $size;
175 $scaled->original = false;
176 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
177 $scaled->filename = $scaled_filename;
178 $scaled->url = Avatar::url($scaled_filename);
179 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
181 if (!$scaled->insert()) {
191 * Delete attached avatars for this user from the database and filesystem.
192 * This should be used instead of a batch delete() to ensure that files
193 * get removed correctly.
195 * @param boolean $original true to delete only the original-size file
198 function delete_avatars($original=true)
200 $avatar = new Avatar();
201 $avatar->profile_id = $this->id;
203 while ($avatar->fetch()) {
204 if ($avatar->original) {
205 if ($original == false) {
215 * Gets either the full name (if filled) or the nickname.
219 function getBestName()
221 return ($this->fullname) ? $this->fullname : $this->nickname;
225 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
226 * if no fullname is provided.
230 function getFancyName()
232 if ($this->fullname) {
233 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
234 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
236 return $this->nickname;
241 * Get the most recent notice posted by this user, if any.
243 * @return mixed Notice or null
245 function getCurrentNotice()
247 $notice = $this->getNotices(0, 1);
249 if ($notice->fetch()) {
250 if ($notice instanceof ArrayWrapper) {
251 // hack for things trying to work with single notices
252 return $notice->_items[0];
260 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
262 $stream = new TaggedProfileNoticeStream($this, $tag);
264 return $stream->getNotices($offset, $limit, $since_id, $max_id);
267 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
269 $stream = new ProfileNoticeStream($this);
271 return $stream->getNotices($offset, $limit, $since_id, $max_id);
274 function isMember($group)
276 $groups = $this->getGroups(0, null);
277 $gs = $groups->fetchAll();
278 foreach ($gs as $g) {
279 if ($group->id == $g->id) {
286 function isAdmin($group)
288 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
289 'group_id' => $group->id));
290 return (!empty($gm) && $gm->is_admin);
293 function isPendingMember($group)
295 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
296 'group_id' => $group->id));
297 return !empty($request);
300 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
304 $keypart = sprintf('profile:groups:%d', $this->id);
306 $idstring = self::cacheGet($keypart);
308 if ($idstring !== false) {
309 $ids = explode(',', $idstring);
311 $gm = new Group_member();
313 $gm->profile_id = $this->id;
316 while ($gm->fetch()) {
317 $ids[] = $gm->group_id;
321 self::cacheSet($keypart, implode(',', $ids));
324 return User_group::multiGet('id', $ids);
327 function isTagged($peopletag)
329 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
330 'tagged' => $this->id,
331 'tag' => $peopletag->tag));
335 function canTag($tagged)
337 if (empty($tagged)) {
341 if ($tagged->id == $this->id) {
345 $all = common_config('peopletag', 'allow_tagging', 'all');
346 $local = common_config('peopletag', 'allow_tagging', 'local');
347 $remote = common_config('peopletag', 'allow_tagging', 'remote');
348 $subs = common_config('peopletag', 'allow_tagging', 'subs');
354 $tagged_user = $tagged->getUser();
355 if (!empty($tagged_user)) {
360 return (Subscription::exists($this, $tagged) ||
361 Subscription::exists($tagged, $this));
362 } else if ($remote) {
368 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
372 $keypart = sprintf('profile:lists:%d', $this->id);
374 $idstr = self::cacheGet($keypart);
376 if ($idstr !== false) {
377 $ids = explode(',', $idstr);
379 $list = new Profile_list();
381 $list->selectAdd('id');
382 $list->tagger = $this->id;
383 $list->selectAdd('id as "cursor"');
386 $list->whereAdd('id > '.$since_id);
390 $list->whereAdd('id <= '.$max_id);
393 if($offset>=0 && !is_null($limit)) {
394 $list->limit($offset, $limit);
397 $list->orderBy('id DESC');
400 while ($list->fetch()) {
405 self::cacheSet($keypart, implode(',', $ids));
408 $showPrivate = (($auth_user instanceof User ||
409 $auth_user instanceof Profile) &&
410 $auth_user->id === $this->id);
414 foreach ($ids as $id) {
415 $list = Profile_list::staticGet('id', $id);
417 ($showPrivate || !$list->private)) {
419 if (!isset($list->cursor)) {
420 $list->cursor = $list->id;
427 return new ArrayWrapper($lists);
430 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
432 $lists = new Profile_list();
434 $tags = new Profile_tag();
435 $tags->tagged = $this->id;
437 $lists->joinAdd($tags);
439 #@fixme: postgres (round(date_part('epoch', my_date)))
440 $lists->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
442 if ($auth_user instanceof User || $auth_user instanceof Profile) {
443 $lists->whereAdd('( ( profile_list.private = false ) ' .
444 'OR ( profile_list.tagger = ' . $auth_user->id . ' AND ' .
445 'profile_list.private = true ) )');
447 $lists->private = false;
451 $lists->whereAdd('cursor > '.$since_id);
455 $lists->whereAdd('cursor <= '.$max_id);
458 if($offset>=0 && !is_null($limit)) {
459 $lists->limit($offset, $limit);
462 $lists->orderBy('profile_tag.modified DESC');
468 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
470 $tags = new Profile_list();
471 $tags->private = true;
472 $tags->tagger = $this->id;
475 $tags->whereAdd('id > '.$since_id);
479 $tags->whereAdd('id <= '.$max_id);
482 if($offset>=0 && !is_null($limit)) {
483 $tags->limit($offset, $limit);
486 $tags->orderBy('id DESC');
492 function hasLocalTags()
494 $tags = new Profile_tag();
496 $tags->joinAdd(array('tagger', 'user:id'));
497 $tags->whereAdd('tagged = '.$this->id);
498 $tags->whereAdd('tagger != '.$this->id);
503 return ($tags->N == 0) ? false : true;
506 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
508 $lists = new Profile_list();
509 $subs = new Profile_tag_subscription();
511 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
513 #@fixme: postgres (round(date_part('epoch', my_date)))
514 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
516 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
519 $lists->whereAdd('cursor > '.$since_id);
523 $lists->whereAdd('cursor <= '.$max_id);
526 if($offset>=0 && !is_null($limit)) {
527 $lists->limit($offset, $limit);
530 $lists->orderBy('"cursor" DESC');
537 * Request to join the given group.
538 * May throw exceptions on failure.
540 * @param User_group $group
541 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
543 function joinGroup(User_group $group)
546 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
547 $join = Group_join_queue::saveNew($this, $group);
549 if (Event::handle('StartJoinGroup', array($group, $this))) {
550 $join = Group_member::join($group->id, $this->id);
551 self::blow('profile:groups:%d', $this->id);
552 Event::handle('EndJoinGroup', array($group, $this));
556 // Send any applicable notifications...
563 * Leave a group that this profile is a member of.
565 * @param User_group $group
567 function leaveGroup(User_group $group)
569 if (Event::handle('StartLeaveGroup', array($group, $this))) {
570 Group_member::leave($group->id, $this->id);
571 self::blow('profile:groups:%d', $this->id);
572 Event::handle('EndLeaveGroup', array($group, $this));
576 function avatarUrl($size=AVATAR_PROFILE_SIZE)
578 $avatar = $this->getAvatar($size);
580 return $avatar->displayUrl();
582 return Avatar::defaultImage($size);
586 function getSubscriptions($offset=0, $limit=null)
588 $subs = Subscription::bySubscriber($this->id,
594 while ($subs->fetch()) {
595 $profile = Profile::staticGet($subs->subscribed);
597 $profiles[] = $profile;
601 return new ArrayWrapper($profiles);
604 function getSubscribers($offset=0, $limit=null)
606 $subs = Subscription::bySubscribed($this->id,
612 while ($subs->fetch()) {
613 $profile = Profile::staticGet($subs->subscriber);
615 $profiles[] = $profile;
619 return new ArrayWrapper($profiles);
622 function getTaggedSubscribers($tag)
625 'SELECT profile.* ' .
626 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
627 'ON profile.id = subscription.subscriber ' .
628 'AND profile.id = profile_tag.tagged ' .
629 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
630 'WHERE subscription.subscribed = %d ' .
631 'AND subscription.subscribed != subscription.subscriber ' .
632 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
633 'AND profile_list.private = false ' .
634 'ORDER BY subscription.created DESC';
636 $profile = new Profile();
639 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
641 while ($profile->fetch()) {
642 $tagged[] = clone($profile);
648 * Get pending subscribers, who have not yet been approved.
654 function getRequests($offset=0, $limit=null)
657 'SELECT profile.* ' .
658 'FROM profile JOIN subscription_queue '.
659 'ON profile.id = subscription_queue.subscriber ' .
660 'WHERE subscription_queue.subscribed = %d ' .
661 'ORDER BY subscription_queue.created DESC ';
663 if ($limit != null) {
664 if (common_config('db','type') == 'pgsql') {
665 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
667 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
671 $members = new Profile();
673 $members->query(sprintf($qry, $this->id));
677 function subscriptionCount()
679 $c = Cache::instance();
682 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
683 if (is_integer($cnt)) {
688 $sub = new Subscription();
689 $sub->subscriber = $this->id;
691 $cnt = (int) $sub->count('distinct subscribed');
693 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
696 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
702 function subscriberCount()
704 $c = Cache::instance();
706 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
707 if (is_integer($cnt)) {
712 $sub = new Subscription();
713 $sub->subscribed = $this->id;
714 $sub->whereAdd('subscriber != subscribed');
715 $cnt = (int) $sub->count('distinct subscriber');
718 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
725 * Is this profile subscribed to another profile?
727 * @param Profile $other
730 function isSubscribed($other)
732 return Subscription::exists($this, $other);
736 * Check if a pending subscription request is outstanding for this...
738 * @param Profile $other
741 function hasPendingSubscription($other)
743 return Subscription_queue::exists($this, $other);
747 * Are these two profiles subscribed to each other?
749 * @param Profile $other
752 function mutuallySubscribed($other)
754 return $this->isSubscribed($other) &&
755 $other->isSubscribed($this);
758 function hasFave($notice)
760 $fave = Fave::pkeyGet(array('user_id' => $this->id,
761 'notice_id' => $notice->id));
762 return ((is_null($fave)) ? false : true);
767 $c = Cache::instance();
769 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
770 if (is_integer($cnt)) {
776 $faves->user_id = $this->id;
777 $cnt = (int) $faves->count('distinct notice_id');
780 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
786 function noticeCount()
788 $c = Cache::instance();
791 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
792 if (is_integer($cnt)) {
797 $notices = new Notice();
798 $notices->profile_id = $this->id;
799 $cnt = (int) $notices->count('distinct id');
802 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
808 function blowFavesCache()
810 $cache = Cache::instance();
812 // Faves don't happen chronologically, so we need to blow
814 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
815 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
816 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
817 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
819 $this->blowFaveCount();
822 function blowSubscriberCount()
824 $c = Cache::instance();
826 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
830 function blowSubscriptionCount()
832 $c = Cache::instance();
834 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
838 function blowFaveCount()
840 $c = Cache::instance();
842 $c->delete(Cache::key('profile:fave_count:'.$this->id));
846 function blowNoticeCount()
848 $c = Cache::instance();
850 $c->delete(Cache::key('profile:notice_count:'.$this->id));
854 static function maxBio()
856 $biolimit = common_config('profile', 'biolimit');
857 // null => use global limit (distinct from 0!)
858 if (is_null($biolimit)) {
859 $biolimit = common_config('site', 'textlimit');
864 static function bioTooLong($bio)
866 $biolimit = self::maxBio();
867 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
872 $this->_deleteNotices();
873 $this->_deleteSubscriptions();
874 $this->_deleteMessages();
875 $this->_deleteTags();
876 $this->_deleteBlocks();
877 $this->delete_avatars();
879 // Warning: delete() will run on the batch objects,
880 // not on individual objects.
881 $related = array('Reply',
884 Event::handle('ProfileDeleteRelated', array($this, &$related));
886 foreach ($related as $cls) {
888 $inst->profile_id = $this->id;
895 function _deleteNotices()
897 $notice = new Notice();
898 $notice->profile_id = $this->id;
900 if ($notice->find()) {
901 while ($notice->fetch()) {
902 $other = clone($notice);
908 function _deleteSubscriptions()
910 $sub = new Subscription();
911 $sub->subscriber = $this->id;
915 while ($sub->fetch()) {
916 $other = Profile::staticGet('id', $sub->subscribed);
920 if ($other->id == $this->id) {
923 Subscription::cancel($this, $other);
926 $subd = new Subscription();
927 $subd->subscribed = $this->id;
930 while ($subd->fetch()) {
931 $other = Profile::staticGet('id', $subd->subscriber);
935 if ($other->id == $this->id) {
938 Subscription::cancel($other, $this);
941 $self = new Subscription();
943 $self->subscriber = $this->id;
944 $self->subscribed = $this->id;
949 function _deleteMessages()
951 $msg = new Message();
952 $msg->from_profile = $this->id;
955 $msg = new Message();
956 $msg->to_profile = $this->id;
960 function _deleteTags()
962 $tag = new Profile_tag();
963 $tag->tagged = $this->id;
967 function _deleteBlocks()
969 $block = new Profile_block();
970 $block->blocked = $this->id;
973 $block = new Group_block();
974 $block->blocked = $this->id;
978 // XXX: identical to Notice::getLocation.
980 function getLocation()
984 if (!empty($this->location_id) && !empty($this->location_ns)) {
985 $location = Location::fromId($this->location_id, $this->location_ns);
988 if (is_null($location)) { // no ID, or Location::fromId() failed
989 if (!empty($this->lat) && !empty($this->lon)) {
990 $location = Location::fromLatLon($this->lat, $this->lon);
994 if (is_null($location)) { // still haven't found it!
995 if (!empty($this->location)) {
996 $location = Location::fromName($this->location);
1003 function hasRole($name)
1006 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1007 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1009 $has_role = !empty($role);
1010 Event::handle('EndHasRole', array($this, $name, $has_role));
1015 function grantRole($name)
1017 if (Event::handle('StartGrantRole', array($this, $name))) {
1019 $role = new Profile_role();
1021 $role->profile_id = $this->id;
1022 $role->role = $name;
1023 $role->created = common_sql_now();
1025 $result = $role->insert();
1028 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1031 if ($name == 'owner') {
1032 User::blow('user:site_owner');
1035 Event::handle('EndGrantRole', array($this, $name));
1041 function revokeRole($name)
1043 if (Event::handle('StartRevokeRole', array($this, $name))) {
1045 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1049 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1050 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1051 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1054 $result = $role->delete();
1057 common_log_db_error($role, 'DELETE', __FILE__);
1058 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1059 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1060 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1063 if ($name == 'owner') {
1064 User::blow('user:site_owner');
1067 Event::handle('EndRevokeRole', array($this, $name));
1073 function isSandboxed()
1075 return $this->hasRole(Profile_role::SANDBOXED);
1078 function isSilenced()
1080 return $this->hasRole(Profile_role::SILENCED);
1085 $this->grantRole(Profile_role::SANDBOXED);
1088 function unsandbox()
1090 $this->revokeRole(Profile_role::SANDBOXED);
1095 $this->grantRole(Profile_role::SILENCED);
1098 function unsilence()
1100 $this->revokeRole(Profile_role::SILENCED);
1104 * Does this user have the right to do X?
1106 * With our role-based authorization, this is merely a lookup for whether the user
1107 * has a particular role. The implementation currently uses a switch statement
1108 * to determine if the user has the pre-defined role to exercise the right. Future
1109 * implementations may allow per-site roles, and different mappings of roles to rights.
1111 * @param $right string Name of the right, usually a constant in class Right
1112 * @return boolean whether the user has the right in question
1114 function hasRight($right)
1118 if ($this->hasRole(Profile_role::DELETED)) {
1122 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1125 case Right::DELETEOTHERSNOTICE:
1126 case Right::MAKEGROUPADMIN:
1127 case Right::SANDBOXUSER:
1128 case Right::SILENCEUSER:
1129 case Right::DELETEUSER:
1130 case Right::DELETEGROUP:
1131 $result = $this->hasRole(Profile_role::MODERATOR);
1133 case Right::CONFIGURESITE:
1134 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1136 case Right::GRANTROLE:
1137 case Right::REVOKEROLE:
1138 $result = $this->hasRole(Profile_role::OWNER);
1140 case Right::NEWNOTICE:
1141 case Right::NEWMESSAGE:
1142 case Right::SUBSCRIBE:
1143 case Right::CREATEGROUP:
1144 $result = !$this->isSilenced();
1146 case Right::PUBLICNOTICE:
1147 case Right::EMAILONREPLY:
1148 case Right::EMAILONSUBSCRIBE:
1149 case Right::EMAILONFAVE:
1150 $result = !$this->isSandboxed();
1152 case Right::WEBLOGIN:
1153 $result = !$this->isSilenced();
1156 $result = !$this->isSilenced();
1158 case Right::BACKUPACCOUNT:
1159 $result = common_config('profile', 'backup');
1161 case Right::RESTOREACCOUNT:
1162 $result = common_config('profile', 'restore');
1164 case Right::DELETEACCOUNT:
1165 $result = common_config('profile', 'delete');
1167 case Right::MOVEACCOUNT:
1168 $result = common_config('profile', 'move');
1178 function hasRepeated($notice_id)
1180 // XXX: not really a pkey, but should work
1182 $notice = Memcached_DataObject::pkeyGet('Notice',
1183 array('profile_id' => $this->id,
1184 'repeat_of' => $notice_id));
1186 return !empty($notice);
1190 * Returns an XML string fragment with limited profile information
1191 * as an Atom <author> element.
1193 * Assumes that Atom has been previously set up as the base namespace.
1195 * @param Profile $cur the current authenticated user
1199 function asAtomAuthor($cur = null)
1201 $xs = new XMLStringer(true);
1203 $xs->elementStart('author');
1204 $xs->element('name', null, $this->nickname);
1205 $xs->element('uri', null, $this->getUri());
1208 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1209 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1210 $xs->element('statusnet:profile_info', $attrs, null);
1212 $xs->elementEnd('author');
1214 return $xs->getString();
1218 * Extra profile info for atom entries
1220 * Clients use some extra profile info in the atom stream.
1221 * This gives it to them.
1223 * @param User $cur Current user
1225 * @return array representation of <statusnet:profile_info> element or null
1228 function profileInfo($cur)
1230 $profileInfoAttr = array('local_id' => $this->id);
1233 // Whether the current user is a subscribed to this profile
1234 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1235 // Whether the current user is has blocked this profile
1236 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1239 return array('statusnet:profile_info', $profileInfoAttr, null);
1243 * Returns an XML string fragment with profile information as an
1244 * Activity Streams <activity:actor> element.
1246 * Assumes that 'activity' namespace has been previously defined.
1250 function asActivityActor()
1252 return $this->asActivityNoun('actor');
1256 * Returns an XML string fragment with profile information as an
1257 * Activity Streams noun object with the given element type.
1259 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1260 * previously defined.
1262 * @param string $element one of 'actor', 'subject', 'object', 'target'
1266 function asActivityNoun($element)
1268 $noun = ActivityObject::fromProfile($this);
1269 return $noun->asString('activity:' . $element);
1273 * Returns the best URI for a profile. Plugins may override.
1275 * @return string $uri
1281 // give plugins a chance to set the URI
1282 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1284 // check for a local user first
1285 $user = User::staticGet('id', $this->id);
1287 if (!empty($user)) {
1291 Event::handle('EndGetProfileUri', array($this, &$uri));
1297 function hasBlocked($other)
1299 $block = Profile_block::get($this->id, $other->id);
1301 if (empty($block)) {
1310 function getAtomFeed()
1314 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1315 $user = User::staticGet('id', $this->id);
1316 if (!empty($user)) {
1317 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1318 'format' => 'atom'));
1320 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1326 static function fromURI($uri)
1330 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1331 // Get a local user or remote (OMB 0.1) profile
1332 $user = User::staticGet('uri', $uri);
1333 if (!empty($user)) {
1334 $profile = $user->getProfile();
1336 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1342 function canRead(Notice $notice)
1344 if ($notice->scope & Notice::SITE_SCOPE) {
1345 $user = $this->getUser();
1351 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1352 $replies = $notice->getReplies();
1354 if (!in_array($this->id, $replies)) {
1355 $groups = $notice->getGroups();
1359 foreach ($groups as $group) {
1360 if ($this->isMember($group)) {
1372 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1373 $author = $notice->getProfile();
1374 if (!Subscription::exists($this, $author)) {
1382 static function current()
1384 $user = common_current_user();
1388 $profile = $user->getProfile();
1394 * Magic function called at serialize() time.
1396 * We use this to drop a couple process-specific references
1397 * from DB_DataObject which can cause trouble in future
1400 * @return array of variable names to include in serialization.
1405 $vars = parent::__sleep();
1406 $skip = array('_user', '_avatars');
1407 return array_diff($vars, $skip);
1410 static function fillAvatars(&$profiles, $width)
1413 foreach ($profiles as $profile) {
1414 $ids[] = $profile->id;
1417 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1418 'height' => $width));
1420 foreach ($profiles as $profile) {
1421 $profile->_fillAvatar($width, $avatars[$profile->id]);