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'),
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);
103 function getAvatar($width, $height=null)
105 if (is_null($height)) {
109 if (!isset($this->_avatars)) {
110 $this->_avatars = array();
113 if (array_key_exists($width, $this->_avatars)) {
114 return $this->_avatars[$width];
119 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
120 $avatar = Avatar::pkeyGet(array('profile_id' => $this->id,
122 'height' => $height));
123 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
126 $this->_avatars[$width] = $avatar;
131 function _fillAvatar($width, $avatar)
133 $this->_avatars[$width] = $avatar;
136 function getOriginalAvatar()
138 $avatar = DB_DataObject::factory('avatar');
139 $avatar->profile_id = $this->id;
140 $avatar->original = true;
141 if ($avatar->find(true)) {
148 function setOriginal($filename)
150 $imagefile = new ImageFile($this->id, Avatar::path($filename));
152 $avatar = new Avatar();
153 $avatar->profile_id = $this->id;
154 $avatar->width = $imagefile->width;
155 $avatar->height = $imagefile->height;
156 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
157 $avatar->filename = $filename;
158 $avatar->original = true;
159 $avatar->url = Avatar::url($filename);
160 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
162 // XXX: start a transaction here
164 if (!$this->delete_avatars() || !$avatar->insert()) {
165 @unlink(Avatar::path($filename));
169 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
170 // We don't do a scaled one if original is our scaled size
171 if (!($avatar->width == $size && $avatar->height == $size)) {
172 $scaled_filename = $imagefile->resize($size);
174 //$scaled = DB_DataObject::factory('avatar');
175 $scaled = new Avatar();
176 $scaled->profile_id = $this->id;
177 $scaled->width = $size;
178 $scaled->height = $size;
179 $scaled->original = false;
180 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
181 $scaled->filename = $scaled_filename;
182 $scaled->url = Avatar::url($scaled_filename);
183 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
185 if (!$scaled->insert()) {
195 * Delete attached avatars for this user from the database and filesystem.
196 * This should be used instead of a batch delete() to ensure that files
197 * get removed correctly.
199 * @param boolean $original true to delete only the original-size file
202 function delete_avatars($original=true)
204 $avatar = new Avatar();
205 $avatar->profile_id = $this->id;
207 while ($avatar->fetch()) {
208 if ($avatar->original) {
209 if ($original == false) {
219 * Gets either the full name (if filled) or the nickname.
223 function getBestName()
225 return ($this->fullname) ? $this->fullname : $this->nickname;
229 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
230 * if no fullname is provided.
234 function getFancyName()
236 if ($this->fullname) {
237 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
238 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
240 return $this->nickname;
245 * Get the most recent notice posted by this user, if any.
247 * @return mixed Notice or null
249 function getCurrentNotice()
251 $notice = $this->getNotices(0, 1);
253 if ($notice->fetch()) {
254 if ($notice instanceof ArrayWrapper) {
255 // hack for things trying to work with single notices
256 return $notice->_items[0];
264 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
266 $stream = new TaggedProfileNoticeStream($this, $tag);
268 return $stream->getNotices($offset, $limit, $since_id, $max_id);
271 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
273 $stream = new ProfileNoticeStream($this);
275 return $stream->getNotices($offset, $limit, $since_id, $max_id);
278 function isMember($group)
280 $groups = $this->getGroups(0, null);
281 $gs = $groups->fetchAll();
282 foreach ($gs as $g) {
283 if ($group->id == $g->id) {
290 function isAdmin($group)
292 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
293 'group_id' => $group->id));
294 return (!empty($gm) && $gm->is_admin);
297 function isPendingMember($group)
299 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
300 'group_id' => $group->id));
301 return !empty($request);
304 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
308 $keypart = sprintf('profile:groups:%d', $this->id);
310 $idstring = self::cacheGet($keypart);
312 if ($idstring !== false) {
313 $ids = explode(',', $idstring);
315 $gm = new Group_member();
317 $gm->profile_id = $this->id;
320 while ($gm->fetch()) {
321 $ids[] = $gm->group_id;
325 self::cacheSet($keypart, implode(',', $ids));
328 return User_group::multiGet('id', $ids);
331 function isTagged($peopletag)
333 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
334 'tagged' => $this->id,
335 'tag' => $peopletag->tag));
339 function canTag($tagged)
341 if (empty($tagged)) {
345 if ($tagged->id == $this->id) {
349 $all = common_config('peopletag', 'allow_tagging', 'all');
350 $local = common_config('peopletag', 'allow_tagging', 'local');
351 $remote = common_config('peopletag', 'allow_tagging', 'remote');
352 $subs = common_config('peopletag', 'allow_tagging', 'subs');
358 $tagged_user = $tagged->getUser();
359 if (!empty($tagged_user)) {
364 return (Subscription::exists($this, $tagged) ||
365 Subscription::exists($tagged, $this));
366 } else if ($remote) {
372 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
376 $keypart = sprintf('profile:lists:%d', $this->id);
378 $idstr = self::cacheGet($keypart);
380 if ($idstr !== false) {
381 $ids = explode(',', $idstr);
383 $list = new Profile_list();
385 $list->selectAdd('id');
386 $list->tagger = $this->id;
387 $list->selectAdd('id as "cursor"');
390 $list->whereAdd('id > '.$since_id);
394 $list->whereAdd('id <= '.$max_id);
397 if($offset>=0 && !is_null($limit)) {
398 $list->limit($offset, $limit);
401 $list->orderBy('id DESC');
404 while ($list->fetch()) {
409 self::cacheSet($keypart, implode(',', $ids));
412 $showPrivate = (($auth_user instanceof User ||
413 $auth_user instanceof Profile) &&
414 $auth_user->id === $this->id);
418 foreach ($ids as $id) {
419 $list = Profile_list::staticGet('id', $id);
421 ($showPrivate || !$list->private)) {
423 if (!isset($list->cursor)) {
424 $list->cursor = $list->id;
431 return new ArrayWrapper($lists);
434 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
436 $lists = new Profile_list();
438 $tags = new Profile_tag();
439 $tags->tagged = $this->id;
441 $lists->joinAdd($tags);
443 #@fixme: postgres (round(date_part('epoch', my_date)))
444 $lists->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
446 if ($auth_user instanceof User || $auth_user instanceof Profile) {
447 $lists->whereAdd('( ( profile_list.private = false ) ' .
448 'OR ( profile_list.tagger = ' . $auth_user->id . ' AND ' .
449 'profile_list.private = true ) )');
451 $lists->private = false;
455 $lists->whereAdd('cursor > '.$since_id);
459 $lists->whereAdd('cursor <= '.$max_id);
462 if($offset>=0 && !is_null($limit)) {
463 $lists->limit($offset, $limit);
466 $lists->orderBy('profile_tag.modified DESC');
472 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
474 $tags = new Profile_list();
475 $tags->private = true;
476 $tags->tagger = $this->id;
479 $tags->whereAdd('id > '.$since_id);
483 $tags->whereAdd('id <= '.$max_id);
486 if($offset>=0 && !is_null($limit)) {
487 $tags->limit($offset, $limit);
490 $tags->orderBy('id DESC');
496 function hasLocalTags()
498 $tags = new Profile_tag();
500 $tags->joinAdd(array('tagger', 'user:id'));
501 $tags->whereAdd('tagged = '.$this->id);
502 $tags->whereAdd('tagger != '.$this->id);
507 return ($tags->N == 0) ? false : true;
510 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
512 $lists = new Profile_list();
513 $subs = new Profile_tag_subscription();
515 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
517 #@fixme: postgres (round(date_part('epoch', my_date)))
518 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
520 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
523 $lists->whereAdd('cursor > '.$since_id);
527 $lists->whereAdd('cursor <= '.$max_id);
530 if($offset>=0 && !is_null($limit)) {
531 $lists->limit($offset, $limit);
534 $lists->orderBy('"cursor" DESC');
541 * Request to join the given group.
542 * May throw exceptions on failure.
544 * @param User_group $group
545 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
547 function joinGroup(User_group $group)
550 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
551 $join = Group_join_queue::saveNew($this, $group);
553 if (Event::handle('StartJoinGroup', array($group, $this))) {
554 $join = Group_member::join($group->id, $this->id);
555 self::blow('profile:groups:%d', $this->id);
556 Event::handle('EndJoinGroup', array($group, $this));
560 // Send any applicable notifications...
567 * Leave a group that this profile is a member of.
569 * @param User_group $group
571 function leaveGroup(User_group $group)
573 if (Event::handle('StartLeaveGroup', array($group, $this))) {
574 Group_member::leave($group->id, $this->id);
575 self::blow('profile:groups:%d', $this->id);
576 Event::handle('EndLeaveGroup', array($group, $this));
580 function avatarUrl($size=AVATAR_PROFILE_SIZE)
582 $avatar = $this->getAvatar($size);
584 return $avatar->displayUrl();
586 return Avatar::defaultImage($size);
590 function getSubscriptions($offset=0, $limit=null)
592 $subs = Subscription::bySubscriber($this->id,
598 while ($subs->fetch()) {
599 $profile = Profile::staticGet($subs->subscribed);
601 $profiles[] = $profile;
605 return new ArrayWrapper($profiles);
608 function getSubscribers($offset=0, $limit=null)
610 $subs = Subscription::bySubscribed($this->id,
616 while ($subs->fetch()) {
617 $profile = Profile::staticGet($subs->subscriber);
619 $profiles[] = $profile;
623 return new ArrayWrapper($profiles);
626 function getTaggedSubscribers($tag)
629 'SELECT profile.* ' .
630 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
631 'ON profile.id = subscription.subscriber ' .
632 'AND profile.id = profile_tag.tagged ' .
633 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
634 'WHERE subscription.subscribed = %d ' .
635 'AND subscription.subscribed != subscription.subscriber ' .
636 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
637 'AND profile_list.private = false ' .
638 'ORDER BY subscription.created DESC';
640 $profile = new Profile();
643 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
645 while ($profile->fetch()) {
646 $tagged[] = clone($profile);
652 * Get pending subscribers, who have not yet been approved.
658 function getRequests($offset=0, $limit=null)
661 'SELECT profile.* ' .
662 'FROM profile JOIN subscription_queue '.
663 'ON profile.id = subscription_queue.subscriber ' .
664 'WHERE subscription_queue.subscribed = %d ' .
665 'ORDER BY subscription_queue.created DESC ';
667 if ($limit != null) {
668 if (common_config('db','type') == 'pgsql') {
669 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
671 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
675 $members = new Profile();
677 $members->query(sprintf($qry, $this->id));
681 function subscriptionCount()
683 $c = Cache::instance();
686 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
687 if (is_integer($cnt)) {
692 $sub = new Subscription();
693 $sub->subscriber = $this->id;
695 $cnt = (int) $sub->count('distinct subscribed');
697 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
700 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
706 function subscriberCount()
708 $c = Cache::instance();
710 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
711 if (is_integer($cnt)) {
716 $sub = new Subscription();
717 $sub->subscribed = $this->id;
718 $sub->whereAdd('subscriber != subscribed');
719 $cnt = (int) $sub->count('distinct subscriber');
722 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
729 * Is this profile subscribed to another profile?
731 * @param Profile $other
734 function isSubscribed($other)
736 return Subscription::exists($this, $other);
740 * Check if a pending subscription request is outstanding for this...
742 * @param Profile $other
745 function hasPendingSubscription($other)
747 return Subscription_queue::exists($this, $other);
751 * Are these two profiles subscribed to each other?
753 * @param Profile $other
756 function mutuallySubscribed($other)
758 return $this->isSubscribed($other) &&
759 $other->isSubscribed($this);
762 function hasFave($notice)
764 $fave = Fave::pkeyGet(array('user_id' => $this->id,
765 'notice_id' => $notice->id));
766 return ((is_null($fave)) ? false : true);
771 $c = Cache::instance();
773 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
774 if (is_integer($cnt)) {
780 $faves->user_id = $this->id;
781 $cnt = (int) $faves->count('notice_id');
784 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
790 function noticeCount()
792 $c = Cache::instance();
795 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
796 if (is_integer($cnt)) {
801 $notices = new Notice();
802 $notices->profile_id = $this->id;
803 $cnt = (int) $notices->count('distinct id');
806 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
812 function blowFavesCache()
814 $cache = Cache::instance();
816 // Faves don't happen chronologically, so we need to blow
818 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
819 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
820 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
821 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
823 $this->blowFaveCount();
826 function blowSubscriberCount()
828 $c = Cache::instance();
830 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
834 function blowSubscriptionCount()
836 $c = Cache::instance();
838 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
842 function blowFaveCount()
844 $c = Cache::instance();
846 $c->delete(Cache::key('profile:fave_count:'.$this->id));
850 function blowNoticeCount()
852 $c = Cache::instance();
854 $c->delete(Cache::key('profile:notice_count:'.$this->id));
858 static function maxBio()
860 $biolimit = common_config('profile', 'biolimit');
861 // null => use global limit (distinct from 0!)
862 if (is_null($biolimit)) {
863 $biolimit = common_config('site', 'textlimit');
868 static function bioTooLong($bio)
870 $biolimit = self::maxBio();
871 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
876 $this->_deleteNotices();
877 $this->_deleteSubscriptions();
878 $this->_deleteMessages();
879 $this->_deleteTags();
880 $this->_deleteBlocks();
881 $this->delete_avatars();
883 // Warning: delete() will run on the batch objects,
884 // not on individual objects.
885 $related = array('Reply',
888 Event::handle('ProfileDeleteRelated', array($this, &$related));
890 foreach ($related as $cls) {
892 $inst->profile_id = $this->id;
899 function _deleteNotices()
901 $notice = new Notice();
902 $notice->profile_id = $this->id;
904 if ($notice->find()) {
905 while ($notice->fetch()) {
906 $other = clone($notice);
912 function _deleteSubscriptions()
914 $sub = new Subscription();
915 $sub->subscriber = $this->id;
919 while ($sub->fetch()) {
920 $other = Profile::staticGet('id', $sub->subscribed);
924 if ($other->id == $this->id) {
927 Subscription::cancel($this, $other);
930 $subd = new Subscription();
931 $subd->subscribed = $this->id;
934 while ($subd->fetch()) {
935 $other = Profile::staticGet('id', $subd->subscriber);
939 if ($other->id == $this->id) {
942 Subscription::cancel($other, $this);
945 $self = new Subscription();
947 $self->subscriber = $this->id;
948 $self->subscribed = $this->id;
953 function _deleteMessages()
955 $msg = new Message();
956 $msg->from_profile = $this->id;
959 $msg = new Message();
960 $msg->to_profile = $this->id;
964 function _deleteTags()
966 $tag = new Profile_tag();
967 $tag->tagged = $this->id;
971 function _deleteBlocks()
973 $block = new Profile_block();
974 $block->blocked = $this->id;
977 $block = new Group_block();
978 $block->blocked = $this->id;
982 // XXX: identical to Notice::getLocation.
984 function getLocation()
988 if (!empty($this->location_id) && !empty($this->location_ns)) {
989 $location = Location::fromId($this->location_id, $this->location_ns);
992 if (is_null($location)) { // no ID, or Location::fromId() failed
993 if (!empty($this->lat) && !empty($this->lon)) {
994 $location = Location::fromLatLon($this->lat, $this->lon);
998 if (is_null($location)) { // still haven't found it!
999 if (!empty($this->location)) {
1000 $location = Location::fromName($this->location);
1007 function hasRole($name)
1010 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1011 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1013 $has_role = !empty($role);
1014 Event::handle('EndHasRole', array($this, $name, $has_role));
1019 function grantRole($name)
1021 if (Event::handle('StartGrantRole', array($this, $name))) {
1023 $role = new Profile_role();
1025 $role->profile_id = $this->id;
1026 $role->role = $name;
1027 $role->created = common_sql_now();
1029 $result = $role->insert();
1032 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1035 if ($name == 'owner') {
1036 User::blow('user:site_owner');
1039 Event::handle('EndGrantRole', array($this, $name));
1045 function revokeRole($name)
1047 if (Event::handle('StartRevokeRole', array($this, $name))) {
1049 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1053 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1054 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1055 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1058 $result = $role->delete();
1061 common_log_db_error($role, 'DELETE', __FILE__);
1062 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1063 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1064 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1067 if ($name == 'owner') {
1068 User::blow('user:site_owner');
1071 Event::handle('EndRevokeRole', array($this, $name));
1077 function isSandboxed()
1079 return $this->hasRole(Profile_role::SANDBOXED);
1082 function isSilenced()
1084 return $this->hasRole(Profile_role::SILENCED);
1089 $this->grantRole(Profile_role::SANDBOXED);
1092 function unsandbox()
1094 $this->revokeRole(Profile_role::SANDBOXED);
1099 $this->grantRole(Profile_role::SILENCED);
1102 function unsilence()
1104 $this->revokeRole(Profile_role::SILENCED);
1108 * Does this user have the right to do X?
1110 * With our role-based authorization, this is merely a lookup for whether the user
1111 * has a particular role. The implementation currently uses a switch statement
1112 * to determine if the user has the pre-defined role to exercise the right. Future
1113 * implementations may allow per-site roles, and different mappings of roles to rights.
1115 * @param $right string Name of the right, usually a constant in class Right
1116 * @return boolean whether the user has the right in question
1118 function hasRight($right)
1122 if ($this->hasRole(Profile_role::DELETED)) {
1126 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1129 case Right::DELETEOTHERSNOTICE:
1130 case Right::MAKEGROUPADMIN:
1131 case Right::SANDBOXUSER:
1132 case Right::SILENCEUSER:
1133 case Right::DELETEUSER:
1134 case Right::DELETEGROUP:
1135 $result = $this->hasRole(Profile_role::MODERATOR);
1137 case Right::CONFIGURESITE:
1138 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1140 case Right::GRANTROLE:
1141 case Right::REVOKEROLE:
1142 $result = $this->hasRole(Profile_role::OWNER);
1144 case Right::NEWNOTICE:
1145 case Right::NEWMESSAGE:
1146 case Right::SUBSCRIBE:
1147 case Right::CREATEGROUP:
1148 $result = !$this->isSilenced();
1150 case Right::PUBLICNOTICE:
1151 case Right::EMAILONREPLY:
1152 case Right::EMAILONSUBSCRIBE:
1153 case Right::EMAILONFAVE:
1154 $result = !$this->isSandboxed();
1156 case Right::WEBLOGIN:
1157 $result = !$this->isSilenced();
1160 $result = !$this->isSilenced();
1162 case Right::BACKUPACCOUNT:
1163 $result = common_config('profile', 'backup');
1165 case Right::RESTOREACCOUNT:
1166 $result = common_config('profile', 'restore');
1168 case Right::DELETEACCOUNT:
1169 $result = common_config('profile', 'delete');
1171 case Right::MOVEACCOUNT:
1172 $result = common_config('profile', 'move');
1182 function hasRepeated($notice_id)
1184 // XXX: not really a pkey, but should work
1186 $notice = Memcached_DataObject::pkeyGet('Notice',
1187 array('profile_id' => $this->id,
1188 'repeat_of' => $notice_id));
1190 return !empty($notice);
1194 * Returns an XML string fragment with limited profile information
1195 * as an Atom <author> element.
1197 * Assumes that Atom has been previously set up as the base namespace.
1199 * @param Profile $cur the current authenticated user
1203 function asAtomAuthor($cur = null)
1205 $xs = new XMLStringer(true);
1207 $xs->elementStart('author');
1208 $xs->element('name', null, $this->nickname);
1209 $xs->element('uri', null, $this->getUri());
1212 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1213 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1214 $xs->element('statusnet:profile_info', $attrs, null);
1216 $xs->elementEnd('author');
1218 return $xs->getString();
1222 * Extra profile info for atom entries
1224 * Clients use some extra profile info in the atom stream.
1225 * This gives it to them.
1227 * @param User $cur Current user
1229 * @return array representation of <statusnet:profile_info> element or null
1232 function profileInfo($cur)
1234 $profileInfoAttr = array('local_id' => $this->id);
1237 // Whether the current user is a subscribed to this profile
1238 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1239 // Whether the current user is has blocked this profile
1240 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1243 return array('statusnet:profile_info', $profileInfoAttr, null);
1247 * Returns an XML string fragment with profile information as an
1248 * Activity Streams <activity:actor> element.
1250 * Assumes that 'activity' namespace has been previously defined.
1254 function asActivityActor()
1256 return $this->asActivityNoun('actor');
1260 * Returns an XML string fragment with profile information as an
1261 * Activity Streams noun object with the given element type.
1263 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1264 * previously defined.
1266 * @param string $element one of 'actor', 'subject', 'object', 'target'
1270 function asActivityNoun($element)
1272 $noun = ActivityObject::fromProfile($this);
1273 return $noun->asString('activity:' . $element);
1277 * Returns the best URI for a profile. Plugins may override.
1279 * @return string $uri
1285 // give plugins a chance to set the URI
1286 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1288 // check for a local user first
1289 $user = User::staticGet('id', $this->id);
1291 if (!empty($user)) {
1295 Event::handle('EndGetProfileUri', array($this, &$uri));
1301 function hasBlocked($other)
1303 $block = Profile_block::get($this->id, $other->id);
1305 if (empty($block)) {
1314 function getAtomFeed()
1318 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1319 $user = User::staticGet('id', $this->id);
1320 if (!empty($user)) {
1321 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1322 'format' => 'atom'));
1324 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1330 static function fromURI($uri)
1334 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1335 // Get a local user or remote (OMB 0.1) profile
1336 $user = User::staticGet('uri', $uri);
1337 if (!empty($user)) {
1338 $profile = $user->getProfile();
1340 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1346 function canRead(Notice $notice)
1348 if ($notice->scope & Notice::SITE_SCOPE) {
1349 $user = $this->getUser();
1355 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1356 $replies = $notice->getReplies();
1358 if (!in_array($this->id, $replies)) {
1359 $groups = $notice->getGroups();
1363 foreach ($groups as $group) {
1364 if ($this->isMember($group)) {
1376 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1377 $author = $notice->getProfile();
1378 if (!Subscription::exists($this, $author)) {
1386 static function current()
1388 $user = common_current_user();
1392 $profile = $user->getProfile();
1398 * Magic function called at serialize() time.
1400 * We use this to drop a couple process-specific references
1401 * from DB_DataObject which can cause trouble in future
1404 * @return array of variable names to include in serialization.
1409 $vars = parent::__sleep();
1410 $skip = array('_user', '_avatars');
1411 return array_diff($vars, $skip);
1414 static function fillAvatars(&$profiles, $width)
1417 foreach ($profiles as $profile) {
1418 $ids[] = $profile->id;
1421 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1422 'height' => $width));
1424 foreach ($profiles as $profile) {
1425 $profile->_fillAvatar($width, $avatars[$profile->id]);