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 function getAvatar($width, $height=null)
123 if (is_null($height)) {
127 $avatar = $this->_getAvatar($width);
129 if (empty($avatar)) {
131 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
132 $avatar = Avatar::pkeyGet(
134 'profile_id' => $this->id,
139 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
142 $this->_fillAvatar($width, $avatar);
148 // XXX: @Fix me gargargar
149 function _getAvatar($width)
151 if (empty($this->_avatars)) {
152 $this->_avatars = array();
155 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
156 // the previously used profile! Please shoot me now! --Zach
157 if (array_key_exists($width, $this->_avatars)) {
158 // Don't return cached avatar unless it's really for this profile
159 if ($this->_avatars[$width]->profile_id == $this->id) {
160 return $this->_avatars[$width];
167 function _fillAvatar($width, $avatar)
169 //common_debug("Storing avatar of width: {$avatar->width} and profile_id {$avatar->profile_id} in profile {$this->id}.");
170 $this->_avatars[$width] = $avatar;
174 function getOriginalAvatar()
176 $pkey = array('profile_id' => $this->id,
178 $avatar = Avatar::pkeyGet($pkey);
179 if (!empty($avatar)) {
186 function setOriginal($filename)
188 $imagefile = new ImageFile($this->id, Avatar::path($filename));
190 $avatar = new Avatar();
191 $avatar->profile_id = $this->id;
192 $avatar->width = $imagefile->width;
193 $avatar->height = $imagefile->height;
194 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
195 $avatar->filename = $filename;
196 $avatar->original = true;
197 $avatar->url = Avatar::url($filename);
198 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
200 // XXX: start a transaction here
202 if (!$this->delete_avatars() || !$avatar->insert()) {
203 @unlink(Avatar::path($filename));
207 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
208 // We don't do a scaled one if original is our scaled size
209 if (!($avatar->width == $size && $avatar->height == $size)) {
210 $scaled_filename = $imagefile->resize($size);
212 //$scaled = DB_DataObject::factory('avatar');
213 $scaled = new Avatar();
214 $scaled->profile_id = $this->id;
215 $scaled->width = $size;
216 $scaled->height = $size;
217 $scaled->original = false;
218 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
219 $scaled->filename = $scaled_filename;
220 $scaled->url = Avatar::url($scaled_filename);
221 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
223 if (!$scaled->insert()) {
233 * Delete attached avatars for this user from the database and filesystem.
234 * This should be used instead of a batch delete() to ensure that files
235 * get removed correctly.
237 * @param boolean $original true to delete only the original-size file
240 function delete_avatars($original=true)
242 $avatar = new Avatar();
243 $avatar->profile_id = $this->id;
245 while ($avatar->fetch()) {
246 if ($avatar->original) {
247 if ($original == false) {
257 * Gets either the full name (if filled) or the nickname.
261 function getBestName()
263 return ($this->fullname) ? $this->fullname : $this->nickname;
267 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
268 * if no fullname is provided.
272 function getFancyName()
274 if ($this->fullname) {
275 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
276 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
278 return $this->nickname;
283 * Get the most recent notice posted by this user, if any.
285 * @return mixed Notice or null
287 function getCurrentNotice()
289 $notice = $this->getNotices(0, 1);
291 if ($notice->fetch()) {
292 if ($notice instanceof ArrayWrapper) {
293 // hack for things trying to work with single notices
294 return $notice->_items[0];
302 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
304 $stream = new TaggedProfileNoticeStream($this, $tag);
306 return $stream->getNotices($offset, $limit, $since_id, $max_id);
309 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
311 $stream = new ProfileNoticeStream($this);
313 return $stream->getNotices($offset, $limit, $since_id, $max_id);
316 function isMember($group)
318 $groups = $this->getGroups(0, null);
319 $gs = $groups->fetchAll();
320 foreach ($gs as $g) {
321 if ($group->id == $g->id) {
328 function isAdmin($group)
330 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
331 'group_id' => $group->id));
332 return (!empty($gm) && $gm->is_admin);
335 function isPendingMember($group)
337 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
338 'group_id' => $group->id));
339 return !empty($request);
342 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
346 $keypart = sprintf('profile:groups:%d', $this->id);
348 $idstring = self::cacheGet($keypart);
350 if ($idstring !== false) {
351 $ids = explode(',', $idstring);
353 $gm = new Group_member();
355 $gm->profile_id = $this->id;
358 while ($gm->fetch()) {
359 $ids[] = $gm->group_id;
363 self::cacheSet($keypart, implode(',', $ids));
366 if (!is_null($offset) && !is_null($limit)) {
367 $ids = array_slice($ids, $offset, $limit);
370 return User_group::multiGet('id', $ids);
373 function isTagged($peopletag)
375 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
376 'tagged' => $this->id,
377 'tag' => $peopletag->tag));
381 function canTag($tagged)
383 if (empty($tagged)) {
387 if ($tagged->id == $this->id) {
391 $all = common_config('peopletag', 'allow_tagging', 'all');
392 $local = common_config('peopletag', 'allow_tagging', 'local');
393 $remote = common_config('peopletag', 'allow_tagging', 'remote');
394 $subs = common_config('peopletag', 'allow_tagging', 'subs');
400 $tagged_user = $tagged->getUser();
401 if (!empty($tagged_user)) {
406 return (Subscription::exists($this, $tagged) ||
407 Subscription::exists($tagged, $this));
408 } else if ($remote) {
414 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
418 $keypart = sprintf('profile:lists:%d', $this->id);
420 $idstr = self::cacheGet($keypart);
422 if ($idstr !== false) {
423 $ids = explode(',', $idstr);
425 $list = new Profile_list();
427 $list->selectAdd('id');
428 $list->tagger = $this->id;
429 $list->selectAdd('id as "cursor"');
432 $list->whereAdd('id > '.$since_id);
436 $list->whereAdd('id <= '.$max_id);
439 if($offset>=0 && !is_null($limit)) {
440 $list->limit($offset, $limit);
443 $list->orderBy('id DESC');
446 while ($list->fetch()) {
451 self::cacheSet($keypart, implode(',', $ids));
454 $showPrivate = (($auth_user instanceof User ||
455 $auth_user instanceof Profile) &&
456 $auth_user->id === $this->id);
460 foreach ($ids as $id) {
461 $list = Profile_list::getKV('id', $id);
463 ($showPrivate || !$list->private)) {
465 if (!isset($list->cursor)) {
466 $list->cursor = $list->id;
473 return new ArrayWrapper($lists);
477 * Get tags that other people put on this profile, in reverse-chron order
479 * @param (Profile|User) $auth_user Authorized user (used for privacy)
480 * @param int $offset Offset from latest
481 * @param int $limit Max number to get
482 * @param datetime $since_id max date
483 * @param datetime $max_id min date
485 * @return Profile_list resulting lists
488 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
490 $list = new Profile_list();
492 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
493 'from profile_tag join profile_list '.
494 'on (profile_tag.tagger = profile_list.tagger ' .
495 ' and profile_tag.tag = profile_list.tag) ' .
496 'where profile_tag.tagged = %d ',
500 if ($auth_user instanceof User || $auth_user instanceof Profile) {
501 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
502 'OR ( profile_list.tagger = %d AND ' .
503 'profile_list.private = true ) )',
506 $qry .= 'AND profile_list.private = 0 ';
510 $qry .= sprintf('AND (cursor > %d) ', $since_id);
514 $qry .= sprintf('AND (cursor < %d) ', $max_id);
517 $qry .= 'ORDER BY profile_tag.modified DESC ';
519 if ($offset >= 0 && !is_null($limit)) {
520 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
527 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
529 $tags = new Profile_list();
530 $tags->private = true;
531 $tags->tagger = $this->id;
534 $tags->whereAdd('id > '.$since_id);
538 $tags->whereAdd('id <= '.$max_id);
541 if($offset>=0 && !is_null($limit)) {
542 $tags->limit($offset, $limit);
545 $tags->orderBy('id DESC');
551 function hasLocalTags()
553 $tags = new Profile_tag();
555 $tags->joinAdd(array('tagger', 'user:id'));
556 $tags->whereAdd('tagged = '.$this->id);
557 $tags->whereAdd('tagger != '.$this->id);
562 return ($tags->N == 0) ? false : true;
565 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
567 $lists = new Profile_list();
568 $subs = new Profile_tag_subscription();
570 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
572 #@fixme: postgres (round(date_part('epoch', my_date)))
573 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
575 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
578 $lists->whereAdd('cursor > '.$since_id);
582 $lists->whereAdd('cursor <= '.$max_id);
585 if($offset>=0 && !is_null($limit)) {
586 $lists->limit($offset, $limit);
589 $lists->orderBy('"cursor" DESC');
596 * Request to join the given group.
597 * May throw exceptions on failure.
599 * @param User_group $group
600 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
602 function joinGroup(User_group $group)
605 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
606 $join = Group_join_queue::saveNew($this, $group);
608 if (Event::handle('StartJoinGroup', array($group, $this))) {
609 $join = Group_member::join($group->id, $this->id);
610 self::blow('profile:groups:%d', $this->id);
611 self::blow('group:member_ids:%d', $group->id);
612 self::blow('group:member_count:%d', $group->id);
613 Event::handle('EndJoinGroup', array($group, $this));
617 // Send any applicable notifications...
624 * Leave a group that this profile is a member of.
626 * @param User_group $group
628 function leaveGroup(User_group $group)
630 if (Event::handle('StartLeaveGroup', array($group, $this))) {
631 Group_member::leave($group->id, $this->id);
632 self::blow('profile:groups:%d', $this->id);
633 self::blow('group:member_ids:%d', $group->id);
634 self::blow('group:member_count:%d', $group->id);
635 Event::handle('EndLeaveGroup', array($group, $this));
639 function avatarUrl($size=AVATAR_PROFILE_SIZE)
641 $avatar = $this->getAvatar($size);
643 return $avatar->displayUrl();
645 return Avatar::defaultImage($size);
649 function getSubscriptions($offset=0, $limit=null)
651 $subs = Subscription::bySubscriber($this->id,
657 while ($subs->fetch()) {
658 $profile = Profile::getKV($subs->subscribed);
660 $profiles[] = $profile;
664 return new ArrayWrapper($profiles);
667 function getSubscribers($offset=0, $limit=null)
669 $subs = Subscription::bySubscribed($this->id,
675 while ($subs->fetch()) {
676 $profile = Profile::getKV($subs->subscriber);
678 $profiles[] = $profile;
682 return new ArrayWrapper($profiles);
685 function getTaggedSubscribers($tag)
688 'SELECT profile.* ' .
689 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
690 'ON profile.id = subscription.subscriber ' .
691 'AND profile.id = profile_tag.tagged ' .
692 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
693 'WHERE subscription.subscribed = %d ' .
694 'AND subscription.subscribed != subscription.subscriber ' .
695 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
696 'AND profile_list.private = false ' .
697 'ORDER BY subscription.created DESC';
699 $profile = new Profile();
702 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
704 while ($profile->fetch()) {
705 $tagged[] = clone($profile);
711 * Get pending subscribers, who have not yet been approved.
717 function getRequests($offset=0, $limit=null)
720 'SELECT profile.* ' .
721 'FROM profile JOIN subscription_queue '.
722 'ON profile.id = subscription_queue.subscriber ' .
723 'WHERE subscription_queue.subscribed = %d ' .
724 'ORDER BY subscription_queue.created DESC ';
726 if ($limit != null) {
727 if (common_config('db','type') == 'pgsql') {
728 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
730 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
734 $members = new Profile();
736 $members->query(sprintf($qry, $this->id));
740 function subscriptionCount()
742 $c = Cache::instance();
745 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
746 if (is_integer($cnt)) {
751 $sub = new Subscription();
752 $sub->subscriber = $this->id;
754 $cnt = (int) $sub->count('distinct subscribed');
756 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
759 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
765 function subscriberCount()
767 $c = Cache::instance();
769 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
770 if (is_integer($cnt)) {
775 $sub = new Subscription();
776 $sub->subscribed = $this->id;
777 $sub->whereAdd('subscriber != subscribed');
778 $cnt = (int) $sub->count('distinct subscriber');
781 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
788 * Is this profile subscribed to another profile?
790 * @param Profile $other
793 function isSubscribed($other)
795 return Subscription::exists($this, $other);
799 * Check if a pending subscription request is outstanding for this...
801 * @param Profile $other
804 function hasPendingSubscription($other)
806 return Subscription_queue::exists($this, $other);
810 * Are these two profiles subscribed to each other?
812 * @param Profile $other
815 function mutuallySubscribed($other)
817 return $this->isSubscribed($other) &&
818 $other->isSubscribed($this);
821 function hasFave($notice)
823 $fave = Fave::pkeyGet(array('user_id' => $this->id,
824 'notice_id' => $notice->id));
825 return ((is_null($fave)) ? false : true);
830 $c = Cache::instance();
832 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
833 if (is_integer($cnt)) {
839 $faves->user_id = $this->id;
840 $cnt = (int) $faves->count('notice_id');
843 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
849 function noticeCount()
851 $c = Cache::instance();
854 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
855 if (is_integer($cnt)) {
860 $notices = new Notice();
861 $notices->profile_id = $this->id;
862 $cnt = (int) $notices->count('distinct id');
865 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
871 function blowFavesCache()
873 $cache = Cache::instance();
875 // Faves don't happen chronologically, so we need to blow
877 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
878 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
879 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
880 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
882 $this->blowFaveCount();
885 function blowSubscriberCount()
887 $c = Cache::instance();
889 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
893 function blowSubscriptionCount()
895 $c = Cache::instance();
897 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
901 function blowFaveCount()
903 $c = Cache::instance();
905 $c->delete(Cache::key('profile:fave_count:'.$this->id));
909 function blowNoticeCount()
911 $c = Cache::instance();
913 $c->delete(Cache::key('profile:notice_count:'.$this->id));
917 static function maxBio()
919 $biolimit = common_config('profile', 'biolimit');
920 // null => use global limit (distinct from 0!)
921 if (is_null($biolimit)) {
922 $biolimit = common_config('site', 'textlimit');
927 static function bioTooLong($bio)
929 $biolimit = self::maxBio();
930 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
935 $this->_deleteNotices();
936 $this->_deleteSubscriptions();
937 $this->_deleteMessages();
938 $this->_deleteTags();
939 $this->_deleteBlocks();
940 $this->delete_avatars();
942 // Warning: delete() will run on the batch objects,
943 // not on individual objects.
944 $related = array('Reply',
947 Event::handle('ProfileDeleteRelated', array($this, &$related));
949 foreach ($related as $cls) {
951 $inst->profile_id = $this->id;
958 function _deleteNotices()
960 $notice = new Notice();
961 $notice->profile_id = $this->id;
963 if ($notice->find()) {
964 while ($notice->fetch()) {
965 $other = clone($notice);
971 function _deleteSubscriptions()
973 $sub = new Subscription();
974 $sub->subscriber = $this->id;
978 while ($sub->fetch()) {
979 $other = Profile::getKV('id', $sub->subscribed);
983 if ($other->id == $this->id) {
986 Subscription::cancel($this, $other);
989 $subd = new Subscription();
990 $subd->subscribed = $this->id;
993 while ($subd->fetch()) {
994 $other = Profile::getKV('id', $subd->subscriber);
998 if ($other->id == $this->id) {
1001 Subscription::cancel($other, $this);
1004 $self = new Subscription();
1006 $self->subscriber = $this->id;
1007 $self->subscribed = $this->id;
1012 function _deleteMessages()
1014 $msg = new Message();
1015 $msg->from_profile = $this->id;
1018 $msg = new Message();
1019 $msg->to_profile = $this->id;
1023 function _deleteTags()
1025 $tag = new Profile_tag();
1026 $tag->tagged = $this->id;
1030 function _deleteBlocks()
1032 $block = new Profile_block();
1033 $block->blocked = $this->id;
1036 $block = new Group_block();
1037 $block->blocked = $this->id;
1041 // XXX: identical to Notice::getLocation.
1043 function getLocation()
1047 if (!empty($this->location_id) && !empty($this->location_ns)) {
1048 $location = Location::fromId($this->location_id, $this->location_ns);
1051 if (is_null($location)) { // no ID, or Location::fromId() failed
1052 if (!empty($this->lat) && !empty($this->lon)) {
1053 $location = Location::fromLatLon($this->lat, $this->lon);
1057 if (is_null($location)) { // still haven't found it!
1058 if (!empty($this->location)) {
1059 $location = Location::fromName($this->location);
1066 function hasRole($name)
1069 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1070 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1072 $has_role = !empty($role);
1073 Event::handle('EndHasRole', array($this, $name, $has_role));
1078 function grantRole($name)
1080 if (Event::handle('StartGrantRole', array($this, $name))) {
1082 $role = new Profile_role();
1084 $role->profile_id = $this->id;
1085 $role->role = $name;
1086 $role->created = common_sql_now();
1088 $result = $role->insert();
1091 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1094 if ($name == 'owner') {
1095 User::blow('user:site_owner');
1098 Event::handle('EndGrantRole', array($this, $name));
1104 function revokeRole($name)
1106 if (Event::handle('StartRevokeRole', array($this, $name))) {
1108 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1112 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1113 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1114 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1117 $result = $role->delete();
1120 common_log_db_error($role, 'DELETE', __FILE__);
1121 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1122 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1123 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1126 if ($name == 'owner') {
1127 User::blow('user:site_owner');
1130 Event::handle('EndRevokeRole', array($this, $name));
1136 function isSandboxed()
1138 return $this->hasRole(Profile_role::SANDBOXED);
1141 function isSilenced()
1143 return $this->hasRole(Profile_role::SILENCED);
1148 $this->grantRole(Profile_role::SANDBOXED);
1151 function unsandbox()
1153 $this->revokeRole(Profile_role::SANDBOXED);
1158 $this->grantRole(Profile_role::SILENCED);
1159 if (common_config('notice', 'hidespam')) {
1160 $this->flushVisibility();
1164 function unsilence()
1166 $this->revokeRole(Profile_role::SILENCED);
1167 if (common_config('notice', 'hidespam')) {
1168 $this->flushVisibility();
1172 function flushVisibility()
1175 $stream = new ProfileNoticeStream($this, $this);
1176 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1177 foreach ($ids as $id) {
1178 self::blow('notice:in-scope-for:%d:null', $id);
1183 * Does this user have the right to do X?
1185 * With our role-based authorization, this is merely a lookup for whether the user
1186 * has a particular role. The implementation currently uses a switch statement
1187 * to determine if the user has the pre-defined role to exercise the right. Future
1188 * implementations may allow per-site roles, and different mappings of roles to rights.
1190 * @param $right string Name of the right, usually a constant in class Right
1191 * @return boolean whether the user has the right in question
1193 function hasRight($right)
1197 if ($this->hasRole(Profile_role::DELETED)) {
1201 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1204 case Right::DELETEOTHERSNOTICE:
1205 case Right::MAKEGROUPADMIN:
1206 case Right::SANDBOXUSER:
1207 case Right::SILENCEUSER:
1208 case Right::DELETEUSER:
1209 case Right::DELETEGROUP:
1210 case Right::TRAINSPAM:
1211 case Right::REVIEWSPAM:
1212 $result = $this->hasRole(Profile_role::MODERATOR);
1214 case Right::CONFIGURESITE:
1215 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1217 case Right::GRANTROLE:
1218 case Right::REVOKEROLE:
1219 $result = $this->hasRole(Profile_role::OWNER);
1221 case Right::NEWNOTICE:
1222 case Right::NEWMESSAGE:
1223 case Right::SUBSCRIBE:
1224 case Right::CREATEGROUP:
1225 $result = !$this->isSilenced();
1227 case Right::PUBLICNOTICE:
1228 case Right::EMAILONREPLY:
1229 case Right::EMAILONSUBSCRIBE:
1230 case Right::EMAILONFAVE:
1231 $result = !$this->isSandboxed();
1233 case Right::WEBLOGIN:
1234 $result = !$this->isSilenced();
1237 $result = !$this->isSilenced();
1239 case Right::BACKUPACCOUNT:
1240 $result = common_config('profile', 'backup');
1242 case Right::RESTOREACCOUNT:
1243 $result = common_config('profile', 'restore');
1245 case Right::DELETEACCOUNT:
1246 $result = common_config('profile', 'delete');
1248 case Right::MOVEACCOUNT:
1249 $result = common_config('profile', 'move');
1259 function hasRepeated($notice_id)
1261 // XXX: not really a pkey, but should work
1263 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1264 'repeat_of' => $notice_id));
1266 return !empty($notice);
1270 * Returns an XML string fragment with limited profile information
1271 * as an Atom <author> element.
1273 * Assumes that Atom has been previously set up as the base namespace.
1275 * @param Profile $cur the current authenticated user
1279 function asAtomAuthor($cur = null)
1281 $xs = new XMLStringer(true);
1283 $xs->elementStart('author');
1284 $xs->element('name', null, $this->nickname);
1285 $xs->element('uri', null, $this->getUri());
1288 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1289 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1290 $xs->element('statusnet:profile_info', $attrs, null);
1292 $xs->elementEnd('author');
1294 return $xs->getString();
1298 * Extra profile info for atom entries
1300 * Clients use some extra profile info in the atom stream.
1301 * This gives it to them.
1303 * @param User $cur Current user
1305 * @return array representation of <statusnet:profile_info> element or null
1308 function profileInfo($cur)
1310 $profileInfoAttr = array('local_id' => $this->id);
1313 // Whether the current user is a subscribed to this profile
1314 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1315 // Whether the current user is has blocked this profile
1316 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1319 return array('statusnet:profile_info', $profileInfoAttr, null);
1323 * Returns an XML string fragment with profile information as an
1324 * Activity Streams <activity:actor> element.
1326 * Assumes that 'activity' namespace has been previously defined.
1330 function asActivityActor()
1332 return $this->asActivityNoun('actor');
1336 * Returns an XML string fragment with profile information as an
1337 * Activity Streams noun object with the given element type.
1339 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1340 * previously defined.
1342 * @param string $element one of 'actor', 'subject', 'object', 'target'
1346 function asActivityNoun($element)
1348 $noun = ActivityObject::fromProfile($this);
1349 return $noun->asString('activity:' . $element);
1353 * Returns the best URI for a profile. Plugins may override.
1355 * @return string $uri
1361 // give plugins a chance to set the URI
1362 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1364 // check for a local user first
1365 $user = User::getKV('id', $this->id);
1367 if (!empty($user)) {
1371 Event::handle('EndGetProfileUri', array($this, &$uri));
1377 function hasBlocked($other)
1379 $block = Profile_block::exists($this, $other);
1380 return !empty($block);
1383 function getAtomFeed()
1387 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1388 $user = User::getKV('id', $this->id);
1389 if (!empty($user)) {
1390 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1391 'format' => 'atom'));
1393 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1399 static function fromURI($uri)
1403 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1404 // Get a local user or remote (OMB 0.1) profile
1405 $user = User::getKV('uri', $uri);
1406 if (!empty($user)) {
1407 $profile = $user->getProfile();
1409 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1415 function canRead(Notice $notice)
1417 if ($notice->scope & Notice::SITE_SCOPE) {
1418 $user = $this->getUser();
1424 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1425 $replies = $notice->getReplies();
1427 if (!in_array($this->id, $replies)) {
1428 $groups = $notice->getGroups();
1432 foreach ($groups as $group) {
1433 if ($this->isMember($group)) {
1445 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1446 $author = $notice->getProfile();
1447 if (!Subscription::exists($this, $author)) {
1455 static function current()
1457 $user = common_current_user();
1461 $profile = $user->getProfile();
1467 * Magic function called at serialize() time.
1469 * We use this to drop a couple process-specific references
1470 * from DB_DataObject which can cause trouble in future
1473 * @return array of variable names to include in serialization.
1478 $vars = parent::__sleep();
1479 $skip = array('_user', '_avatars');
1480 return array_diff($vars, $skip);
1483 static function fillAvatars(&$profiles, $width)
1486 foreach ($profiles as $profile) {
1487 if (!empty($profile)) {
1488 $ids[] = $profile->id;
1492 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1493 'height' => $width));
1495 foreach ($profiles as $profile) {
1496 if (!empty($profile)) { // ???
1497 $profile->_fillAvatar($width, $avatars[$profile->id]);
1502 // Can't seem to find how to fix this.
1504 function getProfile()