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 if (!is_null($offset) && !is_null($limit)) {
354 $ids = array_slice($ids, $offset, $limit);
357 return User_group::multiGet('id', $ids);
360 function isTagged($peopletag)
362 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
363 'tagged' => $this->id,
364 'tag' => $peopletag->tag));
368 function canTag($tagged)
370 if (empty($tagged)) {
374 if ($tagged->id == $this->id) {
378 $all = common_config('peopletag', 'allow_tagging', 'all');
379 $local = common_config('peopletag', 'allow_tagging', 'local');
380 $remote = common_config('peopletag', 'allow_tagging', 'remote');
381 $subs = common_config('peopletag', 'allow_tagging', 'subs');
387 $tagged_user = $tagged->getUser();
388 if (!empty($tagged_user)) {
393 return (Subscription::exists($this, $tagged) ||
394 Subscription::exists($tagged, $this));
395 } else if ($remote) {
401 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
405 $keypart = sprintf('profile:lists:%d', $this->id);
407 $idstr = self::cacheGet($keypart);
409 if ($idstr !== false) {
410 $ids = explode(',', $idstr);
412 $list = new Profile_list();
414 $list->selectAdd('id');
415 $list->tagger = $this->id;
416 $list->selectAdd('id as "cursor"');
419 $list->whereAdd('id > '.$since_id);
423 $list->whereAdd('id <= '.$max_id);
426 if($offset>=0 && !is_null($limit)) {
427 $list->limit($offset, $limit);
430 $list->orderBy('id DESC');
433 while ($list->fetch()) {
438 self::cacheSet($keypart, implode(',', $ids));
441 $showPrivate = (($auth_user instanceof User ||
442 $auth_user instanceof Profile) &&
443 $auth_user->id === $this->id);
447 foreach ($ids as $id) {
448 $list = Profile_list::staticGet('id', $id);
450 ($showPrivate || !$list->private)) {
452 if (!isset($list->cursor)) {
453 $list->cursor = $list->id;
460 return new ArrayWrapper($lists);
464 * Get tags that other people put on this profile, in reverse-chron order
466 * @param (Profile|User) $auth_user Authorized user (used for privacy)
467 * @param int $offset Offset from latest
468 * @param int $limit Max number to get
469 * @param datetime $since_id max date
470 * @param datetime $max_id min date
472 * @return Profile_list resulting lists
475 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
477 $list = new Profile_list();
479 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
480 'from profile_tag join profile_list '.
481 'on (profile_tag.tagger = profile_list.tagger ' .
482 ' and profile_tag.tag = profile_list.tag) ' .
483 'where profile_tag.tagged = %d ',
487 if ($auth_user instanceof User || $auth_user instanceof Profile) {
488 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
489 'OR ( profile_list.tagger = %d AND ' .
490 'profile_list.private = true ) )',
493 $qry .= 'AND profile_list.private = 0 ';
497 $qry .= sprintf('AND (cursor > %d) ', $since_id);
501 $qry .= sprintf('AND (cursor < %d) ', $max_id);
504 $qry .= 'ORDER BY profile_tag.modified DESC ';
506 if ($offset >= 0 && !is_null($limit)) {
507 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
514 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
516 $tags = new Profile_list();
517 $tags->private = true;
518 $tags->tagger = $this->id;
521 $tags->whereAdd('id > '.$since_id);
525 $tags->whereAdd('id <= '.$max_id);
528 if($offset>=0 && !is_null($limit)) {
529 $tags->limit($offset, $limit);
532 $tags->orderBy('id DESC');
538 function hasLocalTags()
540 $tags = new Profile_tag();
542 $tags->joinAdd(array('tagger', 'user:id'));
543 $tags->whereAdd('tagged = '.$this->id);
544 $tags->whereAdd('tagger != '.$this->id);
549 return ($tags->N == 0) ? false : true;
552 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
554 $lists = new Profile_list();
555 $subs = new Profile_tag_subscription();
557 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
559 #@fixme: postgres (round(date_part('epoch', my_date)))
560 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
562 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
565 $lists->whereAdd('cursor > '.$since_id);
569 $lists->whereAdd('cursor <= '.$max_id);
572 if($offset>=0 && !is_null($limit)) {
573 $lists->limit($offset, $limit);
576 $lists->orderBy('"cursor" DESC');
583 * Request to join the given group.
584 * May throw exceptions on failure.
586 * @param User_group $group
587 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
589 function joinGroup(User_group $group)
592 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
593 $join = Group_join_queue::saveNew($this, $group);
595 if (Event::handle('StartJoinGroup', array($group, $this))) {
596 $join = Group_member::join($group->id, $this->id);
597 self::blow('profile:groups:%d', $this->id);
598 self::blow('group:member_ids:%d', $group->id);
599 self::blow('group:member_count:%d', $group->id);
600 Event::handle('EndJoinGroup', array($group, $this));
604 // Send any applicable notifications...
611 * Leave a group that this profile is a member of.
613 * @param User_group $group
615 function leaveGroup(User_group $group)
617 if (Event::handle('StartLeaveGroup', array($group, $this))) {
618 Group_member::leave($group->id, $this->id);
619 self::blow('profile:groups:%d', $this->id);
620 self::blow('group:member_ids:%d', $group->id);
621 self::blow('group:member_count:%d', $group->id);
622 Event::handle('EndLeaveGroup', array($group, $this));
626 function avatarUrl($size=AVATAR_PROFILE_SIZE)
628 $avatar = $this->getAvatar($size);
630 return $avatar->displayUrl();
632 return Avatar::defaultImage($size);
636 function getSubscriptions($offset=0, $limit=null)
638 $subs = Subscription::bySubscriber($this->id,
644 while ($subs->fetch()) {
645 $profile = Profile::staticGet($subs->subscribed);
647 $profiles[] = $profile;
651 return new ArrayWrapper($profiles);
654 function getSubscribers($offset=0, $limit=null)
656 $subs = Subscription::bySubscribed($this->id,
662 while ($subs->fetch()) {
663 $profile = Profile::staticGet($subs->subscriber);
665 $profiles[] = $profile;
669 return new ArrayWrapper($profiles);
672 function getTaggedSubscribers($tag)
675 'SELECT profile.* ' .
676 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
677 'ON profile.id = subscription.subscriber ' .
678 'AND profile.id = profile_tag.tagged ' .
679 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
680 'WHERE subscription.subscribed = %d ' .
681 'AND subscription.subscribed != subscription.subscriber ' .
682 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
683 'AND profile_list.private = false ' .
684 'ORDER BY subscription.created DESC';
686 $profile = new Profile();
689 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $tag));
691 while ($profile->fetch()) {
692 $tagged[] = clone($profile);
698 * Get pending subscribers, who have not yet been approved.
704 function getRequests($offset=0, $limit=null)
707 'SELECT profile.* ' .
708 'FROM profile JOIN subscription_queue '.
709 'ON profile.id = subscription_queue.subscriber ' .
710 'WHERE subscription_queue.subscribed = %d ' .
711 'ORDER BY subscription_queue.created DESC ';
713 if ($limit != null) {
714 if (common_config('db','type') == 'pgsql') {
715 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
717 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
721 $members = new Profile();
723 $members->query(sprintf($qry, $this->id));
727 function subscriptionCount()
729 $c = Cache::instance();
732 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
733 if (is_integer($cnt)) {
738 $sub = new Subscription();
739 $sub->subscriber = $this->id;
741 $cnt = (int) $sub->count('distinct subscribed');
743 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
746 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
752 function subscriberCount()
754 $c = Cache::instance();
756 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
757 if (is_integer($cnt)) {
762 $sub = new Subscription();
763 $sub->subscribed = $this->id;
764 $sub->whereAdd('subscriber != subscribed');
765 $cnt = (int) $sub->count('distinct subscriber');
768 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
775 * Is this profile subscribed to another profile?
777 * @param Profile $other
780 function isSubscribed($other)
782 return Subscription::exists($this, $other);
786 * Check if a pending subscription request is outstanding for this...
788 * @param Profile $other
791 function hasPendingSubscription($other)
793 return Subscription_queue::exists($this, $other);
797 * Are these two profiles subscribed to each other?
799 * @param Profile $other
802 function mutuallySubscribed($other)
804 return $this->isSubscribed($other) &&
805 $other->isSubscribed($this);
808 function hasFave($notice)
810 $fave = Fave::pkeyGet(array('user_id' => $this->id,
811 'notice_id' => $notice->id));
812 return ((is_null($fave)) ? false : true);
817 $c = Cache::instance();
819 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
820 if (is_integer($cnt)) {
826 $faves->user_id = $this->id;
827 $cnt = (int) $faves->count('notice_id');
830 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
836 function noticeCount()
838 $c = Cache::instance();
841 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
842 if (is_integer($cnt)) {
847 $notices = new Notice();
848 $notices->profile_id = $this->id;
849 $cnt = (int) $notices->count('distinct id');
852 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
858 function blowFavesCache()
860 $cache = Cache::instance();
862 // Faves don't happen chronologically, so we need to blow
864 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
865 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
866 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
867 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
869 $this->blowFaveCount();
872 function blowSubscriberCount()
874 $c = Cache::instance();
876 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
880 function blowSubscriptionCount()
882 $c = Cache::instance();
884 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
888 function blowFaveCount()
890 $c = Cache::instance();
892 $c->delete(Cache::key('profile:fave_count:'.$this->id));
896 function blowNoticeCount()
898 $c = Cache::instance();
900 $c->delete(Cache::key('profile:notice_count:'.$this->id));
904 static function maxBio()
906 $biolimit = common_config('profile', 'biolimit');
907 // null => use global limit (distinct from 0!)
908 if (is_null($biolimit)) {
909 $biolimit = common_config('site', 'textlimit');
914 static function bioTooLong($bio)
916 $biolimit = self::maxBio();
917 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
922 $this->_deleteNotices();
923 $this->_deleteSubscriptions();
924 $this->_deleteMessages();
925 $this->_deleteTags();
926 $this->_deleteBlocks();
927 $this->delete_avatars();
929 // Warning: delete() will run on the batch objects,
930 // not on individual objects.
931 $related = array('Reply',
934 Event::handle('ProfileDeleteRelated', array($this, &$related));
936 foreach ($related as $cls) {
938 $inst->profile_id = $this->id;
945 function _deleteNotices()
947 $notice = new Notice();
948 $notice->profile_id = $this->id;
950 if ($notice->find()) {
951 while ($notice->fetch()) {
952 $other = clone($notice);
958 function _deleteSubscriptions()
960 $sub = new Subscription();
961 $sub->subscriber = $this->id;
965 while ($sub->fetch()) {
966 $other = Profile::staticGet('id', $sub->subscribed);
970 if ($other->id == $this->id) {
973 Subscription::cancel($this, $other);
976 $subd = new Subscription();
977 $subd->subscribed = $this->id;
980 while ($subd->fetch()) {
981 $other = Profile::staticGet('id', $subd->subscriber);
985 if ($other->id == $this->id) {
988 Subscription::cancel($other, $this);
991 $self = new Subscription();
993 $self->subscriber = $this->id;
994 $self->subscribed = $this->id;
999 function _deleteMessages()
1001 $msg = new Message();
1002 $msg->from_profile = $this->id;
1005 $msg = new Message();
1006 $msg->to_profile = $this->id;
1010 function _deleteTags()
1012 $tag = new Profile_tag();
1013 $tag->tagged = $this->id;
1017 function _deleteBlocks()
1019 $block = new Profile_block();
1020 $block->blocked = $this->id;
1023 $block = new Group_block();
1024 $block->blocked = $this->id;
1028 // XXX: identical to Notice::getLocation.
1030 function getLocation()
1034 if (!empty($this->location_id) && !empty($this->location_ns)) {
1035 $location = Location::fromId($this->location_id, $this->location_ns);
1038 if (is_null($location)) { // no ID, or Location::fromId() failed
1039 if (!empty($this->lat) && !empty($this->lon)) {
1040 $location = Location::fromLatLon($this->lat, $this->lon);
1044 if (is_null($location)) { // still haven't found it!
1045 if (!empty($this->location)) {
1046 $location = Location::fromName($this->location);
1053 function hasRole($name)
1056 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1057 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1059 $has_role = !empty($role);
1060 Event::handle('EndHasRole', array($this, $name, $has_role));
1065 function grantRole($name)
1067 if (Event::handle('StartGrantRole', array($this, $name))) {
1069 $role = new Profile_role();
1071 $role->profile_id = $this->id;
1072 $role->role = $name;
1073 $role->created = common_sql_now();
1075 $result = $role->insert();
1078 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1081 if ($name == 'owner') {
1082 User::blow('user:site_owner');
1085 Event::handle('EndGrantRole', array($this, $name));
1091 function revokeRole($name)
1093 if (Event::handle('StartRevokeRole', array($this, $name))) {
1095 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1099 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1100 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1101 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1104 $result = $role->delete();
1107 common_log_db_error($role, 'DELETE', __FILE__);
1108 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1109 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1110 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1113 if ($name == 'owner') {
1114 User::blow('user:site_owner');
1117 Event::handle('EndRevokeRole', array($this, $name));
1123 function isSandboxed()
1125 return $this->hasRole(Profile_role::SANDBOXED);
1128 function isSilenced()
1130 return $this->hasRole(Profile_role::SILENCED);
1135 $this->grantRole(Profile_role::SANDBOXED);
1138 function unsandbox()
1140 $this->revokeRole(Profile_role::SANDBOXED);
1145 $this->grantRole(Profile_role::SILENCED);
1146 if (common_config('notice', 'hidespam')) {
1147 $this->flushVisibility();
1151 function unsilence()
1153 $this->revokeRole(Profile_role::SILENCED);
1154 if (common_config('notice', 'hidespam')) {
1155 $this->flushVisibility();
1159 function flushVisibility()
1162 $stream = new ProfileNoticeStream($this, $this);
1163 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1164 foreach ($ids as $id) {
1165 self::blow('notice:in-scope-for:%d:null', $id);
1170 * Does this user have the right to do X?
1172 * With our role-based authorization, this is merely a lookup for whether the user
1173 * has a particular role. The implementation currently uses a switch statement
1174 * to determine if the user has the pre-defined role to exercise the right. Future
1175 * implementations may allow per-site roles, and different mappings of roles to rights.
1177 * @param $right string Name of the right, usually a constant in class Right
1178 * @return boolean whether the user has the right in question
1180 function hasRight($right)
1184 if ($this->hasRole(Profile_role::DELETED)) {
1188 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1191 case Right::DELETEOTHERSNOTICE:
1192 case Right::MAKEGROUPADMIN:
1193 case Right::SANDBOXUSER:
1194 case Right::SILENCEUSER:
1195 case Right::DELETEUSER:
1196 case Right::DELETEGROUP:
1197 case Right::TRAINSPAM:
1198 case Right::REVIEWSPAM:
1199 $result = $this->hasRole(Profile_role::MODERATOR);
1201 case Right::CONFIGURESITE:
1202 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1204 case Right::GRANTROLE:
1205 case Right::REVOKEROLE:
1206 $result = $this->hasRole(Profile_role::OWNER);
1208 case Right::NEWNOTICE:
1209 case Right::NEWMESSAGE:
1210 case Right::SUBSCRIBE:
1211 case Right::CREATEGROUP:
1212 $result = !$this->isSilenced();
1214 case Right::PUBLICNOTICE:
1215 case Right::EMAILONREPLY:
1216 case Right::EMAILONSUBSCRIBE:
1217 case Right::EMAILONFAVE:
1218 $result = !$this->isSandboxed();
1220 case Right::WEBLOGIN:
1221 $result = !$this->isSilenced();
1224 $result = !$this->isSilenced();
1226 case Right::BACKUPACCOUNT:
1227 $result = common_config('profile', 'backup');
1229 case Right::RESTOREACCOUNT:
1230 $result = common_config('profile', 'restore');
1232 case Right::DELETEACCOUNT:
1233 $result = common_config('profile', 'delete');
1235 case Right::MOVEACCOUNT:
1236 $result = common_config('profile', 'move');
1246 function hasRepeated($notice_id)
1248 // XXX: not really a pkey, but should work
1250 $notice = Memcached_DataObject::pkeyGet('Notice',
1251 array('profile_id' => $this->id,
1252 'repeat_of' => $notice_id));
1254 return !empty($notice);
1258 * Returns an XML string fragment with limited profile information
1259 * as an Atom <author> element.
1261 * Assumes that Atom has been previously set up as the base namespace.
1263 * @param Profile $cur the current authenticated user
1267 function asAtomAuthor($cur = null)
1269 $xs = new XMLStringer(true);
1271 $xs->elementStart('author');
1272 $xs->element('name', null, $this->nickname);
1273 $xs->element('uri', null, $this->getUri());
1276 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1277 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1278 $xs->element('statusnet:profile_info', $attrs, null);
1280 $xs->elementEnd('author');
1282 return $xs->getString();
1286 * Extra profile info for atom entries
1288 * Clients use some extra profile info in the atom stream.
1289 * This gives it to them.
1291 * @param User $cur Current user
1293 * @return array representation of <statusnet:profile_info> element or null
1296 function profileInfo($cur)
1298 $profileInfoAttr = array('local_id' => $this->id);
1301 // Whether the current user is a subscribed to this profile
1302 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1303 // Whether the current user is has blocked this profile
1304 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1307 return array('statusnet:profile_info', $profileInfoAttr, null);
1311 * Returns an XML string fragment with profile information as an
1312 * Activity Streams <activity:actor> element.
1314 * Assumes that 'activity' namespace has been previously defined.
1318 function asActivityActor()
1320 return $this->asActivityNoun('actor');
1324 * Returns an XML string fragment with profile information as an
1325 * Activity Streams noun object with the given element type.
1327 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1328 * previously defined.
1330 * @param string $element one of 'actor', 'subject', 'object', 'target'
1334 function asActivityNoun($element)
1336 $noun = ActivityObject::fromProfile($this);
1337 return $noun->asString('activity:' . $element);
1341 * Returns the best URI for a profile. Plugins may override.
1343 * @return string $uri
1349 // give plugins a chance to set the URI
1350 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1352 // check for a local user first
1353 $user = User::staticGet('id', $this->id);
1355 if (!empty($user)) {
1359 Event::handle('EndGetProfileUri', array($this, &$uri));
1365 function hasBlocked($other)
1367 $block = Profile_block::get($this->id, $other->id);
1369 if (empty($block)) {
1378 function getAtomFeed()
1382 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1383 $user = User::staticGet('id', $this->id);
1384 if (!empty($user)) {
1385 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1386 'format' => 'atom'));
1388 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1394 static function fromURI($uri)
1398 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1399 // Get a local user or remote (OMB 0.1) profile
1400 $user = User::staticGet('uri', $uri);
1401 if (!empty($user)) {
1402 $profile = $user->getProfile();
1404 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1410 function canRead(Notice $notice)
1412 if ($notice->scope & Notice::SITE_SCOPE) {
1413 $user = $this->getUser();
1419 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1420 $replies = $notice->getReplies();
1422 if (!in_array($this->id, $replies)) {
1423 $groups = $notice->getGroups();
1427 foreach ($groups as $group) {
1428 if ($this->isMember($group)) {
1440 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1441 $author = $notice->getProfile();
1442 if (!Subscription::exists($this, $author)) {
1450 static function current()
1452 $user = common_current_user();
1456 $profile = $user->getProfile();
1462 * Magic function called at serialize() time.
1464 * We use this to drop a couple process-specific references
1465 * from DB_DataObject which can cause trouble in future
1468 * @return array of variable names to include in serialization.
1473 $vars = parent::__sleep();
1474 $skip = array('_user', '_avatars');
1475 return array_diff($vars, $skip);
1478 static function fillAvatars(&$profiles, $width)
1481 foreach ($profiles as $profile) {
1482 if (!empty($profile)) {
1483 $ids[] = $profile->id;
1487 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1488 'height' => $width));
1490 foreach ($profiles as $profile) {
1491 if (!empty($profile)) { // ???
1492 $profile->_fillAvatar($width, $avatars[$profile->id]);
1497 // Can't seem to find how to fix this.
1499 function getProfile()
1504 static function pivotGet($key, $values, $otherCols=array()) {
1505 return Memcached_DataObject::pivotGet('Profile', $key, $values, $otherCols);