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 $avatar = $this->_getAvatar($width);
116 if (empty($avatar)) {
118 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
119 $avatar = Avatar::pkeyGet(
121 'profile_id' => $this->id,
126 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
129 $this->_fillAvatar($width, $avatar);
135 // XXX: @Fix me gargargar
136 function _getAvatar($width)
138 if (empty($this->_avatars)) {
139 $this->_avatars = array();
142 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
143 // the previously used profile! Please shoot me now! --Zach
144 if (array_key_exists($width, $this->_avatars)) {
145 // Don't return cached avatar unless it's really for this profile
146 if ($this->_avatars[$width]->profile_id == $this->id) {
147 return $this->_avatars[$width];
154 function _fillAvatar($width, $avatar)
156 //common_debug("Storing avatar of width: {$avatar->width} and profile_id {$avatar->profile_id} in profile {$this->id}.");
157 $this->_avatars[$width] = $avatar;
161 function getOriginalAvatar()
163 $avatar = DB_DataObject::factory('avatar');
164 $avatar->profile_id = $this->id;
165 $avatar->original = true;
166 if ($avatar->find(true)) {
173 function setOriginal($filename)
175 $imagefile = new ImageFile($this->id, Avatar::path($filename));
177 $avatar = new Avatar();
178 $avatar->profile_id = $this->id;
179 $avatar->width = $imagefile->width;
180 $avatar->height = $imagefile->height;
181 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
182 $avatar->filename = $filename;
183 $avatar->original = true;
184 $avatar->url = Avatar::url($filename);
185 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
187 // XXX: start a transaction here
189 if (!$this->delete_avatars() || !$avatar->insert()) {
190 @unlink(Avatar::path($filename));
194 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
195 // We don't do a scaled one if original is our scaled size
196 if (!($avatar->width == $size && $avatar->height == $size)) {
197 $scaled_filename = $imagefile->resize($size);
199 //$scaled = DB_DataObject::factory('avatar');
200 $scaled = new Avatar();
201 $scaled->profile_id = $this->id;
202 $scaled->width = $size;
203 $scaled->height = $size;
204 $scaled->original = false;
205 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
206 $scaled->filename = $scaled_filename;
207 $scaled->url = Avatar::url($scaled_filename);
208 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
210 if (!$scaled->insert()) {
220 * Delete attached avatars for this user from the database and filesystem.
221 * This should be used instead of a batch delete() to ensure that files
222 * get removed correctly.
224 * @param boolean $original true to delete only the original-size file
227 function delete_avatars($original=true)
229 $avatar = new Avatar();
230 $avatar->profile_id = $this->id;
232 while ($avatar->fetch()) {
233 if ($avatar->original) {
234 if ($original == false) {
244 * Gets either the full name (if filled) or the nickname.
248 function getBestName()
250 return ($this->fullname) ? $this->fullname : $this->nickname;
254 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
255 * if no fullname is provided.
259 function getFancyName()
261 if ($this->fullname) {
262 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
263 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
265 return $this->nickname;
270 * Get the most recent notice posted by this user, if any.
272 * @return mixed Notice or null
274 function getCurrentNotice()
276 $notice = $this->getNotices(0, 1);
278 if ($notice->fetch()) {
279 if ($notice instanceof ArrayWrapper) {
280 // hack for things trying to work with single notices
281 return $notice->_items[0];
289 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
291 $stream = new TaggedProfileNoticeStream($this, $tag);
293 return $stream->getNotices($offset, $limit, $since_id, $max_id);
296 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
298 $stream = new ProfileNoticeStream($this);
300 return $stream->getNotices($offset, $limit, $since_id, $max_id);
303 function isMember($group)
305 $groups = $this->getGroups(0, null);
306 $gs = $groups->fetchAll();
307 foreach ($gs as $g) {
308 if ($group->id == $g->id) {
315 function isAdmin($group)
317 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
318 'group_id' => $group->id));
319 return (!empty($gm) && $gm->is_admin);
322 function isPendingMember($group)
324 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
325 'group_id' => $group->id));
326 return !empty($request);
329 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
333 $keypart = sprintf('profile:groups:%d', $this->id);
335 $idstring = self::cacheGet($keypart);
337 if ($idstring !== false) {
338 $ids = explode(',', $idstring);
340 $gm = new Group_member();
342 $gm->profile_id = $this->id;
345 while ($gm->fetch()) {
346 $ids[] = $gm->group_id;
350 self::cacheSet($keypart, implode(',', $ids));
353 return User_group::multiGet('id', $ids);
356 function isTagged($peopletag)
358 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
359 'tagged' => $this->id,
360 'tag' => $peopletag->tag));
364 function canTag($tagged)
366 if (empty($tagged)) {
370 if ($tagged->id == $this->id) {
374 $all = common_config('peopletag', 'allow_tagging', 'all');
375 $local = common_config('peopletag', 'allow_tagging', 'local');
376 $remote = common_config('peopletag', 'allow_tagging', 'remote');
377 $subs = common_config('peopletag', 'allow_tagging', 'subs');
383 $tagged_user = $tagged->getUser();
384 if (!empty($tagged_user)) {
389 return (Subscription::exists($this, $tagged) ||
390 Subscription::exists($tagged, $this));
391 } else if ($remote) {
397 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
401 $keypart = sprintf('profile:lists:%d', $this->id);
403 $idstr = self::cacheGet($keypart);
405 if ($idstr !== false) {
406 $ids = explode(',', $idstr);
408 $list = new Profile_list();
410 $list->selectAdd('id');
411 $list->tagger = $this->id;
412 $list->selectAdd('id as "cursor"');
415 $list->whereAdd('id > '.$since_id);
419 $list->whereAdd('id <= '.$max_id);
422 if($offset>=0 && !is_null($limit)) {
423 $list->limit($offset, $limit);
426 $list->orderBy('id DESC');
429 while ($list->fetch()) {
434 self::cacheSet($keypart, implode(',', $ids));
437 $showPrivate = (($auth_user instanceof User ||
438 $auth_user instanceof Profile) &&
439 $auth_user->id === $this->id);
443 foreach ($ids as $id) {
444 $list = Profile_list::staticGet('id', $id);
446 ($showPrivate || !$list->private)) {
448 if (!isset($list->cursor)) {
449 $list->cursor = $list->id;
456 return new ArrayWrapper($lists);
460 * Get tags that other people put on this profile, in reverse-chron order
462 * @param (Profile|User) $auth_user Authorized user (used for privacy)
463 * @param int $offset Offset from latest
464 * @param int $limit Max number to get
465 * @param datetime $since_id max date
466 * @param datetime $max_id min date
468 * @return Profile_list resulting lists
471 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
473 $list = new Profile_list();
475 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
476 'from profile_tag join profile_list '.
477 'on (profile_tag.tagger = profile_list.tagger ' .
478 ' and profile_tag.tag = profile_list.tag) ' .
479 'where profile_tag.tagged = %d ',
483 if ($auth_user instanceof User || $auth_user instanceof Profile) {
484 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
485 'OR ( profile_list.tagger = %d AND ' .
486 'profile_list.private = true ) )',
489 $qry .= 'AND profile_list.private = 0 ';
493 $qry .= sprintf('AND (cursor > %d) ', $since_id);
497 $qry .= sprintf('AND (cursor < %d) ', $max_id);
500 $qry .= 'ORDER BY profile_tag.modified DESC ';
502 if ($offset >= 0 && !is_null($limit)) {
503 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
510 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
512 $tags = new Profile_list();
513 $tags->private = true;
514 $tags->tagger = $this->id;
517 $tags->whereAdd('id > '.$since_id);
521 $tags->whereAdd('id <= '.$max_id);
524 if($offset>=0 && !is_null($limit)) {
525 $tags->limit($offset, $limit);
528 $tags->orderBy('id DESC');
534 function hasLocalTags()
536 $tags = new Profile_tag();
538 $tags->joinAdd(array('tagger', 'user:id'));
539 $tags->whereAdd('tagged = '.$this->id);
540 $tags->whereAdd('tagger != '.$this->id);
545 return ($tags->N == 0) ? false : true;
548 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
550 $lists = new Profile_list();
551 $subs = new Profile_tag_subscription();
553 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
555 #@fixme: postgres (round(date_part('epoch', my_date)))
556 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
558 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
561 $lists->whereAdd('cursor > '.$since_id);
565 $lists->whereAdd('cursor <= '.$max_id);
568 if($offset>=0 && !is_null($limit)) {
569 $lists->limit($offset, $limit);
572 $lists->orderBy('"cursor" DESC');
579 * Request to join the given group.
580 * May throw exceptions on failure.
582 * @param User_group $group
583 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
585 function joinGroup(User_group $group)
588 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
589 $join = Group_join_queue::saveNew($this, $group);
591 if (Event::handle('StartJoinGroup', array($group, $this))) {
592 $join = Group_member::join($group->id, $this->id);
593 self::blow('profile:groups:%d', $this->id);
594 Event::handle('EndJoinGroup', array($group, $this));
598 // Send any applicable notifications...
605 * Leave a group that this profile is a member of.
607 * @param User_group $group
609 function leaveGroup(User_group $group)
611 if (Event::handle('StartLeaveGroup', array($group, $this))) {
612 Group_member::leave($group->id, $this->id);
613 self::blow('profile:groups:%d', $this->id);
614 Event::handle('EndLeaveGroup', array($group, $this));
618 function avatarUrl($size=AVATAR_PROFILE_SIZE)
620 $avatar = $this->getAvatar($size);
622 return $avatar->displayUrl();
624 return Avatar::defaultImage($size);
628 function getSubscriptions($offset=0, $limit=null)
630 $subs = Subscription::bySubscriber($this->id,
636 while ($subs->fetch()) {
637 $profile = Profile::staticGet($subs->subscribed);
639 $profiles[] = $profile;
643 return new ArrayWrapper($profiles);
646 function getSubscribers($offset=0, $limit=null)
648 $subs = Subscription::bySubscribed($this->id,
654 while ($subs->fetch()) {
655 $profile = Profile::staticGet($subs->subscriber);
657 $profiles[] = $profile;
661 return new ArrayWrapper($profiles);
664 function getTaggedSubscribers($tag)
667 'SELECT profile.* ' .
668 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
669 'ON profile.id = subscription.subscriber ' .
670 'AND profile.id = profile_tag.tagged ' .
671 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
672 'WHERE subscription.subscribed = %d ' .
673 'AND subscription.subscribed != subscription.subscriber ' .
674 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
675 'AND profile_list.private = false ' .
676 'ORDER BY subscription.created DESC';
678 $profile = new Profile();
681 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
683 while ($profile->fetch()) {
684 $tagged[] = clone($profile);
690 * Get pending subscribers, who have not yet been approved.
696 function getRequests($offset=0, $limit=null)
699 'SELECT profile.* ' .
700 'FROM profile JOIN subscription_queue '.
701 'ON profile.id = subscription_queue.subscriber ' .
702 'WHERE subscription_queue.subscribed = %d ' .
703 'ORDER BY subscription_queue.created DESC ';
705 if ($limit != null) {
706 if (common_config('db','type') == 'pgsql') {
707 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
709 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
713 $members = new Profile();
715 $members->query(sprintf($qry, $this->id));
719 function subscriptionCount()
721 $c = Cache::instance();
724 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
725 if (is_integer($cnt)) {
730 $sub = new Subscription();
731 $sub->subscriber = $this->id;
733 $cnt = (int) $sub->count('distinct subscribed');
735 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
738 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
744 function subscriberCount()
746 $c = Cache::instance();
748 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
749 if (is_integer($cnt)) {
754 $sub = new Subscription();
755 $sub->subscribed = $this->id;
756 $sub->whereAdd('subscriber != subscribed');
757 $cnt = (int) $sub->count('distinct subscriber');
760 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
767 * Is this profile subscribed to another profile?
769 * @param Profile $other
772 function isSubscribed($other)
774 return Subscription::exists($this, $other);
778 * Check if a pending subscription request is outstanding for this...
780 * @param Profile $other
783 function hasPendingSubscription($other)
785 return Subscription_queue::exists($this, $other);
789 * Are these two profiles subscribed to each other?
791 * @param Profile $other
794 function mutuallySubscribed($other)
796 return $this->isSubscribed($other) &&
797 $other->isSubscribed($this);
800 function hasFave($notice)
802 $fave = Fave::pkeyGet(array('user_id' => $this->id,
803 'notice_id' => $notice->id));
804 return ((is_null($fave)) ? false : true);
809 $c = Cache::instance();
811 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
812 if (is_integer($cnt)) {
818 $faves->user_id = $this->id;
819 $cnt = (int) $faves->count('notice_id');
822 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
828 function noticeCount()
830 $c = Cache::instance();
833 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
834 if (is_integer($cnt)) {
839 $notices = new Notice();
840 $notices->profile_id = $this->id;
841 $cnt = (int) $notices->count('distinct id');
844 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
850 function blowFavesCache()
852 $cache = Cache::instance();
854 // Faves don't happen chronologically, so we need to blow
856 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
857 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
858 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
859 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
861 $this->blowFaveCount();
864 function blowSubscriberCount()
866 $c = Cache::instance();
868 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
872 function blowSubscriptionCount()
874 $c = Cache::instance();
876 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
880 function blowFaveCount()
882 $c = Cache::instance();
884 $c->delete(Cache::key('profile:fave_count:'.$this->id));
888 function blowNoticeCount()
890 $c = Cache::instance();
892 $c->delete(Cache::key('profile:notice_count:'.$this->id));
896 static function maxBio()
898 $biolimit = common_config('profile', 'biolimit');
899 // null => use global limit (distinct from 0!)
900 if (is_null($biolimit)) {
901 $biolimit = common_config('site', 'textlimit');
906 static function bioTooLong($bio)
908 $biolimit = self::maxBio();
909 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
914 $this->_deleteNotices();
915 $this->_deleteSubscriptions();
916 $this->_deleteMessages();
917 $this->_deleteTags();
918 $this->_deleteBlocks();
919 $this->delete_avatars();
921 // Warning: delete() will run on the batch objects,
922 // not on individual objects.
923 $related = array('Reply',
926 Event::handle('ProfileDeleteRelated', array($this, &$related));
928 foreach ($related as $cls) {
930 $inst->profile_id = $this->id;
937 function _deleteNotices()
939 $notice = new Notice();
940 $notice->profile_id = $this->id;
942 if ($notice->find()) {
943 while ($notice->fetch()) {
944 $other = clone($notice);
950 function _deleteSubscriptions()
952 $sub = new Subscription();
953 $sub->subscriber = $this->id;
957 while ($sub->fetch()) {
958 $other = Profile::staticGet('id', $sub->subscribed);
962 if ($other->id == $this->id) {
965 Subscription::cancel($this, $other);
968 $subd = new Subscription();
969 $subd->subscribed = $this->id;
972 while ($subd->fetch()) {
973 $other = Profile::staticGet('id', $subd->subscriber);
977 if ($other->id == $this->id) {
980 Subscription::cancel($other, $this);
983 $self = new Subscription();
985 $self->subscriber = $this->id;
986 $self->subscribed = $this->id;
991 function _deleteMessages()
993 $msg = new Message();
994 $msg->from_profile = $this->id;
997 $msg = new Message();
998 $msg->to_profile = $this->id;
1002 function _deleteTags()
1004 $tag = new Profile_tag();
1005 $tag->tagged = $this->id;
1009 function _deleteBlocks()
1011 $block = new Profile_block();
1012 $block->blocked = $this->id;
1015 $block = new Group_block();
1016 $block->blocked = $this->id;
1020 // XXX: identical to Notice::getLocation.
1022 function getLocation()
1026 if (!empty($this->location_id) && !empty($this->location_ns)) {
1027 $location = Location::fromId($this->location_id, $this->location_ns);
1030 if (is_null($location)) { // no ID, or Location::fromId() failed
1031 if (!empty($this->lat) && !empty($this->lon)) {
1032 $location = Location::fromLatLon($this->lat, $this->lon);
1036 if (is_null($location)) { // still haven't found it!
1037 if (!empty($this->location)) {
1038 $location = Location::fromName($this->location);
1045 function hasRole($name)
1048 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1049 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1051 $has_role = !empty($role);
1052 Event::handle('EndHasRole', array($this, $name, $has_role));
1057 function grantRole($name)
1059 if (Event::handle('StartGrantRole', array($this, $name))) {
1061 $role = new Profile_role();
1063 $role->profile_id = $this->id;
1064 $role->role = $name;
1065 $role->created = common_sql_now();
1067 $result = $role->insert();
1070 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1073 if ($name == 'owner') {
1074 User::blow('user:site_owner');
1077 Event::handle('EndGrantRole', array($this, $name));
1083 function revokeRole($name)
1085 if (Event::handle('StartRevokeRole', array($this, $name))) {
1087 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1091 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1092 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1093 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1096 $result = $role->delete();
1099 common_log_db_error($role, 'DELETE', __FILE__);
1100 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1101 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1102 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1105 if ($name == 'owner') {
1106 User::blow('user:site_owner');
1109 Event::handle('EndRevokeRole', array($this, $name));
1115 function isSandboxed()
1117 return $this->hasRole(Profile_role::SANDBOXED);
1120 function isSilenced()
1122 return $this->hasRole(Profile_role::SILENCED);
1127 $this->grantRole(Profile_role::SANDBOXED);
1130 function unsandbox()
1132 $this->revokeRole(Profile_role::SANDBOXED);
1137 $this->grantRole(Profile_role::SILENCED);
1140 function unsilence()
1142 $this->revokeRole(Profile_role::SILENCED);
1146 * Does this user have the right to do X?
1148 * With our role-based authorization, this is merely a lookup for whether the user
1149 * has a particular role. The implementation currently uses a switch statement
1150 * to determine if the user has the pre-defined role to exercise the right. Future
1151 * implementations may allow per-site roles, and different mappings of roles to rights.
1153 * @param $right string Name of the right, usually a constant in class Right
1154 * @return boolean whether the user has the right in question
1156 function hasRight($right)
1160 if ($this->hasRole(Profile_role::DELETED)) {
1164 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1167 case Right::DELETEOTHERSNOTICE:
1168 case Right::MAKEGROUPADMIN:
1169 case Right::SANDBOXUSER:
1170 case Right::SILENCEUSER:
1171 case Right::DELETEUSER:
1172 case Right::DELETEGROUP:
1173 $result = $this->hasRole(Profile_role::MODERATOR);
1175 case Right::CONFIGURESITE:
1176 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1178 case Right::GRANTROLE:
1179 case Right::REVOKEROLE:
1180 $result = $this->hasRole(Profile_role::OWNER);
1182 case Right::NEWNOTICE:
1183 case Right::NEWMESSAGE:
1184 case Right::SUBSCRIBE:
1185 case Right::CREATEGROUP:
1186 $result = !$this->isSilenced();
1188 case Right::PUBLICNOTICE:
1189 case Right::EMAILONREPLY:
1190 case Right::EMAILONSUBSCRIBE:
1191 case Right::EMAILONFAVE:
1192 $result = !$this->isSandboxed();
1194 case Right::WEBLOGIN:
1195 $result = !$this->isSilenced();
1198 $result = !$this->isSilenced();
1200 case Right::BACKUPACCOUNT:
1201 $result = common_config('profile', 'backup');
1203 case Right::RESTOREACCOUNT:
1204 $result = common_config('profile', 'restore');
1206 case Right::DELETEACCOUNT:
1207 $result = common_config('profile', 'delete');
1209 case Right::MOVEACCOUNT:
1210 $result = common_config('profile', 'move');
1220 function hasRepeated($notice_id)
1222 // XXX: not really a pkey, but should work
1224 $notice = Memcached_DataObject::pkeyGet('Notice',
1225 array('profile_id' => $this->id,
1226 'repeat_of' => $notice_id));
1228 return !empty($notice);
1232 * Returns an XML string fragment with limited profile information
1233 * as an Atom <author> element.
1235 * Assumes that Atom has been previously set up as the base namespace.
1237 * @param Profile $cur the current authenticated user
1241 function asAtomAuthor($cur = null)
1243 $xs = new XMLStringer(true);
1245 $xs->elementStart('author');
1246 $xs->element('name', null, $this->nickname);
1247 $xs->element('uri', null, $this->getUri());
1250 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1251 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1252 $xs->element('statusnet:profile_info', $attrs, null);
1254 $xs->elementEnd('author');
1256 return $xs->getString();
1260 * Extra profile info for atom entries
1262 * Clients use some extra profile info in the atom stream.
1263 * This gives it to them.
1265 * @param User $cur Current user
1267 * @return array representation of <statusnet:profile_info> element or null
1270 function profileInfo($cur)
1272 $profileInfoAttr = array('local_id' => $this->id);
1275 // Whether the current user is a subscribed to this profile
1276 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1277 // Whether the current user is has blocked this profile
1278 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1281 return array('statusnet:profile_info', $profileInfoAttr, null);
1285 * Returns an XML string fragment with profile information as an
1286 * Activity Streams <activity:actor> element.
1288 * Assumes that 'activity' namespace has been previously defined.
1292 function asActivityActor()
1294 return $this->asActivityNoun('actor');
1298 * Returns an XML string fragment with profile information as an
1299 * Activity Streams noun object with the given element type.
1301 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1302 * previously defined.
1304 * @param string $element one of 'actor', 'subject', 'object', 'target'
1308 function asActivityNoun($element)
1310 $noun = ActivityObject::fromProfile($this);
1311 return $noun->asString('activity:' . $element);
1315 * Returns the best URI for a profile. Plugins may override.
1317 * @return string $uri
1323 // give plugins a chance to set the URI
1324 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1326 // check for a local user first
1327 $user = User::staticGet('id', $this->id);
1329 if (!empty($user)) {
1333 Event::handle('EndGetProfileUri', array($this, &$uri));
1339 function hasBlocked($other)
1341 $block = Profile_block::get($this->id, $other->id);
1343 if (empty($block)) {
1352 function getAtomFeed()
1356 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1357 $user = User::staticGet('id', $this->id);
1358 if (!empty($user)) {
1359 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1360 'format' => 'atom'));
1362 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1368 static function fromURI($uri)
1372 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1373 // Get a local user or remote (OMB 0.1) profile
1374 $user = User::staticGet('uri', $uri);
1375 if (!empty($user)) {
1376 $profile = $user->getProfile();
1378 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1384 function canRead(Notice $notice)
1386 if ($notice->scope & Notice::SITE_SCOPE) {
1387 $user = $this->getUser();
1393 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1394 $replies = $notice->getReplies();
1396 if (!in_array($this->id, $replies)) {
1397 $groups = $notice->getGroups();
1401 foreach ($groups as $group) {
1402 if ($this->isMember($group)) {
1414 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1415 $author = $notice->getProfile();
1416 if (!Subscription::exists($this, $author)) {
1424 static function current()
1426 $user = common_current_user();
1430 $profile = $user->getProfile();
1436 * Magic function called at serialize() time.
1438 * We use this to drop a couple process-specific references
1439 * from DB_DataObject which can cause trouble in future
1442 * @return array of variable names to include in serialization.
1447 $vars = parent::__sleep();
1448 $skip = array('_user', '_avatars');
1449 return array_diff($vars, $skip);
1452 static function fillAvatars(&$profiles, $width)
1455 foreach ($profiles as $profile) {
1456 if (!empty($profile)) {
1457 $ids[] = $profile->id;
1461 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1462 'height' => $width));
1464 foreach ($profiles as $profile) {
1465 if (!empty($profile)) { // ???
1466 $profile->_fillAvatar($width, $avatars[$profile->id]);
1471 // Can't seem to find how to fix this.
1473 function getProfile()
1478 static function pivotGet($key, $values, $otherCols=array()) {
1479 return Memcached_DataObject::pivotGet('Profile', $key, $values, $otherCols);