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);
440 * Get tags that other people put on this profile, in reverse-chron order
442 * @param (Profile|User) $auth_user Authorized user (used for privacy)
443 * @param int $offset Offset from latest
444 * @param int $limit Max number to get
445 * @param datetime $since_id max date
446 * @param datetime $max_id min date
448 * @return Profile_list resulting lists
451 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
453 $list = new Profile_list();
455 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
456 'from profile_tag join profile_list '.
457 'on (profile_tag.tagger = profile_list.tagger ' .
458 ' and profile_tag.tag = profile_list.tag) ' .
459 'where profile_tag.tagged = %d ',
463 if ($auth_user instanceof User || $auth_user instanceof Profile) {
464 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
465 'OR ( profile_list.tagger = %d AND ' .
466 'profile_list.private = true ) )',
469 $qry .= 'AND profile_list.private = 0 ';
473 $qry .= sprintf('AND (cursor > %d) ', $since_id);
477 $qry .= sprintf('AND (cursor < %d) ', $max_id);
480 $qry .= 'ORDER BY profile_tag.modified DESC ';
482 if ($offset >= 0 && !is_null($limit)) {
483 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
490 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
492 $tags = new Profile_list();
493 $tags->private = true;
494 $tags->tagger = $this->id;
497 $tags->whereAdd('id > '.$since_id);
501 $tags->whereAdd('id <= '.$max_id);
504 if($offset>=0 && !is_null($limit)) {
505 $tags->limit($offset, $limit);
508 $tags->orderBy('id DESC');
514 function hasLocalTags()
516 $tags = new Profile_tag();
518 $tags->joinAdd(array('tagger', 'user:id'));
519 $tags->whereAdd('tagged = '.$this->id);
520 $tags->whereAdd('tagger != '.$this->id);
525 return ($tags->N == 0) ? false : true;
528 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
530 $lists = new Profile_list();
531 $subs = new Profile_tag_subscription();
533 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
535 #@fixme: postgres (round(date_part('epoch', my_date)))
536 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
538 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
541 $lists->whereAdd('cursor > '.$since_id);
545 $lists->whereAdd('cursor <= '.$max_id);
548 if($offset>=0 && !is_null($limit)) {
549 $lists->limit($offset, $limit);
552 $lists->orderBy('"cursor" DESC');
559 * Request to join the given group.
560 * May throw exceptions on failure.
562 * @param User_group $group
563 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
565 function joinGroup(User_group $group)
568 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
569 $join = Group_join_queue::saveNew($this, $group);
571 if (Event::handle('StartJoinGroup', array($group, $this))) {
572 $join = Group_member::join($group->id, $this->id);
573 self::blow('profile:groups:%d', $this->id);
574 Event::handle('EndJoinGroup', array($group, $this));
578 // Send any applicable notifications...
585 * Leave a group that this profile is a member of.
587 * @param User_group $group
589 function leaveGroup(User_group $group)
591 if (Event::handle('StartLeaveGroup', array($group, $this))) {
592 Group_member::leave($group->id, $this->id);
593 self::blow('profile:groups:%d', $this->id);
594 Event::handle('EndLeaveGroup', array($group, $this));
598 function avatarUrl($size=AVATAR_PROFILE_SIZE)
600 $avatar = $this->getAvatar($size);
602 return $avatar->displayUrl();
604 return Avatar::defaultImage($size);
608 function getSubscriptions($offset=0, $limit=null)
610 $subs = Subscription::bySubscriber($this->id,
616 while ($subs->fetch()) {
617 $profile = Profile::staticGet($subs->subscribed);
619 $profiles[] = $profile;
623 return new ArrayWrapper($profiles);
626 function getSubscribers($offset=0, $limit=null)
628 $subs = Subscription::bySubscribed($this->id,
634 while ($subs->fetch()) {
635 $profile = Profile::staticGet($subs->subscriber);
637 $profiles[] = $profile;
641 return new ArrayWrapper($profiles);
644 function getTaggedSubscribers($tag)
647 'SELECT profile.* ' .
648 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
649 'ON profile.id = subscription.subscriber ' .
650 'AND profile.id = profile_tag.tagged ' .
651 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
652 'WHERE subscription.subscribed = %d ' .
653 'AND subscription.subscribed != subscription.subscriber ' .
654 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
655 'AND profile_list.private = false ' .
656 'ORDER BY subscription.created DESC';
658 $profile = new Profile();
661 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
663 while ($profile->fetch()) {
664 $tagged[] = clone($profile);
670 * Get pending subscribers, who have not yet been approved.
676 function getRequests($offset=0, $limit=null)
679 'SELECT profile.* ' .
680 'FROM profile JOIN subscription_queue '.
681 'ON profile.id = subscription_queue.subscriber ' .
682 'WHERE subscription_queue.subscribed = %d ' .
683 'ORDER BY subscription_queue.created DESC ';
685 if ($limit != null) {
686 if (common_config('db','type') == 'pgsql') {
687 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
689 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
693 $members = new Profile();
695 $members->query(sprintf($qry, $this->id));
699 function subscriptionCount()
701 $c = Cache::instance();
704 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
705 if (is_integer($cnt)) {
710 $sub = new Subscription();
711 $sub->subscriber = $this->id;
713 $cnt = (int) $sub->count('distinct subscribed');
715 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
718 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
724 function subscriberCount()
726 $c = Cache::instance();
728 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
729 if (is_integer($cnt)) {
734 $sub = new Subscription();
735 $sub->subscribed = $this->id;
736 $sub->whereAdd('subscriber != subscribed');
737 $cnt = (int) $sub->count('distinct subscriber');
740 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
747 * Is this profile subscribed to another profile?
749 * @param Profile $other
752 function isSubscribed($other)
754 return Subscription::exists($this, $other);
758 * Check if a pending subscription request is outstanding for this...
760 * @param Profile $other
763 function hasPendingSubscription($other)
765 return Subscription_queue::exists($this, $other);
769 * Are these two profiles subscribed to each other?
771 * @param Profile $other
774 function mutuallySubscribed($other)
776 return $this->isSubscribed($other) &&
777 $other->isSubscribed($this);
780 function hasFave($notice)
782 $fave = Fave::pkeyGet(array('user_id' => $this->id,
783 'notice_id' => $notice->id));
784 return ((is_null($fave)) ? false : true);
789 $c = Cache::instance();
791 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
792 if (is_integer($cnt)) {
798 $faves->user_id = $this->id;
799 $cnt = (int) $faves->count('notice_id');
802 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
808 function noticeCount()
810 $c = Cache::instance();
813 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
814 if (is_integer($cnt)) {
819 $notices = new Notice();
820 $notices->profile_id = $this->id;
821 $cnt = (int) $notices->count('distinct id');
824 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
830 function blowFavesCache()
832 $cache = Cache::instance();
834 // Faves don't happen chronologically, so we need to blow
836 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
837 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
838 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
839 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
841 $this->blowFaveCount();
844 function blowSubscriberCount()
846 $c = Cache::instance();
848 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
852 function blowSubscriptionCount()
854 $c = Cache::instance();
856 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
860 function blowFaveCount()
862 $c = Cache::instance();
864 $c->delete(Cache::key('profile:fave_count:'.$this->id));
868 function blowNoticeCount()
870 $c = Cache::instance();
872 $c->delete(Cache::key('profile:notice_count:'.$this->id));
876 static function maxBio()
878 $biolimit = common_config('profile', 'biolimit');
879 // null => use global limit (distinct from 0!)
880 if (is_null($biolimit)) {
881 $biolimit = common_config('site', 'textlimit');
886 static function bioTooLong($bio)
888 $biolimit = self::maxBio();
889 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
894 $this->_deleteNotices();
895 $this->_deleteSubscriptions();
896 $this->_deleteMessages();
897 $this->_deleteTags();
898 $this->_deleteBlocks();
899 $this->delete_avatars();
901 // Warning: delete() will run on the batch objects,
902 // not on individual objects.
903 $related = array('Reply',
906 Event::handle('ProfileDeleteRelated', array($this, &$related));
908 foreach ($related as $cls) {
910 $inst->profile_id = $this->id;
917 function _deleteNotices()
919 $notice = new Notice();
920 $notice->profile_id = $this->id;
922 if ($notice->find()) {
923 while ($notice->fetch()) {
924 $other = clone($notice);
930 function _deleteSubscriptions()
932 $sub = new Subscription();
933 $sub->subscriber = $this->id;
937 while ($sub->fetch()) {
938 $other = Profile::staticGet('id', $sub->subscribed);
942 if ($other->id == $this->id) {
945 Subscription::cancel($this, $other);
948 $subd = new Subscription();
949 $subd->subscribed = $this->id;
952 while ($subd->fetch()) {
953 $other = Profile::staticGet('id', $subd->subscriber);
957 if ($other->id == $this->id) {
960 Subscription::cancel($other, $this);
963 $self = new Subscription();
965 $self->subscriber = $this->id;
966 $self->subscribed = $this->id;
971 function _deleteMessages()
973 $msg = new Message();
974 $msg->from_profile = $this->id;
977 $msg = new Message();
978 $msg->to_profile = $this->id;
982 function _deleteTags()
984 $tag = new Profile_tag();
985 $tag->tagged = $this->id;
989 function _deleteBlocks()
991 $block = new Profile_block();
992 $block->blocked = $this->id;
995 $block = new Group_block();
996 $block->blocked = $this->id;
1000 // XXX: identical to Notice::getLocation.
1002 function getLocation()
1006 if (!empty($this->location_id) && !empty($this->location_ns)) {
1007 $location = Location::fromId($this->location_id, $this->location_ns);
1010 if (is_null($location)) { // no ID, or Location::fromId() failed
1011 if (!empty($this->lat) && !empty($this->lon)) {
1012 $location = Location::fromLatLon($this->lat, $this->lon);
1016 if (is_null($location)) { // still haven't found it!
1017 if (!empty($this->location)) {
1018 $location = Location::fromName($this->location);
1025 function hasRole($name)
1028 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1029 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1031 $has_role = !empty($role);
1032 Event::handle('EndHasRole', array($this, $name, $has_role));
1037 function grantRole($name)
1039 if (Event::handle('StartGrantRole', array($this, $name))) {
1041 $role = new Profile_role();
1043 $role->profile_id = $this->id;
1044 $role->role = $name;
1045 $role->created = common_sql_now();
1047 $result = $role->insert();
1050 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1053 if ($name == 'owner') {
1054 User::blow('user:site_owner');
1057 Event::handle('EndGrantRole', array($this, $name));
1063 function revokeRole($name)
1065 if (Event::handle('StartRevokeRole', array($this, $name))) {
1067 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1071 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1072 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1073 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1076 $result = $role->delete();
1079 common_log_db_error($role, 'DELETE', __FILE__);
1080 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1081 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1082 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1085 if ($name == 'owner') {
1086 User::blow('user:site_owner');
1089 Event::handle('EndRevokeRole', array($this, $name));
1095 function isSandboxed()
1097 return $this->hasRole(Profile_role::SANDBOXED);
1100 function isSilenced()
1102 return $this->hasRole(Profile_role::SILENCED);
1107 $this->grantRole(Profile_role::SANDBOXED);
1110 function unsandbox()
1112 $this->revokeRole(Profile_role::SANDBOXED);
1117 $this->grantRole(Profile_role::SILENCED);
1120 function unsilence()
1122 $this->revokeRole(Profile_role::SILENCED);
1126 * Does this user have the right to do X?
1128 * With our role-based authorization, this is merely a lookup for whether the user
1129 * has a particular role. The implementation currently uses a switch statement
1130 * to determine if the user has the pre-defined role to exercise the right. Future
1131 * implementations may allow per-site roles, and different mappings of roles to rights.
1133 * @param $right string Name of the right, usually a constant in class Right
1134 * @return boolean whether the user has the right in question
1136 function hasRight($right)
1140 if ($this->hasRole(Profile_role::DELETED)) {
1144 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1147 case Right::DELETEOTHERSNOTICE:
1148 case Right::MAKEGROUPADMIN:
1149 case Right::SANDBOXUSER:
1150 case Right::SILENCEUSER:
1151 case Right::DELETEUSER:
1152 case Right::DELETEGROUP:
1153 $result = $this->hasRole(Profile_role::MODERATOR);
1155 case Right::CONFIGURESITE:
1156 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1158 case Right::GRANTROLE:
1159 case Right::REVOKEROLE:
1160 $result = $this->hasRole(Profile_role::OWNER);
1162 case Right::NEWNOTICE:
1163 case Right::NEWMESSAGE:
1164 case Right::SUBSCRIBE:
1165 case Right::CREATEGROUP:
1166 $result = !$this->isSilenced();
1168 case Right::PUBLICNOTICE:
1169 case Right::EMAILONREPLY:
1170 case Right::EMAILONSUBSCRIBE:
1171 case Right::EMAILONFAVE:
1172 $result = !$this->isSandboxed();
1174 case Right::WEBLOGIN:
1175 $result = !$this->isSilenced();
1178 $result = !$this->isSilenced();
1180 case Right::BACKUPACCOUNT:
1181 $result = common_config('profile', 'backup');
1183 case Right::RESTOREACCOUNT:
1184 $result = common_config('profile', 'restore');
1186 case Right::DELETEACCOUNT:
1187 $result = common_config('profile', 'delete');
1189 case Right::MOVEACCOUNT:
1190 $result = common_config('profile', 'move');
1200 function hasRepeated($notice_id)
1202 // XXX: not really a pkey, but should work
1204 $notice = Memcached_DataObject::pkeyGet('Notice',
1205 array('profile_id' => $this->id,
1206 'repeat_of' => $notice_id));
1208 return !empty($notice);
1212 * Returns an XML string fragment with limited profile information
1213 * as an Atom <author> element.
1215 * Assumes that Atom has been previously set up as the base namespace.
1217 * @param Profile $cur the current authenticated user
1221 function asAtomAuthor($cur = null)
1223 $xs = new XMLStringer(true);
1225 $xs->elementStart('author');
1226 $xs->element('name', null, $this->nickname);
1227 $xs->element('uri', null, $this->getUri());
1230 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1231 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1232 $xs->element('statusnet:profile_info', $attrs, null);
1234 $xs->elementEnd('author');
1236 return $xs->getString();
1240 * Extra profile info for atom entries
1242 * Clients use some extra profile info in the atom stream.
1243 * This gives it to them.
1245 * @param User $cur Current user
1247 * @return array representation of <statusnet:profile_info> element or null
1250 function profileInfo($cur)
1252 $profileInfoAttr = array('local_id' => $this->id);
1255 // Whether the current user is a subscribed to this profile
1256 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1257 // Whether the current user is has blocked this profile
1258 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1261 return array('statusnet:profile_info', $profileInfoAttr, null);
1265 * Returns an XML string fragment with profile information as an
1266 * Activity Streams <activity:actor> element.
1268 * Assumes that 'activity' namespace has been previously defined.
1272 function asActivityActor()
1274 return $this->asActivityNoun('actor');
1278 * Returns an XML string fragment with profile information as an
1279 * Activity Streams noun object with the given element type.
1281 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1282 * previously defined.
1284 * @param string $element one of 'actor', 'subject', 'object', 'target'
1288 function asActivityNoun($element)
1290 $noun = ActivityObject::fromProfile($this);
1291 return $noun->asString('activity:' . $element);
1295 * Returns the best URI for a profile. Plugins may override.
1297 * @return string $uri
1303 // give plugins a chance to set the URI
1304 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1306 // check for a local user first
1307 $user = User::staticGet('id', $this->id);
1309 if (!empty($user)) {
1313 Event::handle('EndGetProfileUri', array($this, &$uri));
1319 function hasBlocked($other)
1321 $block = Profile_block::get($this->id, $other->id);
1323 if (empty($block)) {
1332 function getAtomFeed()
1336 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1337 $user = User::staticGet('id', $this->id);
1338 if (!empty($user)) {
1339 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1340 'format' => 'atom'));
1342 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1348 static function fromURI($uri)
1352 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1353 // Get a local user or remote (OMB 0.1) profile
1354 $user = User::staticGet('uri', $uri);
1355 if (!empty($user)) {
1356 $profile = $user->getProfile();
1358 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1364 function canRead(Notice $notice)
1366 if ($notice->scope & Notice::SITE_SCOPE) {
1367 $user = $this->getUser();
1373 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1374 $replies = $notice->getReplies();
1376 if (!in_array($this->id, $replies)) {
1377 $groups = $notice->getGroups();
1381 foreach ($groups as $group) {
1382 if ($this->isMember($group)) {
1394 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1395 $author = $notice->getProfile();
1396 if (!Subscription::exists($this, $author)) {
1404 static function current()
1406 $user = common_current_user();
1410 $profile = $user->getProfile();
1416 * Magic function called at serialize() time.
1418 * We use this to drop a couple process-specific references
1419 * from DB_DataObject which can cause trouble in future
1422 * @return array of variable names to include in serialization.
1427 $vars = parent::__sleep();
1428 $skip = array('_user', '_avatars');
1429 return array_diff($vars, $skip);
1432 static function fillAvatars(&$profiles, $width)
1435 foreach ($profiles as $profile) {
1436 if (!empty($profile)) {
1437 $ids[] = $profile->id;
1441 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1442 'height' => $width));
1444 foreach ($profiles as $profile) {
1445 if (!empty($profile)) { // ???
1446 $profile->_fillAvatar($width, $avatars[$profile->id]);
1451 // Can't seem to find how to fix this.
1453 function getProfile()