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 protected $_user = -1; // Uninitialized value distinct from null
87 public function getUser()
89 if ($this->_user === -1) {
90 $this->_user = User::getKV('id', $this->id);
92 if (!is_a($this->_user, 'User')) {
93 throw new NoSuchUserException(array('id'=>$this->id));
99 public function isLocal()
103 } catch (NoSuchUserException $e) {
111 function getAvatar($width, $height=null)
113 if (is_null($height)) {
117 $avatar = $this->_getAvatar($width);
119 if (empty($avatar)) {
121 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
122 $avatar = Avatar::pkeyGet(
124 'profile_id' => $this->id,
129 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
132 $this->_fillAvatar($width, $avatar);
138 // XXX: @Fix me gargargar
139 function _getAvatar($width)
141 if (empty($this->_avatars)) {
142 $this->_avatars = array();
145 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
146 // the previously used profile! Please shoot me now! --Zach
147 if (array_key_exists($width, $this->_avatars)) {
148 // Don't return cached avatar unless it's really for this profile
149 if ($this->_avatars[$width]->profile_id == $this->id) {
150 return $this->_avatars[$width];
157 function _fillAvatar($width, $avatar)
159 //common_debug("Storing avatar of width: {$avatar->width} and profile_id {$avatar->profile_id} in profile {$this->id}.");
160 $this->_avatars[$width] = $avatar;
164 function getOriginalAvatar()
166 $pkey = array('profile_id' => $this->id,
168 $avatar = Avatar::pkeyGet($pkey);
169 if (!empty($avatar)) {
176 function setOriginal($filename)
178 $imagefile = new ImageFile($this->id, Avatar::path($filename));
180 $avatar = new Avatar();
181 $avatar->profile_id = $this->id;
182 $avatar->width = $imagefile->width;
183 $avatar->height = $imagefile->height;
184 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
185 $avatar->filename = $filename;
186 $avatar->original = true;
187 $avatar->url = Avatar::url($filename);
188 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
190 // XXX: start a transaction here
192 if (!$this->delete_avatars() || !$avatar->insert()) {
193 @unlink(Avatar::path($filename));
197 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
198 // We don't do a scaled one if original is our scaled size
199 if (!($avatar->width == $size && $avatar->height == $size)) {
200 $scaled_filename = $imagefile->resize($size);
202 //$scaled = DB_DataObject::factory('avatar');
203 $scaled = new Avatar();
204 $scaled->profile_id = $this->id;
205 $scaled->width = $size;
206 $scaled->height = $size;
207 $scaled->original = false;
208 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
209 $scaled->filename = $scaled_filename;
210 $scaled->url = Avatar::url($scaled_filename);
211 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
213 if (!$scaled->insert()) {
223 * Delete attached avatars for this user from the database and filesystem.
224 * This should be used instead of a batch delete() to ensure that files
225 * get removed correctly.
227 * @param boolean $original true to delete only the original-size file
230 function delete_avatars($original=true)
232 $avatar = new Avatar();
233 $avatar->profile_id = $this->id;
235 while ($avatar->fetch()) {
236 if ($avatar->original) {
237 if ($original == false) {
247 * Gets either the full name (if filled) or the nickname.
251 function getBestName()
253 return ($this->fullname) ? $this->fullname : $this->nickname;
257 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
258 * if no fullname is provided.
262 function getFancyName()
264 if ($this->fullname) {
265 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
266 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
268 return $this->nickname;
273 * Get the most recent notice posted by this user, if any.
275 * @return mixed Notice or null
277 function getCurrentNotice()
279 $notice = $this->getNotices(0, 1);
281 if ($notice->fetch()) {
282 if ($notice instanceof ArrayWrapper) {
283 // hack for things trying to work with single notices
284 return $notice->_items[0];
292 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
294 $stream = new TaggedProfileNoticeStream($this, $tag);
296 return $stream->getNotices($offset, $limit, $since_id, $max_id);
299 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
301 $stream = new ProfileNoticeStream($this);
303 return $stream->getNotices($offset, $limit, $since_id, $max_id);
306 function isMember($group)
308 $groups = $this->getGroups(0, null);
309 $gs = $groups->fetchAll();
310 foreach ($gs as $g) {
311 if ($group->id == $g->id) {
318 function isAdmin($group)
320 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
321 'group_id' => $group->id));
322 return (!empty($gm) && $gm->is_admin);
325 function isPendingMember($group)
327 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
328 'group_id' => $group->id));
329 return !empty($request);
332 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
336 $keypart = sprintf('profile:groups:%d', $this->id);
338 $idstring = self::cacheGet($keypart);
340 if ($idstring !== false) {
341 $ids = explode(',', $idstring);
343 $gm = new Group_member();
345 $gm->profile_id = $this->id;
348 while ($gm->fetch()) {
349 $ids[] = $gm->group_id;
353 self::cacheSet($keypart, implode(',', $ids));
356 if (!is_null($offset) && !is_null($limit)) {
357 $ids = array_slice($ids, $offset, $limit);
360 return User_group::multiGet('id', $ids);
363 function isTagged($peopletag)
365 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
366 'tagged' => $this->id,
367 'tag' => $peopletag->tag));
371 function canTag($tagged)
373 if (empty($tagged)) {
377 if ($tagged->id == $this->id) {
381 $all = common_config('peopletag', 'allow_tagging', 'all');
382 $local = common_config('peopletag', 'allow_tagging', 'local');
383 $remote = common_config('peopletag', 'allow_tagging', 'remote');
384 $subs = common_config('peopletag', 'allow_tagging', 'subs');
390 $tagged_user = $tagged->getUser();
391 if (!empty($tagged_user)) {
396 return (Subscription::exists($this, $tagged) ||
397 Subscription::exists($tagged, $this));
398 } else if ($remote) {
404 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
408 $keypart = sprintf('profile:lists:%d', $this->id);
410 $idstr = self::cacheGet($keypart);
412 if ($idstr !== false) {
413 $ids = explode(',', $idstr);
415 $list = new Profile_list();
417 $list->selectAdd('id');
418 $list->tagger = $this->id;
419 $list->selectAdd('id as "cursor"');
422 $list->whereAdd('id > '.$since_id);
426 $list->whereAdd('id <= '.$max_id);
429 if($offset>=0 && !is_null($limit)) {
430 $list->limit($offset, $limit);
433 $list->orderBy('id DESC');
436 while ($list->fetch()) {
441 self::cacheSet($keypart, implode(',', $ids));
444 $showPrivate = (($auth_user instanceof User ||
445 $auth_user instanceof Profile) &&
446 $auth_user->id === $this->id);
450 foreach ($ids as $id) {
451 $list = Profile_list::getKV('id', $id);
453 ($showPrivate || !$list->private)) {
455 if (!isset($list->cursor)) {
456 $list->cursor = $list->id;
463 return new ArrayWrapper($lists);
467 * Get tags that other people put on this profile, in reverse-chron order
469 * @param (Profile|User) $auth_user Authorized user (used for privacy)
470 * @param int $offset Offset from latest
471 * @param int $limit Max number to get
472 * @param datetime $since_id max date
473 * @param datetime $max_id min date
475 * @return Profile_list resulting lists
478 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
480 $list = new Profile_list();
482 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
483 'from profile_tag join profile_list '.
484 'on (profile_tag.tagger = profile_list.tagger ' .
485 ' and profile_tag.tag = profile_list.tag) ' .
486 'where profile_tag.tagged = %d ',
490 if ($auth_user instanceof User || $auth_user instanceof Profile) {
491 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
492 'OR ( profile_list.tagger = %d AND ' .
493 'profile_list.private = true ) )',
496 $qry .= 'AND profile_list.private = 0 ';
500 $qry .= sprintf('AND (cursor > %d) ', $since_id);
504 $qry .= sprintf('AND (cursor < %d) ', $max_id);
507 $qry .= 'ORDER BY profile_tag.modified DESC ';
509 if ($offset >= 0 && !is_null($limit)) {
510 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
517 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
519 $tags = new Profile_list();
520 $tags->private = true;
521 $tags->tagger = $this->id;
524 $tags->whereAdd('id > '.$since_id);
528 $tags->whereAdd('id <= '.$max_id);
531 if($offset>=0 && !is_null($limit)) {
532 $tags->limit($offset, $limit);
535 $tags->orderBy('id DESC');
541 function hasLocalTags()
543 $tags = new Profile_tag();
545 $tags->joinAdd(array('tagger', 'user:id'));
546 $tags->whereAdd('tagged = '.$this->id);
547 $tags->whereAdd('tagger != '.$this->id);
552 return ($tags->N == 0) ? false : true;
555 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
557 $lists = new Profile_list();
558 $subs = new Profile_tag_subscription();
560 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
562 #@fixme: postgres (round(date_part('epoch', my_date)))
563 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
565 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
568 $lists->whereAdd('cursor > '.$since_id);
572 $lists->whereAdd('cursor <= '.$max_id);
575 if($offset>=0 && !is_null($limit)) {
576 $lists->limit($offset, $limit);
579 $lists->orderBy('"cursor" DESC');
586 * Request to join the given group.
587 * May throw exceptions on failure.
589 * @param User_group $group
590 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
592 function joinGroup(User_group $group)
595 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
596 $join = Group_join_queue::saveNew($this, $group);
598 if (Event::handle('StartJoinGroup', array($group, $this))) {
599 $join = Group_member::join($group->id, $this->id);
600 self::blow('profile:groups:%d', $this->id);
601 self::blow('group:member_ids:%d', $group->id);
602 self::blow('group:member_count:%d', $group->id);
603 Event::handle('EndJoinGroup', array($group, $this));
607 // Send any applicable notifications...
614 * Leave a group that this profile is a member of.
616 * @param User_group $group
618 function leaveGroup(User_group $group)
620 if (Event::handle('StartLeaveGroup', array($group, $this))) {
621 Group_member::leave($group->id, $this->id);
622 self::blow('profile:groups:%d', $this->id);
623 self::blow('group:member_ids:%d', $group->id);
624 self::blow('group:member_count:%d', $group->id);
625 Event::handle('EndLeaveGroup', array($group, $this));
629 function avatarUrl($size=AVATAR_PROFILE_SIZE)
631 $avatar = $this->getAvatar($size);
633 return $avatar->displayUrl();
635 return Avatar::defaultImage($size);
639 function getSubscriptions($offset=0, $limit=null)
641 $subs = Subscription::bySubscriber($this->id,
647 while ($subs->fetch()) {
648 $profile = Profile::getKV($subs->subscribed);
650 $profiles[] = $profile;
654 return new ArrayWrapper($profiles);
657 function getSubscribers($offset=0, $limit=null)
659 $subs = Subscription::bySubscribed($this->id,
665 while ($subs->fetch()) {
666 $profile = Profile::getKV($subs->subscriber);
668 $profiles[] = $profile;
672 return new ArrayWrapper($profiles);
675 function getTaggedSubscribers($tag)
678 'SELECT profile.* ' .
679 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
680 'ON profile.id = subscription.subscriber ' .
681 'AND profile.id = profile_tag.tagged ' .
682 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
683 'WHERE subscription.subscribed = %d ' .
684 'AND subscription.subscribed != subscription.subscriber ' .
685 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
686 'AND profile_list.private = false ' .
687 'ORDER BY subscription.created DESC';
689 $profile = new Profile();
692 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
694 while ($profile->fetch()) {
695 $tagged[] = clone($profile);
701 * Get pending subscribers, who have not yet been approved.
707 function getRequests($offset=0, $limit=null)
710 'SELECT profile.* ' .
711 'FROM profile JOIN subscription_queue '.
712 'ON profile.id = subscription_queue.subscriber ' .
713 'WHERE subscription_queue.subscribed = %d ' .
714 'ORDER BY subscription_queue.created DESC ';
716 if ($limit != null) {
717 if (common_config('db','type') == 'pgsql') {
718 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
720 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
724 $members = new Profile();
726 $members->query(sprintf($qry, $this->id));
730 function subscriptionCount()
732 $c = Cache::instance();
735 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
736 if (is_integer($cnt)) {
741 $sub = new Subscription();
742 $sub->subscriber = $this->id;
744 $cnt = (int) $sub->count('distinct subscribed');
746 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
749 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
755 function subscriberCount()
757 $c = Cache::instance();
759 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
760 if (is_integer($cnt)) {
765 $sub = new Subscription();
766 $sub->subscribed = $this->id;
767 $sub->whereAdd('subscriber != subscribed');
768 $cnt = (int) $sub->count('distinct subscriber');
771 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
778 * Is this profile subscribed to another profile?
780 * @param Profile $other
783 function isSubscribed($other)
785 return Subscription::exists($this, $other);
789 * Check if a pending subscription request is outstanding for this...
791 * @param Profile $other
794 function hasPendingSubscription($other)
796 return Subscription_queue::exists($this, $other);
800 * Are these two profiles subscribed to each other?
802 * @param Profile $other
805 function mutuallySubscribed($other)
807 return $this->isSubscribed($other) &&
808 $other->isSubscribed($this);
811 function hasFave($notice)
813 $fave = Fave::pkeyGet(array('user_id' => $this->id,
814 'notice_id' => $notice->id));
815 return ((is_null($fave)) ? false : true);
820 $c = Cache::instance();
822 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
823 if (is_integer($cnt)) {
829 $faves->user_id = $this->id;
830 $cnt = (int) $faves->count('notice_id');
833 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
839 function noticeCount()
841 $c = Cache::instance();
844 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
845 if (is_integer($cnt)) {
850 $notices = new Notice();
851 $notices->profile_id = $this->id;
852 $cnt = (int) $notices->count('distinct id');
855 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
861 function blowFavesCache()
863 $cache = Cache::instance();
865 // Faves don't happen chronologically, so we need to blow
867 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
868 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
869 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
870 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
872 $this->blowFaveCount();
875 function blowSubscriberCount()
877 $c = Cache::instance();
879 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
883 function blowSubscriptionCount()
885 $c = Cache::instance();
887 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
891 function blowFaveCount()
893 $c = Cache::instance();
895 $c->delete(Cache::key('profile:fave_count:'.$this->id));
899 function blowNoticeCount()
901 $c = Cache::instance();
903 $c->delete(Cache::key('profile:notice_count:'.$this->id));
907 static function maxBio()
909 $biolimit = common_config('profile', 'biolimit');
910 // null => use global limit (distinct from 0!)
911 if (is_null($biolimit)) {
912 $biolimit = common_config('site', 'textlimit');
917 static function bioTooLong($bio)
919 $biolimit = self::maxBio();
920 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
925 $this->_deleteNotices();
926 $this->_deleteSubscriptions();
927 $this->_deleteMessages();
928 $this->_deleteTags();
929 $this->_deleteBlocks();
930 $this->delete_avatars();
932 // Warning: delete() will run on the batch objects,
933 // not on individual objects.
934 $related = array('Reply',
937 Event::handle('ProfileDeleteRelated', array($this, &$related));
939 foreach ($related as $cls) {
941 $inst->profile_id = $this->id;
948 function _deleteNotices()
950 $notice = new Notice();
951 $notice->profile_id = $this->id;
953 if ($notice->find()) {
954 while ($notice->fetch()) {
955 $other = clone($notice);
961 function _deleteSubscriptions()
963 $sub = new Subscription();
964 $sub->subscriber = $this->id;
968 while ($sub->fetch()) {
969 $other = Profile::getKV('id', $sub->subscribed);
973 if ($other->id == $this->id) {
976 Subscription::cancel($this, $other);
979 $subd = new Subscription();
980 $subd->subscribed = $this->id;
983 while ($subd->fetch()) {
984 $other = Profile::getKV('id', $subd->subscriber);
988 if ($other->id == $this->id) {
991 Subscription::cancel($other, $this);
994 $self = new Subscription();
996 $self->subscriber = $this->id;
997 $self->subscribed = $this->id;
1002 function _deleteMessages()
1004 $msg = new Message();
1005 $msg->from_profile = $this->id;
1008 $msg = new Message();
1009 $msg->to_profile = $this->id;
1013 function _deleteTags()
1015 $tag = new Profile_tag();
1016 $tag->tagged = $this->id;
1020 function _deleteBlocks()
1022 $block = new Profile_block();
1023 $block->blocked = $this->id;
1026 $block = new Group_block();
1027 $block->blocked = $this->id;
1031 // XXX: identical to Notice::getLocation.
1033 function getLocation()
1037 if (!empty($this->location_id) && !empty($this->location_ns)) {
1038 $location = Location::fromId($this->location_id, $this->location_ns);
1041 if (is_null($location)) { // no ID, or Location::fromId() failed
1042 if (!empty($this->lat) && !empty($this->lon)) {
1043 $location = Location::fromLatLon($this->lat, $this->lon);
1047 if (is_null($location)) { // still haven't found it!
1048 if (!empty($this->location)) {
1049 $location = Location::fromName($this->location);
1056 function hasRole($name)
1059 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1060 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1062 $has_role = !empty($role);
1063 Event::handle('EndHasRole', array($this, $name, $has_role));
1068 function grantRole($name)
1070 if (Event::handle('StartGrantRole', array($this, $name))) {
1072 $role = new Profile_role();
1074 $role->profile_id = $this->id;
1075 $role->role = $name;
1076 $role->created = common_sql_now();
1078 $result = $role->insert();
1081 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1084 if ($name == 'owner') {
1085 User::blow('user:site_owner');
1088 Event::handle('EndGrantRole', array($this, $name));
1094 function revokeRole($name)
1096 if (Event::handle('StartRevokeRole', array($this, $name))) {
1098 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1102 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1103 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1104 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1107 $result = $role->delete();
1110 common_log_db_error($role, 'DELETE', __FILE__);
1111 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1112 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1113 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1116 if ($name == 'owner') {
1117 User::blow('user:site_owner');
1120 Event::handle('EndRevokeRole', array($this, $name));
1126 function isSandboxed()
1128 return $this->hasRole(Profile_role::SANDBOXED);
1131 function isSilenced()
1133 return $this->hasRole(Profile_role::SILENCED);
1138 $this->grantRole(Profile_role::SANDBOXED);
1141 function unsandbox()
1143 $this->revokeRole(Profile_role::SANDBOXED);
1148 $this->grantRole(Profile_role::SILENCED);
1149 if (common_config('notice', 'hidespam')) {
1150 $this->flushVisibility();
1154 function unsilence()
1156 $this->revokeRole(Profile_role::SILENCED);
1157 if (common_config('notice', 'hidespam')) {
1158 $this->flushVisibility();
1162 function flushVisibility()
1165 $stream = new ProfileNoticeStream($this, $this);
1166 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1167 foreach ($ids as $id) {
1168 self::blow('notice:in-scope-for:%d:null', $id);
1173 * Does this user have the right to do X?
1175 * With our role-based authorization, this is merely a lookup for whether the user
1176 * has a particular role. The implementation currently uses a switch statement
1177 * to determine if the user has the pre-defined role to exercise the right. Future
1178 * implementations may allow per-site roles, and different mappings of roles to rights.
1180 * @param $right string Name of the right, usually a constant in class Right
1181 * @return boolean whether the user has the right in question
1183 function hasRight($right)
1187 if ($this->hasRole(Profile_role::DELETED)) {
1191 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1194 case Right::DELETEOTHERSNOTICE:
1195 case Right::MAKEGROUPADMIN:
1196 case Right::SANDBOXUSER:
1197 case Right::SILENCEUSER:
1198 case Right::DELETEUSER:
1199 case Right::DELETEGROUP:
1200 case Right::TRAINSPAM:
1201 case Right::REVIEWSPAM:
1202 $result = $this->hasRole(Profile_role::MODERATOR);
1204 case Right::CONFIGURESITE:
1205 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1207 case Right::GRANTROLE:
1208 case Right::REVOKEROLE:
1209 $result = $this->hasRole(Profile_role::OWNER);
1211 case Right::NEWNOTICE:
1212 case Right::NEWMESSAGE:
1213 case Right::SUBSCRIBE:
1214 case Right::CREATEGROUP:
1215 $result = !$this->isSilenced();
1217 case Right::PUBLICNOTICE:
1218 case Right::EMAILONREPLY:
1219 case Right::EMAILONSUBSCRIBE:
1220 case Right::EMAILONFAVE:
1221 $result = !$this->isSandboxed();
1223 case Right::WEBLOGIN:
1224 $result = !$this->isSilenced();
1227 $result = !$this->isSilenced();
1229 case Right::BACKUPACCOUNT:
1230 $result = common_config('profile', 'backup');
1232 case Right::RESTOREACCOUNT:
1233 $result = common_config('profile', 'restore');
1235 case Right::DELETEACCOUNT:
1236 $result = common_config('profile', 'delete');
1238 case Right::MOVEACCOUNT:
1239 $result = common_config('profile', 'move');
1249 function hasRepeated($notice_id)
1251 // XXX: not really a pkey, but should work
1253 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1254 'repeat_of' => $notice_id));
1256 return !empty($notice);
1260 * Returns an XML string fragment with limited profile information
1261 * as an Atom <author> element.
1263 * Assumes that Atom has been previously set up as the base namespace.
1265 * @param Profile $cur the current authenticated user
1269 function asAtomAuthor($cur = null)
1271 $xs = new XMLStringer(true);
1273 $xs->elementStart('author');
1274 $xs->element('name', null, $this->nickname);
1275 $xs->element('uri', null, $this->getUri());
1278 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1279 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1280 $xs->element('statusnet:profile_info', $attrs, null);
1282 $xs->elementEnd('author');
1284 return $xs->getString();
1288 * Extra profile info for atom entries
1290 * Clients use some extra profile info in the atom stream.
1291 * This gives it to them.
1293 * @param User $cur Current user
1295 * @return array representation of <statusnet:profile_info> element or null
1298 function profileInfo($cur)
1300 $profileInfoAttr = array('local_id' => $this->id);
1303 // Whether the current user is a subscribed to this profile
1304 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1305 // Whether the current user is has blocked this profile
1306 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1309 return array('statusnet:profile_info', $profileInfoAttr, null);
1313 * Returns an XML string fragment with profile information as an
1314 * Activity Streams <activity:actor> element.
1316 * Assumes that 'activity' namespace has been previously defined.
1320 function asActivityActor()
1322 return $this->asActivityNoun('actor');
1326 * Returns an XML string fragment with profile information as an
1327 * Activity Streams noun object with the given element type.
1329 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1330 * previously defined.
1332 * @param string $element one of 'actor', 'subject', 'object', 'target'
1336 function asActivityNoun($element)
1338 $noun = ActivityObject::fromProfile($this);
1339 return $noun->asString('activity:' . $element);
1343 * Returns the best URI for a profile. Plugins may override.
1345 * @return string $uri
1351 // give plugins a chance to set the URI
1352 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1354 // check for a local user first
1355 $user = User::getKV('id', $this->id);
1357 if (!empty($user)) {
1361 Event::handle('EndGetProfileUri', array($this, &$uri));
1367 function hasBlocked($other)
1369 $block = Profile_block::exists($this, $other);
1370 return !empty($block);
1373 function getAtomFeed()
1377 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1378 $user = User::getKV('id', $this->id);
1379 if (!empty($user)) {
1380 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1381 'format' => 'atom'));
1383 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1389 static function fromURI($uri)
1393 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1394 // Get a local user or remote (OMB 0.1) profile
1395 $user = User::getKV('uri', $uri);
1396 if (!empty($user)) {
1397 $profile = $user->getProfile();
1399 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1405 function canRead(Notice $notice)
1407 if ($notice->scope & Notice::SITE_SCOPE) {
1408 $user = $this->getUser();
1414 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1415 $replies = $notice->getReplies();
1417 if (!in_array($this->id, $replies)) {
1418 $groups = $notice->getGroups();
1422 foreach ($groups as $group) {
1423 if ($this->isMember($group)) {
1435 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1436 $author = $notice->getProfile();
1437 if (!Subscription::exists($this, $author)) {
1445 static function current()
1447 $user = common_current_user();
1451 $profile = $user->getProfile();
1457 * Magic function called at serialize() time.
1459 * We use this to drop a couple process-specific references
1460 * from DB_DataObject which can cause trouble in future
1463 * @return array of variable names to include in serialization.
1468 $vars = parent::__sleep();
1469 $skip = array('_user', '_avatars');
1470 return array_diff($vars, $skip);
1473 static function fillAvatars(&$profiles, $width)
1476 foreach ($profiles as $profile) {
1477 if (!empty($profile)) {
1478 $ids[] = $profile->id;
1482 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1483 'height' => $width));
1485 foreach ($profiles as $profile) {
1486 if (!empty($profile)) { // ???
1487 $profile->_fillAvatar($width, $avatars[$profile->id]);
1492 // Can't seem to find how to fix this.
1494 function getProfile()