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);
438 #@fixme: postgres (round(date_part('epoch', my_date)))
439 $lists->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
441 if ($auth_user instanceof User || $auth_user instanceof Profile) {
442 $lists->whereAdd('( ( profile_list.private = false ) ' .
443 'OR ( profile_list.tagger = ' . $auth_user->id . ' AND ' .
444 'profile_list.private = true ) )');
446 $lists->private = false;
450 $lists->whereAdd('cursor > '.$since_id);
454 $lists->whereAdd('cursor <= '.$max_id);
457 if($offset>=0 && !is_null($limit)) {
458 $lists->limit($offset, $limit);
461 $lists->orderBy('profile_tag.modified DESC');
467 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
469 $tags = new Profile_list();
470 $tags->private = true;
471 $tags->tagger = $this->id;
474 $tags->whereAdd('id > '.$since_id);
478 $tags->whereAdd('id <= '.$max_id);
481 if($offset>=0 && !is_null($limit)) {
482 $tags->limit($offset, $limit);
485 $tags->orderBy('id DESC');
491 function hasLocalTags()
493 $tags = new Profile_tag();
495 $tags->joinAdd(array('tagger', 'user:id'));
496 $tags->whereAdd('tagged = '.$this->id);
497 $tags->whereAdd('tagger != '.$this->id);
502 return ($tags->N == 0) ? false : true;
505 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
507 $lists = new Profile_list();
508 $subs = new Profile_tag_subscription();
510 $lists->joinAdd($subs);
511 #@fixme: postgres (round(date_part('epoch', my_date)))
512 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
514 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
517 $lists->whereAdd('cursor > '.$since_id);
521 $lists->whereAdd('cursor <= '.$max_id);
524 if($offset>=0 && !is_null($limit)) {
525 $lists->limit($offset, $limit);
528 $lists->orderBy('"cursor" DESC');
535 * Request to join the given group.
536 * May throw exceptions on failure.
538 * @param User_group $group
539 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
541 function joinGroup(User_group $group)
544 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
545 $join = Group_join_queue::saveNew($this, $group);
547 if (Event::handle('StartJoinGroup', array($group, $this))) {
548 $join = Group_member::join($group->id, $this->id);
549 self::blow('profile:groups:%d', $this->id);
550 Event::handle('EndJoinGroup', array($group, $this));
554 // Send any applicable notifications...
561 * Leave a group that this profile is a member of.
563 * @param User_group $group
565 function leaveGroup(User_group $group)
567 if (Event::handle('StartLeaveGroup', array($group, $this))) {
568 Group_member::leave($group->id, $this->id);
569 self::blow('profile:groups:%d', $this->id);
570 Event::handle('EndLeaveGroup', array($group, $this));
574 function avatarUrl($size=AVATAR_PROFILE_SIZE)
576 $avatar = $this->getAvatar($size);
578 return $avatar->displayUrl();
580 return Avatar::defaultImage($size);
584 function getSubscriptions($offset=0, $limit=null)
586 $subs = Subscription::bySubscriber($this->id,
592 while ($subs->fetch()) {
593 $profile = Profile::staticGet($subs->subscribed);
595 $profiles[] = $profile;
599 return new ArrayWrapper($profiles);
602 function getSubscribers($offset=0, $limit=null)
604 $subs = Subscription::bySubscribed($this->id,
610 while ($subs->fetch()) {
611 $profile = Profile::staticGet($subs->subscriber);
613 $profiles[] = $profile;
617 return new ArrayWrapper($profiles);
620 function getTaggedSubscribers($tag)
623 'SELECT profile.* ' .
624 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
625 'ON profile.id = subscription.subscriber ' .
626 'AND profile.id = profile_tag.tagged ' .
627 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
628 'WHERE subscription.subscribed = %d ' .
629 'AND subscription.subscribed != subscription.subscriber ' .
630 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
631 'AND profile_list.private = false ' .
632 'ORDER BY subscription.created DESC';
634 $profile = new Profile();
637 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
639 while ($profile->fetch()) {
640 $tagged[] = clone($profile);
646 * Get pending subscribers, who have not yet been approved.
652 function getRequests($offset=0, $limit=null)
655 'SELECT profile.* ' .
656 'FROM profile JOIN subscription_queue '.
657 'ON profile.id = subscription_queue.subscriber ' .
658 'WHERE subscription_queue.subscribed = %d ' .
659 'ORDER BY subscription_queue.created DESC ';
661 if ($limit != null) {
662 if (common_config('db','type') == 'pgsql') {
663 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
665 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
669 $members = new Profile();
671 $members->query(sprintf($qry, $this->id));
675 function subscriptionCount()
677 $c = Cache::instance();
680 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
681 if (is_integer($cnt)) {
686 $sub = new Subscription();
687 $sub->subscriber = $this->id;
689 $cnt = (int) $sub->count('distinct subscribed');
691 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
694 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
700 function subscriberCount()
702 $c = Cache::instance();
704 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
705 if (is_integer($cnt)) {
710 $sub = new Subscription();
711 $sub->subscribed = $this->id;
712 $sub->whereAdd('subscriber != subscribed');
713 $cnt = (int) $sub->count('distinct subscriber');
716 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
723 * Is this profile subscribed to another profile?
725 * @param Profile $other
728 function isSubscribed($other)
730 return Subscription::exists($this, $other);
734 * Check if a pending subscription request is outstanding for this...
736 * @param Profile $other
739 function hasPendingSubscription($other)
741 return Subscription_queue::exists($this, $other);
745 * Are these two profiles subscribed to each other?
747 * @param Profile $other
750 function mutuallySubscribed($other)
752 return $this->isSubscribed($other) &&
753 $other->isSubscribed($this);
756 function hasFave($notice)
758 $fave = Fave::pkeyGet(array('user_id' => $this->id,
759 'notice_id' => $notice->id));
760 return ((is_null($fave)) ? false : true);
765 $c = Cache::instance();
767 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
768 if (is_integer($cnt)) {
774 $faves->user_id = $this->id;
775 $cnt = (int) $faves->count('distinct notice_id');
778 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
784 function noticeCount()
786 $c = Cache::instance();
789 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
790 if (is_integer($cnt)) {
795 $notices = new Notice();
796 $notices->profile_id = $this->id;
797 $cnt = (int) $notices->count('distinct id');
800 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
806 function blowFavesCache()
808 $cache = Cache::instance();
810 // Faves don't happen chronologically, so we need to blow
812 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
813 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
814 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
815 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
817 $this->blowFaveCount();
820 function blowSubscriberCount()
822 $c = Cache::instance();
824 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
828 function blowSubscriptionCount()
830 $c = Cache::instance();
832 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
836 function blowFaveCount()
838 $c = Cache::instance();
840 $c->delete(Cache::key('profile:fave_count:'.$this->id));
844 function blowNoticeCount()
846 $c = Cache::instance();
848 $c->delete(Cache::key('profile:notice_count:'.$this->id));
852 static function maxBio()
854 $biolimit = common_config('profile', 'biolimit');
855 // null => use global limit (distinct from 0!)
856 if (is_null($biolimit)) {
857 $biolimit = common_config('site', 'textlimit');
862 static function bioTooLong($bio)
864 $biolimit = self::maxBio();
865 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
870 $this->_deleteNotices();
871 $this->_deleteSubscriptions();
872 $this->_deleteMessages();
873 $this->_deleteTags();
874 $this->_deleteBlocks();
875 $this->delete_avatars();
877 // Warning: delete() will run on the batch objects,
878 // not on individual objects.
879 $related = array('Reply',
882 Event::handle('ProfileDeleteRelated', array($this, &$related));
884 foreach ($related as $cls) {
886 $inst->profile_id = $this->id;
893 function _deleteNotices()
895 $notice = new Notice();
896 $notice->profile_id = $this->id;
898 if ($notice->find()) {
899 while ($notice->fetch()) {
900 $other = clone($notice);
906 function _deleteSubscriptions()
908 $sub = new Subscription();
909 $sub->subscriber = $this->id;
913 while ($sub->fetch()) {
914 $other = Profile::staticGet('id', $sub->subscribed);
918 if ($other->id == $this->id) {
921 Subscription::cancel($this, $other);
924 $subd = new Subscription();
925 $subd->subscribed = $this->id;
928 while ($subd->fetch()) {
929 $other = Profile::staticGet('id', $subd->subscriber);
933 if ($other->id == $this->id) {
936 Subscription::cancel($other, $this);
939 $self = new Subscription();
941 $self->subscriber = $this->id;
942 $self->subscribed = $this->id;
947 function _deleteMessages()
949 $msg = new Message();
950 $msg->from_profile = $this->id;
953 $msg = new Message();
954 $msg->to_profile = $this->id;
958 function _deleteTags()
960 $tag = new Profile_tag();
961 $tag->tagged = $this->id;
965 function _deleteBlocks()
967 $block = new Profile_block();
968 $block->blocked = $this->id;
971 $block = new Group_block();
972 $block->blocked = $this->id;
976 // XXX: identical to Notice::getLocation.
978 function getLocation()
982 if (!empty($this->location_id) && !empty($this->location_ns)) {
983 $location = Location::fromId($this->location_id, $this->location_ns);
986 if (is_null($location)) { // no ID, or Location::fromId() failed
987 if (!empty($this->lat) && !empty($this->lon)) {
988 $location = Location::fromLatLon($this->lat, $this->lon);
992 if (is_null($location)) { // still haven't found it!
993 if (!empty($this->location)) {
994 $location = Location::fromName($this->location);
1001 function hasRole($name)
1004 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1005 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1007 $has_role = !empty($role);
1008 Event::handle('EndHasRole', array($this, $name, $has_role));
1013 function grantRole($name)
1015 if (Event::handle('StartGrantRole', array($this, $name))) {
1017 $role = new Profile_role();
1019 $role->profile_id = $this->id;
1020 $role->role = $name;
1021 $role->created = common_sql_now();
1023 $result = $role->insert();
1026 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1029 if ($name == 'owner') {
1030 User::blow('user:site_owner');
1033 Event::handle('EndGrantRole', array($this, $name));
1039 function revokeRole($name)
1041 if (Event::handle('StartRevokeRole', array($this, $name))) {
1043 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1047 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1048 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1049 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1052 $result = $role->delete();
1055 common_log_db_error($role, 'DELETE', __FILE__);
1056 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1057 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1058 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1061 if ($name == 'owner') {
1062 User::blow('user:site_owner');
1065 Event::handle('EndRevokeRole', array($this, $name));
1071 function isSandboxed()
1073 return $this->hasRole(Profile_role::SANDBOXED);
1076 function isSilenced()
1078 return $this->hasRole(Profile_role::SILENCED);
1083 $this->grantRole(Profile_role::SANDBOXED);
1086 function unsandbox()
1088 $this->revokeRole(Profile_role::SANDBOXED);
1093 $this->grantRole(Profile_role::SILENCED);
1096 function unsilence()
1098 $this->revokeRole(Profile_role::SILENCED);
1102 * Does this user have the right to do X?
1104 * With our role-based authorization, this is merely a lookup for whether the user
1105 * has a particular role. The implementation currently uses a switch statement
1106 * to determine if the user has the pre-defined role to exercise the right. Future
1107 * implementations may allow per-site roles, and different mappings of roles to rights.
1109 * @param $right string Name of the right, usually a constant in class Right
1110 * @return boolean whether the user has the right in question
1112 function hasRight($right)
1116 if ($this->hasRole(Profile_role::DELETED)) {
1120 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1123 case Right::DELETEOTHERSNOTICE:
1124 case Right::MAKEGROUPADMIN:
1125 case Right::SANDBOXUSER:
1126 case Right::SILENCEUSER:
1127 case Right::DELETEUSER:
1128 case Right::DELETEGROUP:
1129 $result = $this->hasRole(Profile_role::MODERATOR);
1131 case Right::CONFIGURESITE:
1132 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1134 case Right::GRANTROLE:
1135 case Right::REVOKEROLE:
1136 $result = $this->hasRole(Profile_role::OWNER);
1138 case Right::NEWNOTICE:
1139 case Right::NEWMESSAGE:
1140 case Right::SUBSCRIBE:
1141 case Right::CREATEGROUP:
1142 $result = !$this->isSilenced();
1144 case Right::PUBLICNOTICE:
1145 case Right::EMAILONREPLY:
1146 case Right::EMAILONSUBSCRIBE:
1147 case Right::EMAILONFAVE:
1148 $result = !$this->isSandboxed();
1150 case Right::WEBLOGIN:
1151 $result = !$this->isSilenced();
1154 $result = !$this->isSilenced();
1156 case Right::BACKUPACCOUNT:
1157 $result = common_config('profile', 'backup');
1159 case Right::RESTOREACCOUNT:
1160 $result = common_config('profile', 'restore');
1162 case Right::DELETEACCOUNT:
1163 $result = common_config('profile', 'delete');
1165 case Right::MOVEACCOUNT:
1166 $result = common_config('profile', 'move');
1176 function hasRepeated($notice_id)
1178 // XXX: not really a pkey, but should work
1180 $notice = Memcached_DataObject::pkeyGet('Notice',
1181 array('profile_id' => $this->id,
1182 'repeat_of' => $notice_id));
1184 return !empty($notice);
1188 * Returns an XML string fragment with limited profile information
1189 * as an Atom <author> element.
1191 * Assumes that Atom has been previously set up as the base namespace.
1193 * @param Profile $cur the current authenticated user
1197 function asAtomAuthor($cur = null)
1199 $xs = new XMLStringer(true);
1201 $xs->elementStart('author');
1202 $xs->element('name', null, $this->nickname);
1203 $xs->element('uri', null, $this->getUri());
1206 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1207 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1208 $xs->element('statusnet:profile_info', $attrs, null);
1210 $xs->elementEnd('author');
1212 return $xs->getString();
1216 * Extra profile info for atom entries
1218 * Clients use some extra profile info in the atom stream.
1219 * This gives it to them.
1221 * @param User $cur Current user
1223 * @return array representation of <statusnet:profile_info> element or null
1226 function profileInfo($cur)
1228 $profileInfoAttr = array('local_id' => $this->id);
1231 // Whether the current user is a subscribed to this profile
1232 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1233 // Whether the current user is has blocked this profile
1234 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1237 return array('statusnet:profile_info', $profileInfoAttr, null);
1241 * Returns an XML string fragment with profile information as an
1242 * Activity Streams <activity:actor> element.
1244 * Assumes that 'activity' namespace has been previously defined.
1248 function asActivityActor()
1250 return $this->asActivityNoun('actor');
1254 * Returns an XML string fragment with profile information as an
1255 * Activity Streams noun object with the given element type.
1257 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1258 * previously defined.
1260 * @param string $element one of 'actor', 'subject', 'object', 'target'
1264 function asActivityNoun($element)
1266 $noun = ActivityObject::fromProfile($this);
1267 return $noun->asString('activity:' . $element);
1271 * Returns the best URI for a profile. Plugins may override.
1273 * @return string $uri
1279 // give plugins a chance to set the URI
1280 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1282 // check for a local user first
1283 $user = User::staticGet('id', $this->id);
1285 if (!empty($user)) {
1289 Event::handle('EndGetProfileUri', array($this, &$uri));
1295 function hasBlocked($other)
1297 $block = Profile_block::get($this->id, $other->id);
1299 if (empty($block)) {
1308 function getAtomFeed()
1312 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1313 $user = User::staticGet('id', $this->id);
1314 if (!empty($user)) {
1315 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1316 'format' => 'atom'));
1318 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1324 static function fromURI($uri)
1328 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1329 // Get a local user or remote (OMB 0.1) profile
1330 $user = User::staticGet('uri', $uri);
1331 if (!empty($user)) {
1332 $profile = $user->getProfile();
1334 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1340 function canRead(Notice $notice)
1342 if ($notice->scope & Notice::SITE_SCOPE) {
1343 $user = $this->getUser();
1349 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1350 $replies = $notice->getReplies();
1352 if (!in_array($this->id, $replies)) {
1353 $groups = $notice->getGroups();
1357 foreach ($groups as $group) {
1358 if ($this->isMember($group)) {
1370 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1371 $author = $notice->getProfile();
1372 if (!Subscription::exists($this, $author)) {
1380 static function current()
1382 $user = common_current_user();
1386 $profile = $user->getProfile();
1392 * Magic function called at serialize() time.
1394 * We use this to drop a couple process-specific references
1395 * from DB_DataObject which can cause trouble in future
1398 * @return array of variable names to include in serialization.
1403 $vars = parent::__sleep();
1404 $skip = array('_user', '_avatars');
1405 return array_diff($vars, $skip);
1408 static function fillAvatars(&$profiles, $width)
1411 foreach ($profiles as $profile) {
1412 $ids[] = $profile->id;
1415 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1416 'height' => $width));
1418 foreach ($profiles as $profile) {
1419 $profile->_fillAvatar($width, $avatars[$profile->id]);