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 if (!isset($this->_avatars)) {
115 $this->_avatars = array();
118 if (array_key_exists($width, $this->_avatars)) {
119 return $this->_avatars[$width];
124 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
125 $avatar = Avatar::pkeyGet(array('profile_id' => $this->id,
127 'height' => $height));
128 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
131 $this->_avatars[$width] = $avatar;
136 function _fillAvatar($width, $avatar)
138 $this->_avatars[$width] = $avatar;
141 function getOriginalAvatar()
143 $avatar = DB_DataObject::factory('avatar');
144 $avatar->profile_id = $this->id;
145 $avatar->original = true;
146 if ($avatar->find(true)) {
153 function setOriginal($filename)
155 $imagefile = new ImageFile($this->id, Avatar::path($filename));
157 $avatar = new Avatar();
158 $avatar->profile_id = $this->id;
159 $avatar->width = $imagefile->width;
160 $avatar->height = $imagefile->height;
161 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
162 $avatar->filename = $filename;
163 $avatar->original = true;
164 $avatar->url = Avatar::url($filename);
165 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
167 // XXX: start a transaction here
169 if (!$this->delete_avatars() || !$avatar->insert()) {
170 @unlink(Avatar::path($filename));
174 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
175 // We don't do a scaled one if original is our scaled size
176 if (!($avatar->width == $size && $avatar->height == $size)) {
177 $scaled_filename = $imagefile->resize($size);
179 //$scaled = DB_DataObject::factory('avatar');
180 $scaled = new Avatar();
181 $scaled->profile_id = $this->id;
182 $scaled->width = $size;
183 $scaled->height = $size;
184 $scaled->original = false;
185 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
186 $scaled->filename = $scaled_filename;
187 $scaled->url = Avatar::url($scaled_filename);
188 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
190 if (!$scaled->insert()) {
200 * Delete attached avatars for this user from the database and filesystem.
201 * This should be used instead of a batch delete() to ensure that files
202 * get removed correctly.
204 * @param boolean $original true to delete only the original-size file
207 function delete_avatars($original=true)
209 $avatar = new Avatar();
210 $avatar->profile_id = $this->id;
212 while ($avatar->fetch()) {
213 if ($avatar->original) {
214 if ($original == false) {
224 * Gets either the full name (if filled) or the nickname.
228 function getBestName()
230 return ($this->fullname) ? $this->fullname : $this->nickname;
234 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
235 * if no fullname is provided.
239 function getFancyName()
241 if ($this->fullname) {
242 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
243 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
245 return $this->nickname;
250 * Get the most recent notice posted by this user, if any.
252 * @return mixed Notice or null
254 function getCurrentNotice()
256 $notice = $this->getNotices(0, 1);
258 if ($notice->fetch()) {
259 if ($notice instanceof ArrayWrapper) {
260 // hack for things trying to work with single notices
261 return $notice->_items[0];
269 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
271 $stream = new TaggedProfileNoticeStream($this, $tag);
273 return $stream->getNotices($offset, $limit, $since_id, $max_id);
276 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
278 $stream = new ProfileNoticeStream($this);
280 return $stream->getNotices($offset, $limit, $since_id, $max_id);
283 function isMember($group)
285 $groups = $this->getGroups(0, null);
286 $gs = $groups->fetchAll();
287 foreach ($gs as $g) {
288 if ($group->id == $g->id) {
295 function isAdmin($group)
297 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
298 'group_id' => $group->id));
299 return (!empty($gm) && $gm->is_admin);
302 function isPendingMember($group)
304 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
305 'group_id' => $group->id));
306 return !empty($request);
309 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
313 $keypart = sprintf('profile:groups:%d', $this->id);
315 $idstring = self::cacheGet($keypart);
317 if ($idstring !== false) {
318 $ids = explode(',', $idstring);
320 $gm = new Group_member();
322 $gm->profile_id = $this->id;
325 while ($gm->fetch()) {
326 $ids[] = $gm->group_id;
330 self::cacheSet($keypart, implode(',', $ids));
333 return User_group::multiGet('id', $ids);
336 function isTagged($peopletag)
338 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
339 'tagged' => $this->id,
340 'tag' => $peopletag->tag));
344 function canTag($tagged)
346 if (empty($tagged)) {
350 if ($tagged->id == $this->id) {
354 $all = common_config('peopletag', 'allow_tagging', 'all');
355 $local = common_config('peopletag', 'allow_tagging', 'local');
356 $remote = common_config('peopletag', 'allow_tagging', 'remote');
357 $subs = common_config('peopletag', 'allow_tagging', 'subs');
363 $tagged_user = $tagged->getUser();
364 if (!empty($tagged_user)) {
369 return (Subscription::exists($this, $tagged) ||
370 Subscription::exists($tagged, $this));
371 } else if ($remote) {
377 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
381 $keypart = sprintf('profile:lists:%d', $this->id);
383 $idstr = self::cacheGet($keypart);
385 if ($idstr !== false) {
386 $ids = explode(',', $idstr);
388 $list = new Profile_list();
390 $list->selectAdd('id');
391 $list->tagger = $this->id;
392 $list->selectAdd('id as "cursor"');
395 $list->whereAdd('id > '.$since_id);
399 $list->whereAdd('id <= '.$max_id);
402 if($offset>=0 && !is_null($limit)) {
403 $list->limit($offset, $limit);
406 $list->orderBy('id DESC');
409 while ($list->fetch()) {
414 self::cacheSet($keypart, implode(',', $ids));
417 $showPrivate = (($auth_user instanceof User ||
418 $auth_user instanceof Profile) &&
419 $auth_user->id === $this->id);
423 foreach ($ids as $id) {
424 $list = Profile_list::staticGet('id', $id);
426 ($showPrivate || !$list->private)) {
428 if (!isset($list->cursor)) {
429 $list->cursor = $list->id;
436 return new ArrayWrapper($lists);
439 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
441 $lists = new Profile_list();
443 $tags = new Profile_tag();
444 $tags->tagged = $this->id;
446 $lists->joinAdd($tags);
448 #@fixme: postgres (round(date_part('epoch', my_date)))
449 $lists->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
451 if ($auth_user instanceof User || $auth_user instanceof Profile) {
452 $lists->whereAdd('( ( profile_list.private = false ) ' .
453 'OR ( profile_list.tagger = ' . $auth_user->id . ' AND ' .
454 'profile_list.private = true ) )');
456 $lists->private = false;
460 $lists->whereAdd('cursor > '.$since_id);
464 $lists->whereAdd('cursor <= '.$max_id);
467 if($offset>=0 && !is_null($limit)) {
468 $lists->limit($offset, $limit);
471 $lists->orderBy('profile_tag.modified DESC');
477 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
479 $tags = new Profile_list();
480 $tags->private = true;
481 $tags->tagger = $this->id;
484 $tags->whereAdd('id > '.$since_id);
488 $tags->whereAdd('id <= '.$max_id);
491 if($offset>=0 && !is_null($limit)) {
492 $tags->limit($offset, $limit);
495 $tags->orderBy('id DESC');
501 function hasLocalTags()
503 $tags = new Profile_tag();
505 $tags->joinAdd(array('tagger', 'user:id'));
506 $tags->whereAdd('tagged = '.$this->id);
507 $tags->whereAdd('tagger != '.$this->id);
512 return ($tags->N == 0) ? false : true;
515 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
517 $lists = new Profile_list();
518 $subs = new Profile_tag_subscription();
520 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
522 #@fixme: postgres (round(date_part('epoch', my_date)))
523 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
525 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
528 $lists->whereAdd('cursor > '.$since_id);
532 $lists->whereAdd('cursor <= '.$max_id);
535 if($offset>=0 && !is_null($limit)) {
536 $lists->limit($offset, $limit);
539 $lists->orderBy('"cursor" DESC');
546 * Request to join the given group.
547 * May throw exceptions on failure.
549 * @param User_group $group
550 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
552 function joinGroup(User_group $group)
555 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
556 $join = Group_join_queue::saveNew($this, $group);
558 if (Event::handle('StartJoinGroup', array($group, $this))) {
559 $join = Group_member::join($group->id, $this->id);
560 self::blow('profile:groups:%d', $this->id);
561 Event::handle('EndJoinGroup', array($group, $this));
565 // Send any applicable notifications...
572 * Leave a group that this profile is a member of.
574 * @param User_group $group
576 function leaveGroup(User_group $group)
578 if (Event::handle('StartLeaveGroup', array($group, $this))) {
579 Group_member::leave($group->id, $this->id);
580 self::blow('profile:groups:%d', $this->id);
581 Event::handle('EndLeaveGroup', array($group, $this));
585 function avatarUrl($size=AVATAR_PROFILE_SIZE)
587 $avatar = $this->getAvatar($size);
589 return $avatar->displayUrl();
591 return Avatar::defaultImage($size);
595 function getSubscriptions($offset=0, $limit=null)
597 $subs = Subscription::bySubscriber($this->id,
603 while ($subs->fetch()) {
604 $profile = Profile::staticGet($subs->subscribed);
606 $profiles[] = $profile;
610 return new ArrayWrapper($profiles);
613 function getSubscribers($offset=0, $limit=null)
615 $subs = Subscription::bySubscribed($this->id,
621 while ($subs->fetch()) {
622 $profile = Profile::staticGet($subs->subscriber);
624 $profiles[] = $profile;
628 return new ArrayWrapper($profiles);
631 function getTaggedSubscribers($tag)
634 'SELECT profile.* ' .
635 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
636 'ON profile.id = subscription.subscriber ' .
637 'AND profile.id = profile_tag.tagged ' .
638 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
639 'WHERE subscription.subscribed = %d ' .
640 'AND subscription.subscribed != subscription.subscriber ' .
641 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
642 'AND profile_list.private = false ' .
643 'ORDER BY subscription.created DESC';
645 $profile = new Profile();
648 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
650 while ($profile->fetch()) {
651 $tagged[] = clone($profile);
657 * Get pending subscribers, who have not yet been approved.
663 function getRequests($offset=0, $limit=null)
666 'SELECT profile.* ' .
667 'FROM profile JOIN subscription_queue '.
668 'ON profile.id = subscription_queue.subscriber ' .
669 'WHERE subscription_queue.subscribed = %d ' .
670 'ORDER BY subscription_queue.created DESC ';
672 if ($limit != null) {
673 if (common_config('db','type') == 'pgsql') {
674 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
676 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
680 $members = new Profile();
682 $members->query(sprintf($qry, $this->id));
686 function subscriptionCount()
688 $c = Cache::instance();
691 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
692 if (is_integer($cnt)) {
697 $sub = new Subscription();
698 $sub->subscriber = $this->id;
700 $cnt = (int) $sub->count('distinct subscribed');
702 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
705 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
711 function subscriberCount()
713 $c = Cache::instance();
715 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
716 if (is_integer($cnt)) {
721 $sub = new Subscription();
722 $sub->subscribed = $this->id;
723 $sub->whereAdd('subscriber != subscribed');
724 $cnt = (int) $sub->count('distinct subscriber');
727 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
734 * Is this profile subscribed to another profile?
736 * @param Profile $other
739 function isSubscribed($other)
741 return Subscription::exists($this, $other);
745 * Check if a pending subscription request is outstanding for this...
747 * @param Profile $other
750 function hasPendingSubscription($other)
752 return Subscription_queue::exists($this, $other);
756 * Are these two profiles subscribed to each other?
758 * @param Profile $other
761 function mutuallySubscribed($other)
763 return $this->isSubscribed($other) &&
764 $other->isSubscribed($this);
767 function hasFave($notice)
769 $fave = Fave::pkeyGet(array('user_id' => $this->id,
770 'notice_id' => $notice->id));
771 return ((is_null($fave)) ? false : true);
776 $c = Cache::instance();
778 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
779 if (is_integer($cnt)) {
785 $faves->user_id = $this->id;
786 $cnt = (int) $faves->count('notice_id');
789 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
795 function noticeCount()
797 $c = Cache::instance();
800 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
801 if (is_integer($cnt)) {
806 $notices = new Notice();
807 $notices->profile_id = $this->id;
808 $cnt = (int) $notices->count('distinct id');
811 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
817 function blowFavesCache()
819 $cache = Cache::instance();
821 // Faves don't happen chronologically, so we need to blow
823 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
824 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
825 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
826 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
828 $this->blowFaveCount();
831 function blowSubscriberCount()
833 $c = Cache::instance();
835 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
839 function blowSubscriptionCount()
841 $c = Cache::instance();
843 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
847 function blowFaveCount()
849 $c = Cache::instance();
851 $c->delete(Cache::key('profile:fave_count:'.$this->id));
855 function blowNoticeCount()
857 $c = Cache::instance();
859 $c->delete(Cache::key('profile:notice_count:'.$this->id));
863 static function maxBio()
865 $biolimit = common_config('profile', 'biolimit');
866 // null => use global limit (distinct from 0!)
867 if (is_null($biolimit)) {
868 $biolimit = common_config('site', 'textlimit');
873 static function bioTooLong($bio)
875 $biolimit = self::maxBio();
876 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
881 $this->_deleteNotices();
882 $this->_deleteSubscriptions();
883 $this->_deleteMessages();
884 $this->_deleteTags();
885 $this->_deleteBlocks();
886 $this->delete_avatars();
888 // Warning: delete() will run on the batch objects,
889 // not on individual objects.
890 $related = array('Reply',
893 Event::handle('ProfileDeleteRelated', array($this, &$related));
895 foreach ($related as $cls) {
897 $inst->profile_id = $this->id;
904 function _deleteNotices()
906 $notice = new Notice();
907 $notice->profile_id = $this->id;
909 if ($notice->find()) {
910 while ($notice->fetch()) {
911 $other = clone($notice);
917 function _deleteSubscriptions()
919 $sub = new Subscription();
920 $sub->subscriber = $this->id;
924 while ($sub->fetch()) {
925 $other = Profile::staticGet('id', $sub->subscribed);
929 if ($other->id == $this->id) {
932 Subscription::cancel($this, $other);
935 $subd = new Subscription();
936 $subd->subscribed = $this->id;
939 while ($subd->fetch()) {
940 $other = Profile::staticGet('id', $subd->subscriber);
944 if ($other->id == $this->id) {
947 Subscription::cancel($other, $this);
950 $self = new Subscription();
952 $self->subscriber = $this->id;
953 $self->subscribed = $this->id;
958 function _deleteMessages()
960 $msg = new Message();
961 $msg->from_profile = $this->id;
964 $msg = new Message();
965 $msg->to_profile = $this->id;
969 function _deleteTags()
971 $tag = new Profile_tag();
972 $tag->tagged = $this->id;
976 function _deleteBlocks()
978 $block = new Profile_block();
979 $block->blocked = $this->id;
982 $block = new Group_block();
983 $block->blocked = $this->id;
987 // XXX: identical to Notice::getLocation.
989 function getLocation()
993 if (!empty($this->location_id) && !empty($this->location_ns)) {
994 $location = Location::fromId($this->location_id, $this->location_ns);
997 if (is_null($location)) { // no ID, or Location::fromId() failed
998 if (!empty($this->lat) && !empty($this->lon)) {
999 $location = Location::fromLatLon($this->lat, $this->lon);
1003 if (is_null($location)) { // still haven't found it!
1004 if (!empty($this->location)) {
1005 $location = Location::fromName($this->location);
1012 function hasRole($name)
1015 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1016 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1018 $has_role = !empty($role);
1019 Event::handle('EndHasRole', array($this, $name, $has_role));
1024 function grantRole($name)
1026 if (Event::handle('StartGrantRole', array($this, $name))) {
1028 $role = new Profile_role();
1030 $role->profile_id = $this->id;
1031 $role->role = $name;
1032 $role->created = common_sql_now();
1034 $result = $role->insert();
1037 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1040 if ($name == 'owner') {
1041 User::blow('user:site_owner');
1044 Event::handle('EndGrantRole', array($this, $name));
1050 function revokeRole($name)
1052 if (Event::handle('StartRevokeRole', array($this, $name))) {
1054 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1058 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
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; does not exist.'),$name, $this->id));
1063 $result = $role->delete();
1066 common_log_db_error($role, 'DELETE', __FILE__);
1067 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1068 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1069 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1072 if ($name == 'owner') {
1073 User::blow('user:site_owner');
1076 Event::handle('EndRevokeRole', array($this, $name));
1082 function isSandboxed()
1084 return $this->hasRole(Profile_role::SANDBOXED);
1087 function isSilenced()
1089 return $this->hasRole(Profile_role::SILENCED);
1094 $this->grantRole(Profile_role::SANDBOXED);
1097 function unsandbox()
1099 $this->revokeRole(Profile_role::SANDBOXED);
1104 $this->grantRole(Profile_role::SILENCED);
1107 function unsilence()
1109 $this->revokeRole(Profile_role::SILENCED);
1113 * Does this user have the right to do X?
1115 * With our role-based authorization, this is merely a lookup for whether the user
1116 * has a particular role. The implementation currently uses a switch statement
1117 * to determine if the user has the pre-defined role to exercise the right. Future
1118 * implementations may allow per-site roles, and different mappings of roles to rights.
1120 * @param $right string Name of the right, usually a constant in class Right
1121 * @return boolean whether the user has the right in question
1123 function hasRight($right)
1127 if ($this->hasRole(Profile_role::DELETED)) {
1131 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1134 case Right::DELETEOTHERSNOTICE:
1135 case Right::MAKEGROUPADMIN:
1136 case Right::SANDBOXUSER:
1137 case Right::SILENCEUSER:
1138 case Right::DELETEUSER:
1139 case Right::DELETEGROUP:
1140 $result = $this->hasRole(Profile_role::MODERATOR);
1142 case Right::CONFIGURESITE:
1143 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1145 case Right::GRANTROLE:
1146 case Right::REVOKEROLE:
1147 $result = $this->hasRole(Profile_role::OWNER);
1149 case Right::NEWNOTICE:
1150 case Right::NEWMESSAGE:
1151 case Right::SUBSCRIBE:
1152 case Right::CREATEGROUP:
1153 $result = !$this->isSilenced();
1155 case Right::PUBLICNOTICE:
1156 case Right::EMAILONREPLY:
1157 case Right::EMAILONSUBSCRIBE:
1158 case Right::EMAILONFAVE:
1159 $result = !$this->isSandboxed();
1161 case Right::WEBLOGIN:
1162 $result = !$this->isSilenced();
1165 $result = !$this->isSilenced();
1167 case Right::BACKUPACCOUNT:
1168 $result = common_config('profile', 'backup');
1170 case Right::RESTOREACCOUNT:
1171 $result = common_config('profile', 'restore');
1173 case Right::DELETEACCOUNT:
1174 $result = common_config('profile', 'delete');
1176 case Right::MOVEACCOUNT:
1177 $result = common_config('profile', 'move');
1187 function hasRepeated($notice_id)
1189 // XXX: not really a pkey, but should work
1191 $notice = Memcached_DataObject::pkeyGet('Notice',
1192 array('profile_id' => $this->id,
1193 'repeat_of' => $notice_id));
1195 return !empty($notice);
1199 * Returns an XML string fragment with limited profile information
1200 * as an Atom <author> element.
1202 * Assumes that Atom has been previously set up as the base namespace.
1204 * @param Profile $cur the current authenticated user
1208 function asAtomAuthor($cur = null)
1210 $xs = new XMLStringer(true);
1212 $xs->elementStart('author');
1213 $xs->element('name', null, $this->nickname);
1214 $xs->element('uri', null, $this->getUri());
1217 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1218 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1219 $xs->element('statusnet:profile_info', $attrs, null);
1221 $xs->elementEnd('author');
1223 return $xs->getString();
1227 * Extra profile info for atom entries
1229 * Clients use some extra profile info in the atom stream.
1230 * This gives it to them.
1232 * @param User $cur Current user
1234 * @return array representation of <statusnet:profile_info> element or null
1237 function profileInfo($cur)
1239 $profileInfoAttr = array('local_id' => $this->id);
1242 // Whether the current user is a subscribed to this profile
1243 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1244 // Whether the current user is has blocked this profile
1245 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1248 return array('statusnet:profile_info', $profileInfoAttr, null);
1252 * Returns an XML string fragment with profile information as an
1253 * Activity Streams <activity:actor> element.
1255 * Assumes that 'activity' namespace has been previously defined.
1259 function asActivityActor()
1261 return $this->asActivityNoun('actor');
1265 * Returns an XML string fragment with profile information as an
1266 * Activity Streams noun object with the given element type.
1268 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1269 * previously defined.
1271 * @param string $element one of 'actor', 'subject', 'object', 'target'
1275 function asActivityNoun($element)
1277 $noun = ActivityObject::fromProfile($this);
1278 return $noun->asString('activity:' . $element);
1282 * Returns the best URI for a profile. Plugins may override.
1284 * @return string $uri
1290 // give plugins a chance to set the URI
1291 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1293 // check for a local user first
1294 $user = User::staticGet('id', $this->id);
1296 if (!empty($user)) {
1300 Event::handle('EndGetProfileUri', array($this, &$uri));
1306 function hasBlocked($other)
1308 $block = Profile_block::get($this->id, $other->id);
1310 if (empty($block)) {
1319 function getAtomFeed()
1323 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1324 $user = User::staticGet('id', $this->id);
1325 if (!empty($user)) {
1326 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1327 'format' => 'atom'));
1329 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1335 static function fromURI($uri)
1339 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1340 // Get a local user or remote (OMB 0.1) profile
1341 $user = User::staticGet('uri', $uri);
1342 if (!empty($user)) {
1343 $profile = $user->getProfile();
1345 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1351 function canRead(Notice $notice)
1353 if ($notice->scope & Notice::SITE_SCOPE) {
1354 $user = $this->getUser();
1360 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1361 $replies = $notice->getReplies();
1363 if (!in_array($this->id, $replies)) {
1364 $groups = $notice->getGroups();
1368 foreach ($groups as $group) {
1369 if ($this->isMember($group)) {
1381 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1382 $author = $notice->getProfile();
1383 if (!Subscription::exists($this, $author)) {
1391 static function current()
1393 $user = common_current_user();
1397 $profile = $user->getProfile();
1403 * Magic function called at serialize() time.
1405 * We use this to drop a couple process-specific references
1406 * from DB_DataObject which can cause trouble in future
1409 * @return array of variable names to include in serialization.
1414 $vars = parent::__sleep();
1415 $skip = array('_user', '_avatars');
1416 return array_diff($vars, $skip);
1419 static function fillAvatars(&$profiles, $width)
1422 foreach ($profiles as $profile) {
1423 $ids[] = $profile->id;
1426 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1427 'height' => $width));
1429 foreach ($profiles as $profile) {
1430 $profile->_fillAvatar($width, $avatars[$profile->id]);