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
47 public static function schemaDef()
50 'description' => 'local and remote users have profiles',
52 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
53 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
54 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
55 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
56 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
57 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
58 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
59 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
60 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
61 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
62 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
64 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
65 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
67 'primary key' => array('id'),
69 'profile_nickname_idx' => array('nickname'),
73 // Add a fulltext index
75 if (common_config('search', 'type') == 'fulltext') {
76 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
82 /* the code above is auto generated do not remove the tag below */
85 public static function getByEmail($email)
87 // in the future, profiles should have emails stored...
88 $user = User::getKV('email', $email);
89 if (!($user instanceof User)) {
90 throw new NoSuchUserException(array('email'=>$email));
92 return $user->getProfile();
95 protected $_user = -1; // Uninitialized value distinct from null
97 public function getUser()
99 if ($this->_user === -1) {
100 $this->_user = User::getKV('id', $this->id);
102 if (!($this->_user instanceof User)) {
103 throw new NoSuchUserException(array('id'=>$this->id));
109 public function isLocal()
113 } catch (NoSuchUserException $e) {
121 public function getAvatar($width, $height=null)
123 if (is_null($height)) {
127 $avatar = $this->_getAvatar($width);
129 if (empty($avatar)) {
130 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
131 $avatar = Avatar::pkeyGet(
133 'profile_id' => $this->id,
138 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
141 // if-empty within an if-empty? Let's find a prettier solution...
142 if (empty($avatar)) {
143 // Obviously we can't find an avatar, so let's resize the original!
145 $avatar = Avatar::newSize($this, $width);
146 } catch (Exception $e) {
147 // Could not generate a resized avatar. How do we handle it?
151 // cache the avatar for future use
152 $this->_fillAvatar($width, $avatar);
158 // XXX: @Fix me gargargar
159 function _getAvatar($width)
161 if (empty($this->_avatars)) {
162 $this->_avatars = array();
165 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
166 // the previously used profile! Please shoot me now! --Zach
167 if (array_key_exists($width, $this->_avatars)) {
168 // Don't return cached avatar unless it's really for this profile
169 if ($this->_avatars[$width]->profile_id == $this->id) {
170 return $this->_avatars[$width];
177 protected function _fillAvatar($width, Avatar $avatar)
179 // This avoids storing null values, a problem report in issue #3478
180 $this->_avatars[$width] = $avatar;
183 // For backwards compatibility only!
184 public function getOriginalAvatar()
187 return Avatar::getOriginal($this);
188 } catch (Exception $e) {
193 function setOriginal($filename)
195 $imagefile = new ImageFile($this->id, Avatar::path($filename));
197 $avatar = new Avatar();
198 $avatar->profile_id = $this->id;
199 $avatar->width = $imagefile->width;
200 $avatar->height = $imagefile->height;
201 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
202 $avatar->filename = $filename;
203 $avatar->original = true;
204 $avatar->url = Avatar::url($filename);
205 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
207 // XXX: start a transaction here
209 if (!$this->delete_avatars() || !$avatar->insert()) {
210 @unlink(Avatar::path($filename));
214 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
215 // We don't do a scaled one if original is our scaled size
216 if (!($avatar->width == $size && $avatar->height == $size)) {
218 Avatar::newSize($this, $size);
219 } catch (Exception $e) {
220 // should we abort the generation and live without smaller avatars?
229 * Delete attached avatars for this user from the database and filesystem.
230 * This should be used instead of a batch delete() to ensure that files
231 * get removed correctly.
233 * @param boolean $original true to delete only the original-size file
236 function delete_avatars($original=true)
238 $avatar = new Avatar();
239 $avatar->profile_id = $this->id;
241 while ($avatar->fetch()) {
242 if ($avatar->original) {
243 if ($original == false) {
253 * Gets either the full name (if filled) or the nickname.
257 function getBestName()
259 return ($this->fullname) ? $this->fullname : $this->nickname;
263 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
264 * if no fullname is provided.
268 function getFancyName()
270 if ($this->fullname) {
271 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
272 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
274 return $this->nickname;
279 * Get the most recent notice posted by this user, if any.
281 * @return mixed Notice or null
283 function getCurrentNotice()
285 $notice = $this->getNotices(0, 1);
287 if ($notice->fetch()) {
288 if ($notice instanceof ArrayWrapper) {
289 // hack for things trying to work with single notices
290 return $notice->_items[0];
298 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
300 $stream = new TaggedProfileNoticeStream($this, $tag);
302 return $stream->getNotices($offset, $limit, $since_id, $max_id);
305 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
307 $stream = new ProfileNoticeStream($this);
309 return $stream->getNotices($offset, $limit, $since_id, $max_id);
312 function isMember($group)
314 $groups = $this->getGroups(0, null);
315 $gs = $groups->fetchAll();
316 foreach ($gs as $g) {
317 if ($group->id == $g->id) {
324 function isAdmin($group)
326 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
327 'group_id' => $group->id));
328 return (!empty($gm) && $gm->is_admin);
331 function isPendingMember($group)
333 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
334 'group_id' => $group->id));
335 return !empty($request);
338 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
342 $keypart = sprintf('profile:groups:%d', $this->id);
344 $idstring = self::cacheGet($keypart);
346 if ($idstring !== false) {
347 $ids = explode(',', $idstring);
349 $gm = new Group_member();
351 $gm->profile_id = $this->id;
354 while ($gm->fetch()) {
355 $ids[] = $gm->group_id;
359 self::cacheSet($keypart, implode(',', $ids));
362 if (!is_null($offset) && !is_null($limit)) {
363 $ids = array_slice($ids, $offset, $limit);
366 return User_group::multiGet('id', $ids);
369 function isTagged($peopletag)
371 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
372 'tagged' => $this->id,
373 'tag' => $peopletag->tag));
377 function canTag($tagged)
379 if (empty($tagged)) {
383 if ($tagged->id == $this->id) {
387 $all = common_config('peopletag', 'allow_tagging', 'all');
388 $local = common_config('peopletag', 'allow_tagging', 'local');
389 $remote = common_config('peopletag', 'allow_tagging', 'remote');
390 $subs = common_config('peopletag', 'allow_tagging', 'subs');
396 $tagged_user = $tagged->getUser();
397 if (!empty($tagged_user)) {
402 return (Subscription::exists($this, $tagged) ||
403 Subscription::exists($tagged, $this));
404 } else if ($remote) {
410 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
414 $keypart = sprintf('profile:lists:%d', $this->id);
416 $idstr = self::cacheGet($keypart);
418 if ($idstr !== false) {
419 $ids = explode(',', $idstr);
421 $list = new Profile_list();
423 $list->selectAdd('id');
424 $list->tagger = $this->id;
425 $list->selectAdd('id as "cursor"');
428 $list->whereAdd('id > '.$since_id);
432 $list->whereAdd('id <= '.$max_id);
435 if($offset>=0 && !is_null($limit)) {
436 $list->limit($offset, $limit);
439 $list->orderBy('id DESC');
442 while ($list->fetch()) {
447 self::cacheSet($keypart, implode(',', $ids));
450 $showPrivate = (($auth_user instanceof User ||
451 $auth_user instanceof Profile) &&
452 $auth_user->id === $this->id);
456 foreach ($ids as $id) {
457 $list = Profile_list::getKV('id', $id);
459 ($showPrivate || !$list->private)) {
461 if (!isset($list->cursor)) {
462 $list->cursor = $list->id;
469 return new ArrayWrapper($lists);
473 * Get tags that other people put on this profile, in reverse-chron order
475 * @param (Profile|User) $auth_user Authorized user (used for privacy)
476 * @param int $offset Offset from latest
477 * @param int $limit Max number to get
478 * @param datetime $since_id max date
479 * @param datetime $max_id min date
481 * @return Profile_list resulting lists
484 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
486 $list = new Profile_list();
488 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
489 'from profile_tag join profile_list '.
490 'on (profile_tag.tagger = profile_list.tagger ' .
491 ' and profile_tag.tag = profile_list.tag) ' .
492 'where profile_tag.tagged = %d ',
496 if ($auth_user instanceof User || $auth_user instanceof Profile) {
497 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
498 'OR ( profile_list.tagger = %d AND ' .
499 'profile_list.private = true ) )',
502 $qry .= 'AND profile_list.private = 0 ';
506 $qry .= sprintf('AND (cursor > %d) ', $since_id);
510 $qry .= sprintf('AND (cursor < %d) ', $max_id);
513 $qry .= 'ORDER BY profile_tag.modified DESC ';
515 if ($offset >= 0 && !is_null($limit)) {
516 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
523 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
525 $tags = new Profile_list();
526 $tags->private = true;
527 $tags->tagger = $this->id;
530 $tags->whereAdd('id > '.$since_id);
534 $tags->whereAdd('id <= '.$max_id);
537 if($offset>=0 && !is_null($limit)) {
538 $tags->limit($offset, $limit);
541 $tags->orderBy('id DESC');
547 function hasLocalTags()
549 $tags = new Profile_tag();
551 $tags->joinAdd(array('tagger', 'user:id'));
552 $tags->whereAdd('tagged = '.$this->id);
553 $tags->whereAdd('tagger != '.$this->id);
558 return ($tags->N == 0) ? false : true;
561 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
563 $lists = new Profile_list();
564 $subs = new Profile_tag_subscription();
566 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
568 #@fixme: postgres (round(date_part('epoch', my_date)))
569 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
571 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
574 $lists->whereAdd('cursor > '.$since_id);
578 $lists->whereAdd('cursor <= '.$max_id);
581 if($offset>=0 && !is_null($limit)) {
582 $lists->limit($offset, $limit);
585 $lists->orderBy('"cursor" DESC');
592 * Request to join the given group.
593 * May throw exceptions on failure.
595 * @param User_group $group
596 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
598 function joinGroup(User_group $group)
601 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
602 $join = Group_join_queue::saveNew($this, $group);
604 if (Event::handle('StartJoinGroup', array($group, $this))) {
605 $join = Group_member::join($group->id, $this->id);
606 self::blow('profile:groups:%d', $this->id);
607 self::blow('group:member_ids:%d', $group->id);
608 self::blow('group:member_count:%d', $group->id);
609 Event::handle('EndJoinGroup', array($group, $this));
613 // Send any applicable notifications...
620 * Leave a group that this profile is a member of.
622 * @param User_group $group
624 function leaveGroup(User_group $group)
626 if (Event::handle('StartLeaveGroup', array($group, $this))) {
627 Group_member::leave($group->id, $this->id);
628 self::blow('profile:groups:%d', $this->id);
629 self::blow('group:member_ids:%d', $group->id);
630 self::blow('group:member_count:%d', $group->id);
631 Event::handle('EndLeaveGroup', array($group, $this));
635 function avatarUrl($size=AVATAR_PROFILE_SIZE)
637 $avatar = $this->getAvatar($size);
639 return $avatar->displayUrl();
641 return Avatar::defaultImage($size);
645 function getSubscribed($offset=0, $limit=null)
647 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
648 $profiles = Profile::listFind('id', $subs);
652 function getSubscribers($offset=0, $limit=null)
654 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
655 $profiles = Profile::listFind('id', $subs);
659 function getTaggedSubscribers($tag)
662 'SELECT profile.* ' .
663 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
664 'ON profile.id = subscription.subscriber ' .
665 'AND profile.id = profile_tag.tagged ' .
666 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
667 'WHERE subscription.subscribed = %d ' .
668 'AND subscription.subscribed != subscription.subscriber ' .
669 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
670 'AND profile_list.private = false ' .
671 'ORDER BY subscription.created DESC';
673 $profile = new Profile();
676 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
678 while ($profile->fetch()) {
679 $tagged[] = clone($profile);
685 * Get pending subscribers, who have not yet been approved.
691 function getRequests($offset=0, $limit=null)
694 'SELECT profile.* ' .
695 'FROM profile JOIN subscription_queue '.
696 'ON profile.id = subscription_queue.subscriber ' .
697 'WHERE subscription_queue.subscribed = %d ' .
698 'ORDER BY subscription_queue.created DESC ';
700 if ($limit != null) {
701 if (common_config('db','type') == 'pgsql') {
702 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
704 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
708 $members = new Profile();
710 $members->query(sprintf($qry, $this->id));
714 function subscriptionCount()
716 $c = Cache::instance();
719 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
720 if (is_integer($cnt)) {
725 $sub = new Subscription();
726 $sub->subscriber = $this->id;
728 $cnt = (int) $sub->count('distinct subscribed');
730 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
733 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
739 function subscriberCount()
741 $c = Cache::instance();
743 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
744 if (is_integer($cnt)) {
749 $sub = new Subscription();
750 $sub->subscribed = $this->id;
751 $sub->whereAdd('subscriber != subscribed');
752 $cnt = (int) $sub->count('distinct subscriber');
755 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
762 * Is this profile subscribed to another profile?
764 * @param Profile $other
767 function isSubscribed($other)
769 return Subscription::exists($this, $other);
773 * Check if a pending subscription request is outstanding for this...
775 * @param Profile $other
778 function hasPendingSubscription($other)
780 return Subscription_queue::exists($this, $other);
784 * Are these two profiles subscribed to each other?
786 * @param Profile $other
789 function mutuallySubscribed($other)
791 return $this->isSubscribed($other) &&
792 $other->isSubscribed($this);
795 function hasFave($notice)
797 $fave = Fave::pkeyGet(array('user_id' => $this->id,
798 'notice_id' => $notice->id));
799 return ((is_null($fave)) ? false : true);
804 $c = Cache::instance();
806 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
807 if (is_integer($cnt)) {
813 $faves->user_id = $this->id;
814 $cnt = (int) $faves->count('notice_id');
817 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
823 function noticeCount()
825 $c = Cache::instance();
828 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
829 if (is_integer($cnt)) {
834 $notices = new Notice();
835 $notices->profile_id = $this->id;
836 $cnt = (int) $notices->count('distinct id');
839 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
845 function blowFavesCache()
847 $cache = Cache::instance();
849 // Faves don't happen chronologically, so we need to blow
851 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
852 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
853 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
854 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
856 $this->blowFaveCount();
859 function blowSubscriberCount()
861 $c = Cache::instance();
863 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
867 function blowSubscriptionCount()
869 $c = Cache::instance();
871 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
875 function blowFaveCount()
877 $c = Cache::instance();
879 $c->delete(Cache::key('profile:fave_count:'.$this->id));
883 function blowNoticeCount()
885 $c = Cache::instance();
887 $c->delete(Cache::key('profile:notice_count:'.$this->id));
891 static function maxBio()
893 $biolimit = common_config('profile', 'biolimit');
894 // null => use global limit (distinct from 0!)
895 if (is_null($biolimit)) {
896 $biolimit = common_config('site', 'textlimit');
901 static function bioTooLong($bio)
903 $biolimit = self::maxBio();
904 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
909 $this->_deleteNotices();
910 $this->_deleteSubscriptions();
911 $this->_deleteMessages();
912 $this->_deleteTags();
913 $this->_deleteBlocks();
914 $this->delete_avatars();
916 // Warning: delete() will run on the batch objects,
917 // not on individual objects.
918 $related = array('Reply',
921 Event::handle('ProfileDeleteRelated', array($this, &$related));
923 foreach ($related as $cls) {
925 $inst->profile_id = $this->id;
932 function _deleteNotices()
934 $notice = new Notice();
935 $notice->profile_id = $this->id;
937 if ($notice->find()) {
938 while ($notice->fetch()) {
939 $other = clone($notice);
945 function _deleteSubscriptions()
947 $sub = new Subscription();
948 $sub->subscriber = $this->id;
952 while ($sub->fetch()) {
953 $other = Profile::getKV('id', $sub->subscribed);
957 if ($other->id == $this->id) {
960 Subscription::cancel($this, $other);
963 $subd = new Subscription();
964 $subd->subscribed = $this->id;
967 while ($subd->fetch()) {
968 $other = Profile::getKV('id', $subd->subscriber);
972 if ($other->id == $this->id) {
975 Subscription::cancel($other, $this);
978 $self = new Subscription();
980 $self->subscriber = $this->id;
981 $self->subscribed = $this->id;
986 function _deleteMessages()
988 $msg = new Message();
989 $msg->from_profile = $this->id;
992 $msg = new Message();
993 $msg->to_profile = $this->id;
997 function _deleteTags()
999 $tag = new Profile_tag();
1000 $tag->tagged = $this->id;
1004 function _deleteBlocks()
1006 $block = new Profile_block();
1007 $block->blocked = $this->id;
1010 $block = new Group_block();
1011 $block->blocked = $this->id;
1015 // XXX: identical to Notice::getLocation.
1017 function getLocation()
1021 if (!empty($this->location_id) && !empty($this->location_ns)) {
1022 $location = Location::fromId($this->location_id, $this->location_ns);
1025 if (is_null($location)) { // no ID, or Location::fromId() failed
1026 if (!empty($this->lat) && !empty($this->lon)) {
1027 $location = Location::fromLatLon($this->lat, $this->lon);
1031 if (is_null($location)) { // still haven't found it!
1032 if (!empty($this->location)) {
1033 $location = Location::fromName($this->location);
1040 function hasRole($name)
1043 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1044 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1046 $has_role = !empty($role);
1047 Event::handle('EndHasRole', array($this, $name, $has_role));
1052 function grantRole($name)
1054 if (Event::handle('StartGrantRole', array($this, $name))) {
1056 $role = new Profile_role();
1058 $role->profile_id = $this->id;
1059 $role->role = $name;
1060 $role->created = common_sql_now();
1062 $result = $role->insert();
1065 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1068 if ($name == 'owner') {
1069 User::blow('user:site_owner');
1072 Event::handle('EndGrantRole', array($this, $name));
1078 function revokeRole($name)
1080 if (Event::handle('StartRevokeRole', array($this, $name))) {
1082 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1086 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1087 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1088 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1091 $result = $role->delete();
1094 common_log_db_error($role, 'DELETE', __FILE__);
1095 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1096 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1097 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1100 if ($name == 'owner') {
1101 User::blow('user:site_owner');
1104 Event::handle('EndRevokeRole', array($this, $name));
1110 function isSandboxed()
1112 return $this->hasRole(Profile_role::SANDBOXED);
1115 function isSilenced()
1117 return $this->hasRole(Profile_role::SILENCED);
1122 $this->grantRole(Profile_role::SANDBOXED);
1125 function unsandbox()
1127 $this->revokeRole(Profile_role::SANDBOXED);
1132 $this->grantRole(Profile_role::SILENCED);
1133 if (common_config('notice', 'hidespam')) {
1134 $this->flushVisibility();
1138 function unsilence()
1140 $this->revokeRole(Profile_role::SILENCED);
1141 if (common_config('notice', 'hidespam')) {
1142 $this->flushVisibility();
1146 function flushVisibility()
1149 $stream = new ProfileNoticeStream($this, $this);
1150 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1151 foreach ($ids as $id) {
1152 self::blow('notice:in-scope-for:%d:null', $id);
1157 * Does this user have the right to do X?
1159 * With our role-based authorization, this is merely a lookup for whether the user
1160 * has a particular role. The implementation currently uses a switch statement
1161 * to determine if the user has the pre-defined role to exercise the right. Future
1162 * implementations may allow per-site roles, and different mappings of roles to rights.
1164 * @param $right string Name of the right, usually a constant in class Right
1165 * @return boolean whether the user has the right in question
1167 function hasRight($right)
1171 if ($this->hasRole(Profile_role::DELETED)) {
1175 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1178 case Right::DELETEOTHERSNOTICE:
1179 case Right::MAKEGROUPADMIN:
1180 case Right::SANDBOXUSER:
1181 case Right::SILENCEUSER:
1182 case Right::DELETEUSER:
1183 case Right::DELETEGROUP:
1184 case Right::TRAINSPAM:
1185 case Right::REVIEWSPAM:
1186 $result = $this->hasRole(Profile_role::MODERATOR);
1188 case Right::CONFIGURESITE:
1189 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1191 case Right::GRANTROLE:
1192 case Right::REVOKEROLE:
1193 $result = $this->hasRole(Profile_role::OWNER);
1195 case Right::NEWNOTICE:
1196 case Right::NEWMESSAGE:
1197 case Right::SUBSCRIBE:
1198 case Right::CREATEGROUP:
1199 $result = !$this->isSilenced();
1201 case Right::PUBLICNOTICE:
1202 case Right::EMAILONREPLY:
1203 case Right::EMAILONSUBSCRIBE:
1204 case Right::EMAILONFAVE:
1205 $result = !$this->isSandboxed();
1207 case Right::WEBLOGIN:
1208 $result = !$this->isSilenced();
1211 $result = !$this->isSilenced();
1213 case Right::BACKUPACCOUNT:
1214 $result = common_config('profile', 'backup');
1216 case Right::RESTOREACCOUNT:
1217 $result = common_config('profile', 'restore');
1219 case Right::DELETEACCOUNT:
1220 $result = common_config('profile', 'delete');
1222 case Right::MOVEACCOUNT:
1223 $result = common_config('profile', 'move');
1233 function hasRepeated($notice_id)
1235 // XXX: not really a pkey, but should work
1237 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1238 'repeat_of' => $notice_id));
1240 return !empty($notice);
1244 * Returns an XML string fragment with limited profile information
1245 * as an Atom <author> element.
1247 * Assumes that Atom has been previously set up as the base namespace.
1249 * @param Profile $cur the current authenticated user
1253 function asAtomAuthor($cur = null)
1255 $xs = new XMLStringer(true);
1257 $xs->elementStart('author');
1258 $xs->element('name', null, $this->nickname);
1259 $xs->element('uri', null, $this->getUri());
1262 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1263 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1264 $xs->element('statusnet:profile_info', $attrs, null);
1266 $xs->elementEnd('author');
1268 return $xs->getString();
1272 * Extra profile info for atom entries
1274 * Clients use some extra profile info in the atom stream.
1275 * This gives it to them.
1277 * @param User $cur Current user
1279 * @return array representation of <statusnet:profile_info> element or null
1282 function profileInfo($cur)
1284 $profileInfoAttr = array('local_id' => $this->id);
1287 // Whether the current user is a subscribed to this profile
1288 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1289 // Whether the current user is has blocked this profile
1290 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1293 return array('statusnet:profile_info', $profileInfoAttr, null);
1297 * Returns an XML string fragment with profile information as an
1298 * Activity Streams <activity:actor> element.
1300 * Assumes that 'activity' namespace has been previously defined.
1304 function asActivityActor()
1306 return $this->asActivityNoun('actor');
1310 * Returns an XML string fragment with profile information as an
1311 * Activity Streams noun object with the given element type.
1313 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1314 * previously defined.
1316 * @param string $element one of 'actor', 'subject', 'object', 'target'
1320 function asActivityNoun($element)
1322 $noun = ActivityObject::fromProfile($this);
1323 return $noun->asString('activity:' . $element);
1327 * Returns the profile's canonical url, not necessarily a uri/unique id
1329 * @return string $profileurl
1331 public function getUrl()
1333 if (empty($this->profileurl) ||
1334 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1335 throw new InvalidUrlException($this->profileurl);
1337 return $this->profileurl;
1341 * Returns the best URI for a profile. Plugins may override.
1343 * @return string $uri
1345 public function getUri()
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::getKV('id', $this->id);
1355 if (!empty($user)) {
1359 Event::handle('EndGetProfileUri', array($this, &$uri));
1365 function hasBlocked($other)
1367 $block = Profile_block::exists($this, $other);
1368 return !empty($block);
1371 function getAtomFeed()
1375 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1376 $user = User::getKV('id', $this->id);
1377 if (!empty($user)) {
1378 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1379 'format' => 'atom'));
1381 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1387 static function fromURI($uri)
1391 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1392 // Get a local user or remote (OMB 0.1) profile
1393 $user = User::getKV('uri', $uri);
1394 if (!empty($user)) {
1395 $profile = $user->getProfile();
1397 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1403 function canRead(Notice $notice)
1405 if ($notice->scope & Notice::SITE_SCOPE) {
1406 $user = $this->getUser();
1412 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1413 $replies = $notice->getReplies();
1415 if (!in_array($this->id, $replies)) {
1416 $groups = $notice->getGroups();
1420 foreach ($groups as $group) {
1421 if ($this->isMember($group)) {
1433 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1434 $author = $notice->getProfile();
1435 if (!Subscription::exists($this, $author)) {
1443 static function current()
1445 $user = common_current_user();
1449 $profile = $user->getProfile();
1455 * Magic function called at serialize() time.
1457 * We use this to drop a couple process-specific references
1458 * from DB_DataObject which can cause trouble in future
1461 * @return array of variable names to include in serialization.
1466 $vars = parent::__sleep();
1467 $skip = array('_user', '_avatars');
1468 return array_diff($vars, $skip);
1471 static function fillAvatars(&$profiles, $width)
1474 foreach ($profiles as $profile) {
1475 if (!empty($profile)) {
1476 $ids[] = $profile->id;
1480 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1481 'height' => $width));
1483 foreach ($profiles as $profile) {
1484 if (!empty($profile)) { // ???
1485 $profile->_fillAvatar($width, $avatars[$profile->id]);
1490 // Can't seem to find how to fix this.
1492 function getProfile()