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 getSubscribed($offset=0, $limit=null)
651 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
652 $profiles = Profile::listFind('id', $subs);
656 function getSubscribers($offset=0, $limit=null)
658 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
659 $profiles = Profile::listFind('id', $subs);
663 function getTaggedSubscribers($tag)
666 'SELECT profile.* ' .
667 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
668 'ON profile.id = subscription.subscriber ' .
669 'AND profile.id = profile_tag.tagged ' .
670 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
671 'WHERE subscription.subscribed = %d ' .
672 'AND subscription.subscribed != subscription.subscriber ' .
673 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
674 'AND profile_list.private = false ' .
675 'ORDER BY subscription.created DESC';
677 $profile = new Profile();
680 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
682 while ($profile->fetch()) {
683 $tagged[] = clone($profile);
689 * Get pending subscribers, who have not yet been approved.
695 function getRequests($offset=0, $limit=null)
698 'SELECT profile.* ' .
699 'FROM profile JOIN subscription_queue '.
700 'ON profile.id = subscription_queue.subscriber ' .
701 'WHERE subscription_queue.subscribed = %d ' .
702 'ORDER BY subscription_queue.created DESC ';
704 if ($limit != null) {
705 if (common_config('db','type') == 'pgsql') {
706 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
708 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
712 $members = new Profile();
714 $members->query(sprintf($qry, $this->id));
718 function subscriptionCount()
720 $c = Cache::instance();
723 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
724 if (is_integer($cnt)) {
729 $sub = new Subscription();
730 $sub->subscriber = $this->id;
732 $cnt = (int) $sub->count('distinct subscribed');
734 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
737 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
743 function subscriberCount()
745 $c = Cache::instance();
747 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
748 if (is_integer($cnt)) {
753 $sub = new Subscription();
754 $sub->subscribed = $this->id;
755 $sub->whereAdd('subscriber != subscribed');
756 $cnt = (int) $sub->count('distinct subscriber');
759 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
766 * Is this profile subscribed to another profile?
768 * @param Profile $other
771 function isSubscribed($other)
773 return Subscription::exists($this, $other);
777 * Check if a pending subscription request is outstanding for this...
779 * @param Profile $other
782 function hasPendingSubscription($other)
784 return Subscription_queue::exists($this, $other);
788 * Are these two profiles subscribed to each other?
790 * @param Profile $other
793 function mutuallySubscribed($other)
795 return $this->isSubscribed($other) &&
796 $other->isSubscribed($this);
799 function hasFave($notice)
801 $fave = Fave::pkeyGet(array('user_id' => $this->id,
802 'notice_id' => $notice->id));
803 return ((is_null($fave)) ? false : true);
808 $c = Cache::instance();
810 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
811 if (is_integer($cnt)) {
817 $faves->user_id = $this->id;
818 $cnt = (int) $faves->count('notice_id');
821 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
827 function noticeCount()
829 $c = Cache::instance();
832 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
833 if (is_integer($cnt)) {
838 $notices = new Notice();
839 $notices->profile_id = $this->id;
840 $cnt = (int) $notices->count('distinct id');
843 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
849 function blowFavesCache()
851 $cache = Cache::instance();
853 // Faves don't happen chronologically, so we need to blow
855 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
856 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
857 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
858 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
860 $this->blowFaveCount();
863 function blowSubscriberCount()
865 $c = Cache::instance();
867 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
871 function blowSubscriptionCount()
873 $c = Cache::instance();
875 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
879 function blowFaveCount()
881 $c = Cache::instance();
883 $c->delete(Cache::key('profile:fave_count:'.$this->id));
887 function blowNoticeCount()
889 $c = Cache::instance();
891 $c->delete(Cache::key('profile:notice_count:'.$this->id));
895 static function maxBio()
897 $biolimit = common_config('profile', 'biolimit');
898 // null => use global limit (distinct from 0!)
899 if (is_null($biolimit)) {
900 $biolimit = common_config('site', 'textlimit');
905 static function bioTooLong($bio)
907 $biolimit = self::maxBio();
908 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
913 $this->_deleteNotices();
914 $this->_deleteSubscriptions();
915 $this->_deleteMessages();
916 $this->_deleteTags();
917 $this->_deleteBlocks();
918 $this->delete_avatars();
920 // Warning: delete() will run on the batch objects,
921 // not on individual objects.
922 $related = array('Reply',
925 Event::handle('ProfileDeleteRelated', array($this, &$related));
927 foreach ($related as $cls) {
929 $inst->profile_id = $this->id;
936 function _deleteNotices()
938 $notice = new Notice();
939 $notice->profile_id = $this->id;
941 if ($notice->find()) {
942 while ($notice->fetch()) {
943 $other = clone($notice);
949 function _deleteSubscriptions()
951 $sub = new Subscription();
952 $sub->subscriber = $this->id;
956 while ($sub->fetch()) {
957 $other = Profile::getKV('id', $sub->subscribed);
961 if ($other->id == $this->id) {
964 Subscription::cancel($this, $other);
967 $subd = new Subscription();
968 $subd->subscribed = $this->id;
971 while ($subd->fetch()) {
972 $other = Profile::getKV('id', $subd->subscriber);
976 if ($other->id == $this->id) {
979 Subscription::cancel($other, $this);
982 $self = new Subscription();
984 $self->subscriber = $this->id;
985 $self->subscribed = $this->id;
990 function _deleteMessages()
992 $msg = new Message();
993 $msg->from_profile = $this->id;
996 $msg = new Message();
997 $msg->to_profile = $this->id;
1001 function _deleteTags()
1003 $tag = new Profile_tag();
1004 $tag->tagged = $this->id;
1008 function _deleteBlocks()
1010 $block = new Profile_block();
1011 $block->blocked = $this->id;
1014 $block = new Group_block();
1015 $block->blocked = $this->id;
1019 // XXX: identical to Notice::getLocation.
1021 function getLocation()
1025 if (!empty($this->location_id) && !empty($this->location_ns)) {
1026 $location = Location::fromId($this->location_id, $this->location_ns);
1029 if (is_null($location)) { // no ID, or Location::fromId() failed
1030 if (!empty($this->lat) && !empty($this->lon)) {
1031 $location = Location::fromLatLon($this->lat, $this->lon);
1035 if (is_null($location)) { // still haven't found it!
1036 if (!empty($this->location)) {
1037 $location = Location::fromName($this->location);
1044 function hasRole($name)
1047 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1048 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1050 $has_role = !empty($role);
1051 Event::handle('EndHasRole', array($this, $name, $has_role));
1056 function grantRole($name)
1058 if (Event::handle('StartGrantRole', array($this, $name))) {
1060 $role = new Profile_role();
1062 $role->profile_id = $this->id;
1063 $role->role = $name;
1064 $role->created = common_sql_now();
1066 $result = $role->insert();
1069 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1072 if ($name == 'owner') {
1073 User::blow('user:site_owner');
1076 Event::handle('EndGrantRole', array($this, $name));
1082 function revokeRole($name)
1084 if (Event::handle('StartRevokeRole', array($this, $name))) {
1086 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1090 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1091 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1092 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1095 $result = $role->delete();
1098 common_log_db_error($role, 'DELETE', __FILE__);
1099 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1100 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1101 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1104 if ($name == 'owner') {
1105 User::blow('user:site_owner');
1108 Event::handle('EndRevokeRole', array($this, $name));
1114 function isSandboxed()
1116 return $this->hasRole(Profile_role::SANDBOXED);
1119 function isSilenced()
1121 return $this->hasRole(Profile_role::SILENCED);
1126 $this->grantRole(Profile_role::SANDBOXED);
1129 function unsandbox()
1131 $this->revokeRole(Profile_role::SANDBOXED);
1136 $this->grantRole(Profile_role::SILENCED);
1137 if (common_config('notice', 'hidespam')) {
1138 $this->flushVisibility();
1142 function unsilence()
1144 $this->revokeRole(Profile_role::SILENCED);
1145 if (common_config('notice', 'hidespam')) {
1146 $this->flushVisibility();
1150 function flushVisibility()
1153 $stream = new ProfileNoticeStream($this, $this);
1154 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1155 foreach ($ids as $id) {
1156 self::blow('notice:in-scope-for:%d:null', $id);
1161 * Does this user have the right to do X?
1163 * With our role-based authorization, this is merely a lookup for whether the user
1164 * has a particular role. The implementation currently uses a switch statement
1165 * to determine if the user has the pre-defined role to exercise the right. Future
1166 * implementations may allow per-site roles, and different mappings of roles to rights.
1168 * @param $right string Name of the right, usually a constant in class Right
1169 * @return boolean whether the user has the right in question
1171 function hasRight($right)
1175 if ($this->hasRole(Profile_role::DELETED)) {
1179 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1182 case Right::DELETEOTHERSNOTICE:
1183 case Right::MAKEGROUPADMIN:
1184 case Right::SANDBOXUSER:
1185 case Right::SILENCEUSER:
1186 case Right::DELETEUSER:
1187 case Right::DELETEGROUP:
1188 case Right::TRAINSPAM:
1189 case Right::REVIEWSPAM:
1190 $result = $this->hasRole(Profile_role::MODERATOR);
1192 case Right::CONFIGURESITE:
1193 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1195 case Right::GRANTROLE:
1196 case Right::REVOKEROLE:
1197 $result = $this->hasRole(Profile_role::OWNER);
1199 case Right::NEWNOTICE:
1200 case Right::NEWMESSAGE:
1201 case Right::SUBSCRIBE:
1202 case Right::CREATEGROUP:
1203 $result = !$this->isSilenced();
1205 case Right::PUBLICNOTICE:
1206 case Right::EMAILONREPLY:
1207 case Right::EMAILONSUBSCRIBE:
1208 case Right::EMAILONFAVE:
1209 $result = !$this->isSandboxed();
1211 case Right::WEBLOGIN:
1212 $result = !$this->isSilenced();
1215 $result = !$this->isSilenced();
1217 case Right::BACKUPACCOUNT:
1218 $result = common_config('profile', 'backup');
1220 case Right::RESTOREACCOUNT:
1221 $result = common_config('profile', 'restore');
1223 case Right::DELETEACCOUNT:
1224 $result = common_config('profile', 'delete');
1226 case Right::MOVEACCOUNT:
1227 $result = common_config('profile', 'move');
1237 function hasRepeated($notice_id)
1239 // XXX: not really a pkey, but should work
1241 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1242 'repeat_of' => $notice_id));
1244 return !empty($notice);
1248 * Returns an XML string fragment with limited profile information
1249 * as an Atom <author> element.
1251 * Assumes that Atom has been previously set up as the base namespace.
1253 * @param Profile $cur the current authenticated user
1257 function asAtomAuthor($cur = null)
1259 $xs = new XMLStringer(true);
1261 $xs->elementStart('author');
1262 $xs->element('name', null, $this->nickname);
1263 $xs->element('uri', null, $this->getUri());
1266 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1267 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1268 $xs->element('statusnet:profile_info', $attrs, null);
1270 $xs->elementEnd('author');
1272 return $xs->getString();
1276 * Extra profile info for atom entries
1278 * Clients use some extra profile info in the atom stream.
1279 * This gives it to them.
1281 * @param User $cur Current user
1283 * @return array representation of <statusnet:profile_info> element or null
1286 function profileInfo($cur)
1288 $profileInfoAttr = array('local_id' => $this->id);
1291 // Whether the current user is a subscribed to this profile
1292 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1293 // Whether the current user is has blocked this profile
1294 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1297 return array('statusnet:profile_info', $profileInfoAttr, null);
1301 * Returns an XML string fragment with profile information as an
1302 * Activity Streams <activity:actor> element.
1304 * Assumes that 'activity' namespace has been previously defined.
1308 function asActivityActor()
1310 return $this->asActivityNoun('actor');
1314 * Returns an XML string fragment with profile information as an
1315 * Activity Streams noun object with the given element type.
1317 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1318 * previously defined.
1320 * @param string $element one of 'actor', 'subject', 'object', 'target'
1324 function asActivityNoun($element)
1326 $noun = ActivityObject::fromProfile($this);
1327 return $noun->asString('activity:' . $element);
1331 * Returns the profile's canonical url, not necessarily a uri/unique id
1333 * @return string $profileurl
1335 public function getUrl()
1337 if (empty($this->profileurl) ||
1338 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1339 throw new InvalidUrlException($this->profileurl);
1341 return $this->profileurl;
1345 * Returns the best URI for a profile. Plugins may override.
1347 * @return string $uri
1349 public function getUri()
1353 // give plugins a chance to set the URI
1354 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1356 // check for a local user first
1357 $user = User::getKV('id', $this->id);
1359 if (!empty($user)) {
1363 Event::handle('EndGetProfileUri', array($this, &$uri));
1369 function hasBlocked($other)
1371 $block = Profile_block::exists($this, $other);
1372 return !empty($block);
1375 function getAtomFeed()
1379 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1380 $user = User::getKV('id', $this->id);
1381 if (!empty($user)) {
1382 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1383 'format' => 'atom'));
1385 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1391 static function fromURI($uri)
1395 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1396 // Get a local user or remote (OMB 0.1) profile
1397 $user = User::getKV('uri', $uri);
1398 if (!empty($user)) {
1399 $profile = $user->getProfile();
1401 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1407 function canRead(Notice $notice)
1409 if ($notice->scope & Notice::SITE_SCOPE) {
1410 $user = $this->getUser();
1416 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1417 $replies = $notice->getReplies();
1419 if (!in_array($this->id, $replies)) {
1420 $groups = $notice->getGroups();
1424 foreach ($groups as $group) {
1425 if ($this->isMember($group)) {
1437 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1438 $author = $notice->getProfile();
1439 if (!Subscription::exists($this, $author)) {
1447 static function current()
1449 $user = common_current_user();
1453 $profile = $user->getProfile();
1459 * Magic function called at serialize() time.
1461 * We use this to drop a couple process-specific references
1462 * from DB_DataObject which can cause trouble in future
1465 * @return array of variable names to include in serialization.
1470 $vars = parent::__sleep();
1471 $skip = array('_user', '_avatars');
1472 return array_diff($vars, $skip);
1475 static function fillAvatars(&$profiles, $width)
1478 foreach ($profiles as $profile) {
1479 if (!empty($profile)) {
1480 $ids[] = $profile->id;
1484 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1485 'height' => $width));
1487 foreach ($profiles as $profile) {
1488 if (!empty($profile)) { // ???
1489 $profile->_fillAvatar($width, $avatars[$profile->id]);
1494 // Can't seem to find how to fix this.
1496 function getProfile()