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 class Profile extends Managed_DataObject
28 /* the code below is auto generated do not remove the above tag */
30 public $__table = 'profile'; // table name
31 public $id; // int(4) primary_key not_null
32 public $nickname; // varchar(64) multiple_key not_null
33 public $fullname; // varchar(191) multiple_key not 255 because utf8mb4 takes more space
34 public $profileurl; // varchar(191) not 255 because utf8mb4 takes more space
35 public $homepage; // varchar(191) multiple_key not 255 because utf8mb4 takes more space
36 public $bio; // text() multiple_key
37 public $location; // varchar(191) multiple_key not 255 because utf8mb4 takes more space
38 public $lat; // decimal(10,7)
39 public $lon; // decimal(10,7)
40 public $location_id; // int(4)
41 public $location_ns; // int(4)
42 public $created; // datetime() not_null
43 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
45 public static function schemaDef()
48 'description' => 'local and remote users have profiles',
50 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
51 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8mb4_general_ci'),
52 'fullname' => array('type' => 'varchar', 'length' => 191, 'description' => 'display name', 'collate' => 'utf8mb4_general_ci'),
53 'profileurl' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL, cached so we dont regenerate'),
54 'homepage' => array('type' => 'varchar', 'length' => 191, 'description' => 'identifying URL', 'collate' => 'utf8mb4_general_ci'),
55 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8mb4_general_ci'),
56 'location' => array('type' => 'varchar', 'length' => 191, 'description' => 'physical location', 'collate' => 'utf8mb4_general_ci'),
57 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
58 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
59 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
60 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
62 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
63 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
65 'primary key' => array('id'),
67 'profile_nickname_idx' => array('nickname'),
71 // Add a fulltext index
73 if (common_config('search', 'type') == 'fulltext') {
74 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
80 /* the code above is auto generated do not remove the tag below */
83 public static function getByEmail($email)
85 // in the future, profiles should have emails stored...
86 $user = User::getKV('email', $email);
87 if (!($user instanceof User)) {
88 throw new NoSuchUserException(array('email'=>$email));
90 return $user->getProfile();
93 protected $_user = array();
95 public function getUser()
97 if (!isset($this->_user[$this->id])) {
98 $user = User::getKV('id', $this->id);
99 if (!$user instanceof User) {
100 throw new NoSuchUserException(array('id'=>$this->id));
102 $this->_user[$this->id] = $user;
104 return $this->_user[$this->id];
107 protected $_group = array();
109 public function getGroup()
111 if (!isset($this->_group[$this->id])) {
112 $group = User_group::getKV('profile_id', $this->id);
113 if (!$group instanceof User_group) {
114 throw new NoSuchGroupException(array('profile_id'=>$this->id));
116 $this->_group[$this->id] = $group;
118 return $this->_group[$this->id];
121 public function isGroup()
126 } catch (NoSuchGroupException $e) {
131 public function isLocal()
135 } catch (NoSuchUserException $e) {
141 public function getObjectType()
143 // FIXME: More types... like peopletags and whatever
144 if ($this->isGroup()) {
145 return ActivityObject::GROUP;
147 return ActivityObject::PERSON;
151 public function getAvatar($width, $height=null)
153 return Avatar::byProfile($this, $width, $height);
156 public function setOriginal($filename)
158 if ($this->isGroup()) {
159 // Until Group avatars are handled just like profile avatars.
160 return $this->getGroup()->setOriginal($filename);
163 $imagefile = new ImageFile(null, Avatar::path($filename));
165 $avatar = new Avatar();
166 $avatar->profile_id = $this->id;
167 $avatar->width = $imagefile->width;
168 $avatar->height = $imagefile->height;
169 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
170 $avatar->filename = $filename;
171 $avatar->original = true;
172 $avatar->url = Avatar::url($filename);
173 $avatar->created = common_sql_now();
175 // XXX: start a transaction here
176 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
177 // If we can't delete the old avatars, let's abort right here.
178 @unlink(Avatar::path($filename));
186 * Gets either the full name (if filled) or the nickname.
190 function getBestName()
192 return ($this->fullname) ? $this->fullname : $this->nickname;
196 * Takes the currently scoped profile into account to give a name
197 * to list in notice streams. Preferences may differ between profiles.
199 function getStreamName()
201 $user = common_current_user();
202 if ($user instanceof User && $user->streamNicknames()) {
203 return $this->nickname;
206 return $this->getBestName();
210 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
211 * if no fullname is provided.
215 function getFancyName()
217 if ($this->fullname) {
218 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
219 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
221 return $this->nickname;
226 * Get the most recent notice posted by this user, if any.
228 * @return mixed Notice or null
230 function getCurrentNotice()
232 $notice = $this->getNotices(0, 1);
234 if ($notice->fetch()) {
235 if ($notice instanceof ArrayWrapper) {
236 // hack for things trying to work with single notices
237 return $notice->_items[0];
245 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
247 return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
250 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
252 $stream = new TaggedProfileNoticeStream($this, $tag);
254 return $stream->getNotices($offset, $limit, $since_id, $max_id);
257 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
259 $stream = new ProfileNoticeStream($this, $scoped);
261 return $stream->getNotices($offset, $limit, $since_id, $max_id);
264 function isMember(User_group $group)
266 $groups = $this->getGroups(0, null);
267 while ($groups instanceof User_group && $groups->fetch()) {
268 if ($groups->id == $group->id) {
275 function isAdmin(User_group $group)
277 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
278 'group_id' => $group->id));
279 return (!empty($gm) && $gm->is_admin);
282 function isPendingMember($group)
284 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
285 'group_id' => $group->id));
286 return !empty($request);
289 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
293 $keypart = sprintf('profile:groups:%d', $this->id);
295 $idstring = self::cacheGet($keypart);
297 if ($idstring !== false) {
298 $ids = explode(',', $idstring);
300 $gm = new Group_member();
302 $gm->profile_id = $this->id;
305 while ($gm->fetch()) {
306 $ids[] = $gm->group_id;
310 self::cacheSet($keypart, implode(',', $ids));
313 if (!is_null($offset) && !is_null($limit)) {
314 $ids = array_slice($ids, $offset, $limit);
318 return User_group::multiGet('id', $ids);
319 } catch (NoResultException $e) {
320 return null; // throw exception when we handle it everywhere
324 function getGroupCount() {
325 $groups = $this->getGroups(0, null);
326 return $groups instanceof User_group
331 function isTagged($peopletag)
333 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
334 'tagged' => $this->id,
335 'tag' => $peopletag->tag));
339 function canTag($tagged)
341 if (empty($tagged)) {
345 if ($tagged->id == $this->id) {
349 $all = common_config('peopletag', 'allow_tagging', 'all');
350 $local = common_config('peopletag', 'allow_tagging', 'local');
351 $remote = common_config('peopletag', 'allow_tagging', 'remote');
352 $subs = common_config('peopletag', 'allow_tagging', 'subs');
358 $tagged_user = $tagged->getUser();
359 if (!empty($tagged_user)) {
364 return (Subscription::exists($this, $tagged) ||
365 Subscription::exists($tagged, $this));
366 } else if ($remote) {
372 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
376 $keypart = sprintf('profile:lists:%d', $this->id);
378 $idstr = self::cacheGet($keypart);
380 if ($idstr !== false) {
381 $ids = explode(',', $idstr);
383 $list = new Profile_list();
385 $list->selectAdd('id');
386 $list->tagger = $this->id;
387 $list->selectAdd('id as "cursor"');
390 $list->whereAdd('id > '.$since_id);
394 $list->whereAdd('id <= '.$max_id);
397 if($offset>=0 && !is_null($limit)) {
398 $list->limit($offset, $limit);
401 $list->orderBy('id DESC');
404 while ($list->fetch()) {
409 self::cacheSet($keypart, implode(',', $ids));
412 $showPrivate = (($auth_user instanceof User ||
413 $auth_user instanceof Profile) &&
414 $auth_user->id === $this->id);
418 foreach ($ids as $id) {
419 $list = Profile_list::getKV('id', $id);
421 ($showPrivate || !$list->private)) {
423 if (!isset($list->cursor)) {
424 $list->cursor = $list->id;
431 return new ArrayWrapper($lists);
435 * Get tags that other people put on this profile, in reverse-chron order
437 * @param (Profile|User) $auth_user Authorized user (used for privacy)
438 * @param int $offset Offset from latest
439 * @param int $limit Max number to get
440 * @param datetime $since_id max date
441 * @param datetime $max_id min date
443 * @return Profile_list resulting lists
446 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
448 $list = new Profile_list();
450 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
451 'from profile_tag join profile_list '.
452 'on (profile_tag.tagger = profile_list.tagger ' .
453 ' and profile_tag.tag = profile_list.tag) ' .
454 'where profile_tag.tagged = %d ',
458 if ($auth_user instanceof User || $auth_user instanceof Profile) {
459 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
460 'OR ( profile_list.tagger = %d AND ' .
461 'profile_list.private = true ) )',
464 $qry .= 'AND profile_list.private = 0 ';
468 $qry .= sprintf('AND (cursor > %d) ', $since_id);
472 $qry .= sprintf('AND (cursor < %d) ', $max_id);
475 $qry .= 'ORDER BY profile_tag.modified DESC ';
477 if ($offset >= 0 && !is_null($limit)) {
478 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
485 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
487 $tags = new Profile_list();
488 $tags->private = true;
489 $tags->tagger = $this->id;
492 $tags->whereAdd('id > '.$since_id);
496 $tags->whereAdd('id <= '.$max_id);
499 if($offset>=0 && !is_null($limit)) {
500 $tags->limit($offset, $limit);
503 $tags->orderBy('id DESC');
509 function hasLocalTags()
511 $tags = new Profile_tag();
513 $tags->joinAdd(array('tagger', 'user:id'));
514 $tags->whereAdd('tagged = '.$this->id);
515 $tags->whereAdd('tagger != '.$this->id);
520 return ($tags->N == 0) ? false : true;
523 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
525 $lists = new Profile_list();
526 $subs = new Profile_tag_subscription();
528 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
530 #@fixme: postgres (round(date_part('epoch', my_date)))
531 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
533 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
536 $lists->whereAdd('cursor > '.$since_id);
540 $lists->whereAdd('cursor <= '.$max_id);
543 if($offset>=0 && !is_null($limit)) {
544 $lists->limit($offset, $limit);
547 $lists->orderBy('"cursor" DESC');
554 * Request to join the given group.
555 * May throw exceptions on failure.
557 * @param User_group $group
558 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
560 function joinGroup(User_group $group)
563 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
564 $join = Group_join_queue::saveNew($this, $group);
566 if (Event::handle('StartJoinGroup', array($group, $this))) {
567 $join = Group_member::join($group->id, $this->id);
568 self::blow('profile:groups:%d', $this->id);
569 self::blow('group:member_ids:%d', $group->id);
570 self::blow('group:member_count:%d', $group->id);
571 Event::handle('EndJoinGroup', array($group, $this));
575 // Send any applicable notifications...
582 * Leave a group that this profile is a member of.
584 * @param User_group $group
586 function leaveGroup(User_group $group)
588 if (Event::handle('StartLeaveGroup', array($group, $this))) {
589 Group_member::leave($group->id, $this->id);
590 self::blow('profile:groups:%d', $this->id);
591 self::blow('group:member_ids:%d', $group->id);
592 self::blow('group:member_count:%d', $group->id);
593 Event::handle('EndLeaveGroup', array($group, $this));
597 function avatarUrl($size=AVATAR_PROFILE_SIZE)
599 return Avatar::urlByProfile($this, $size);
602 function getSubscribed($offset=0, $limit=null)
604 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
606 $profiles = Profile::multiGet('id', $subs);
607 } catch (NoResultException $e) {
613 function getSubscribers($offset=0, $limit=null)
615 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
617 $profiles = Profile::multiGet('id', $subs);
618 } catch (NoResultException $e) {
624 function getTaggedSubscribers($tag, $offset=0, $limit=null)
627 'SELECT profile.* ' .
628 'FROM profile JOIN subscription ' .
629 'ON profile.id = subscription.subscriber ' .
630 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
631 'AND profile_tag.tagger = subscription.subscribed) ' .
632 'WHERE subscription.subscribed = %d ' .
633 "AND profile_tag.tag = '%s' " .
634 'AND subscription.subscribed != subscription.subscriber ' .
635 'ORDER BY subscription.created DESC ';
638 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
641 $profile = new Profile();
643 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
648 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
651 'SELECT profile.* ' .
652 'FROM profile JOIN subscription ' .
653 'ON profile.id = subscription.subscribed ' .
654 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
655 'AND profile_tag.tagger = subscription.subscriber) ' .
656 'WHERE subscription.subscriber = %d ' .
657 "AND profile_tag.tag = '%s' " .
658 'AND subscription.subscribed != subscription.subscriber ' .
659 'ORDER BY subscription.created DESC ';
661 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
663 $profile = new Profile();
665 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
671 * Get pending subscribers, who have not yet been approved.
677 function getRequests($offset=0, $limit=null)
680 'SELECT profile.* ' .
681 'FROM profile JOIN subscription_queue '.
682 'ON profile.id = subscription_queue.subscriber ' .
683 'WHERE subscription_queue.subscribed = %d ' .
684 'ORDER BY subscription_queue.created DESC ';
686 if ($limit != null) {
687 if (common_config('db','type') == 'pgsql') {
688 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
690 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
694 $members = new Profile();
696 $members->query(sprintf($qry, $this->id));
700 function subscriptionCount()
702 $c = Cache::instance();
705 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
706 if (is_integer($cnt)) {
711 $sub = new Subscription();
712 $sub->subscriber = $this->id;
714 $cnt = (int) $sub->count('distinct subscribed');
716 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
719 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
725 function subscriberCount()
727 $c = Cache::instance();
729 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
730 if (is_integer($cnt)) {
735 $sub = new Subscription();
736 $sub->subscribed = $this->id;
737 $sub->whereAdd('subscriber != subscribed');
738 $cnt = (int) $sub->count('distinct subscriber');
741 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
748 * Is this profile subscribed to another profile?
750 * @param Profile $other
753 function isSubscribed(Profile $other)
755 return Subscription::exists($this, $other);
759 * Check if a pending subscription request is outstanding for this...
761 * @param Profile $other
764 function hasPendingSubscription(Profile $other)
766 return Subscription_queue::exists($this, $other);
770 * Are these two profiles subscribed to each other?
772 * @param Profile $other
775 function mutuallySubscribed(Profile $other)
777 return $this->isSubscribed($other) &&
778 $other->isSubscribed($this);
781 function noticeCount()
783 $c = Cache::instance();
786 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
787 if (is_integer($cnt)) {
792 $notices = new Notice();
793 $notices->profile_id = $this->id;
794 $cnt = (int) $notices->count('distinct id');
797 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
803 function blowSubscriberCount()
805 $c = Cache::instance();
807 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
811 function blowSubscriptionCount()
813 $c = Cache::instance();
815 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
819 function blowNoticeCount()
821 $c = Cache::instance();
823 $c->delete(Cache::key('profile:notice_count:'.$this->id));
827 static function maxBio()
829 $biolimit = common_config('profile', 'biolimit');
830 // null => use global limit (distinct from 0!)
831 if (is_null($biolimit)) {
832 $biolimit = common_config('site', 'textlimit');
837 static function bioTooLong($bio)
839 $biolimit = self::maxBio();
840 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
843 function update($dataObject=false)
845 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
847 $local = $this->getUser();
848 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
849 $origuser = clone($local);
850 $local->nickname = $this->nickname;
851 // updateWithKeys throws exception on failure.
852 $local->updateWithKeys($origuser);
854 // Clear the site owner, in case nickname changed
855 if ($local->hasRole(Profile_role::OWNER)) {
856 User::blow('user:site_owner');
858 } catch (NoSuchUserException $e) {
863 return parent::update($dataObject);
866 function delete($useWhere=false)
868 $this->_deleteNotices();
869 $this->_deleteSubscriptions();
870 $this->_deleteTags();
871 $this->_deleteBlocks();
872 $this->_deleteAttentions();
873 Avatar::deleteFromProfile($this, true);
875 // Warning: delete() will run on the batch objects,
876 // not on individual objects.
877 $related = array('Reply',
880 Event::handle('ProfileDeleteRelated', array($this, &$related));
882 foreach ($related as $cls) {
884 $inst->profile_id = $this->id;
888 $localuser = User::getKV('id', $this->id);
889 if ($localuser instanceof User) {
890 $localuser->delete();
893 return parent::delete($useWhere);
896 function _deleteNotices()
898 $notice = new Notice();
899 $notice->profile_id = $this->id;
901 if ($notice->find()) {
902 while ($notice->fetch()) {
903 $other = clone($notice);
909 function _deleteSubscriptions()
911 $sub = new Subscription();
912 $sub->subscriber = $this->id;
916 while ($sub->fetch()) {
917 $other = Profile::getKV('id', $sub->subscribed);
921 if ($other->id == $this->id) {
924 Subscription::cancel($this, $other);
927 $subd = new Subscription();
928 $subd->subscribed = $this->id;
931 while ($subd->fetch()) {
932 $other = Profile::getKV('id', $subd->subscriber);
936 if ($other->id == $this->id) {
939 Subscription::cancel($other, $this);
942 $self = new Subscription();
944 $self->subscriber = $this->id;
945 $self->subscribed = $this->id;
950 function _deleteTags()
952 $tag = new Profile_tag();
953 $tag->tagged = $this->id;
957 function _deleteBlocks()
959 $block = new Profile_block();
960 $block->blocked = $this->id;
963 $block = new Group_block();
964 $block->blocked = $this->id;
968 function _deleteAttentions()
970 $att = new Attention();
971 $att->profile_id = $this->getID();
974 while ($att->fetch()) {
975 // Can't do delete() on the object directly since it won't remove all of it
976 $other = clone($att);
982 // XXX: identical to Notice::getLocation.
984 public function getLocation()
988 if (!empty($this->location_id) && !empty($this->location_ns)) {
989 $location = Location::fromId($this->location_id, $this->location_ns);
992 if (is_null($location)) { // no ID, or Location::fromId() failed
993 if (!empty($this->lat) && !empty($this->lon)) {
994 $location = Location::fromLatLon($this->lat, $this->lon);
998 if (is_null($location)) { // still haven't found it!
999 if (!empty($this->location)) {
1000 $location = Location::fromName($this->location);
1007 public function shareLocation()
1009 $cfg = common_config('location', 'share');
1011 if ($cfg == 'always') {
1013 } else if ($cfg == 'never') {
1016 $share = common_config('location', 'sharedefault');
1018 // Check if user has a personal setting for this
1019 $prefs = User_location_prefs::getKV('user_id', $this->id);
1021 if (!empty($prefs)) {
1022 $share = $prefs->share_location;
1030 function hasRole($name)
1033 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1034 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1036 $has_role = !empty($role);
1037 Event::handle('EndHasRole', array($this, $name, $has_role));
1042 function grantRole($name)
1044 if (Event::handle('StartGrantRole', array($this, $name))) {
1046 $role = new Profile_role();
1048 $role->profile_id = $this->id;
1049 $role->role = $name;
1050 $role->created = common_sql_now();
1052 $result = $role->insert();
1055 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1058 if ($name == 'owner') {
1059 User::blow('user:site_owner');
1062 Event::handle('EndGrantRole', array($this, $name));
1068 function revokeRole($name)
1070 if (Event::handle('StartRevokeRole', array($this, $name))) {
1072 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1076 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1077 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1078 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1081 $result = $role->delete();
1084 common_log_db_error($role, 'DELETE', __FILE__);
1085 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1086 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1087 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1090 if ($name == 'owner') {
1091 User::blow('user:site_owner');
1094 Event::handle('EndRevokeRole', array($this, $name));
1100 function isSandboxed()
1102 return $this->hasRole(Profile_role::SANDBOXED);
1105 function isSilenced()
1107 return $this->hasRole(Profile_role::SILENCED);
1112 $this->grantRole(Profile_role::SANDBOXED);
1115 function unsandbox()
1117 $this->revokeRole(Profile_role::SANDBOXED);
1122 $this->grantRole(Profile_role::SILENCED);
1123 if (common_config('notice', 'hidespam')) {
1124 $this->flushVisibility();
1128 function unsilence()
1130 $this->revokeRole(Profile_role::SILENCED);
1131 if (common_config('notice', 'hidespam')) {
1132 $this->flushVisibility();
1136 function flushVisibility()
1139 $stream = new ProfileNoticeStream($this, $this);
1140 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1141 foreach ($ids as $id) {
1142 self::blow('notice:in-scope-for:%d:null', $id);
1147 * Does this user have the right to do X?
1149 * With our role-based authorization, this is merely a lookup for whether the user
1150 * has a particular role. The implementation currently uses a switch statement
1151 * to determine if the user has the pre-defined role to exercise the right. Future
1152 * implementations may allow per-site roles, and different mappings of roles to rights.
1154 * @param $right string Name of the right, usually a constant in class Right
1155 * @return boolean whether the user has the right in question
1157 public function hasRight($right)
1161 if ($this->hasRole(Profile_role::DELETED)) {
1165 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1168 case Right::DELETEOTHERSNOTICE:
1169 case Right::MAKEGROUPADMIN:
1170 case Right::SANDBOXUSER:
1171 case Right::SILENCEUSER:
1172 case Right::DELETEUSER:
1173 case Right::DELETEGROUP:
1174 case Right::TRAINSPAM:
1175 case Right::REVIEWSPAM:
1176 $result = $this->hasRole(Profile_role::MODERATOR);
1178 case Right::CONFIGURESITE:
1179 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1181 case Right::GRANTROLE:
1182 case Right::REVOKEROLE:
1183 $result = $this->hasRole(Profile_role::OWNER);
1185 case Right::NEWNOTICE:
1186 case Right::NEWMESSAGE:
1187 case Right::SUBSCRIBE:
1188 case Right::CREATEGROUP:
1189 $result = !$this->isSilenced();
1191 case Right::PUBLICNOTICE:
1192 case Right::EMAILONREPLY:
1193 case Right::EMAILONSUBSCRIBE:
1194 case Right::EMAILONFAVE:
1195 $result = !$this->isSandboxed();
1197 case Right::WEBLOGIN:
1198 $result = !$this->isSilenced();
1201 $result = !$this->isSilenced();
1203 case Right::BACKUPACCOUNT:
1204 $result = common_config('profile', 'backup');
1206 case Right::RESTOREACCOUNT:
1207 $result = common_config('profile', 'restore');
1209 case Right::DELETEACCOUNT:
1210 $result = common_config('profile', 'delete');
1212 case Right::MOVEACCOUNT:
1213 $result = common_config('profile', 'move');
1223 // FIXME: Can't put Notice typing here due to ArrayWrapper
1224 public function hasRepeated($notice)
1226 // XXX: not really a pkey, but should work
1228 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1229 'repeat_of' => $notice->id));
1231 return !empty($notice);
1235 * Returns an XML string fragment with limited profile information
1236 * as an Atom <author> element.
1238 * Assumes that Atom has been previously set up as the base namespace.
1240 * @param Profile $cur the current authenticated user
1244 function asAtomAuthor($cur = null)
1246 $xs = new XMLStringer(true);
1248 $xs->elementStart('author');
1249 $xs->element('name', null, $this->nickname);
1250 $xs->element('uri', null, $this->getUri());
1253 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1254 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1255 $xs->element('statusnet:profile_info', $attrs, null);
1257 $xs->elementEnd('author');
1259 return $xs->getString();
1263 * Extra profile info for atom entries
1265 * Clients use some extra profile info in the atom stream.
1266 * This gives it to them.
1268 * @param Profile $scoped The currently logged in/scoped profile
1270 * @return array representation of <statusnet:profile_info> element or null
1273 function profileInfo(Profile $scoped=null)
1275 $profileInfoAttr = array('local_id' => $this->id);
1277 if ($scoped instanceof Profile) {
1278 // Whether the current user is a subscribed to this profile
1279 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1280 // Whether the current user is has blocked this profile
1281 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1284 return array('statusnet:profile_info', $profileInfoAttr, null);
1288 * Returns an XML string fragment with profile information as an
1289 * Activity Streams <activity:actor> element.
1291 * Assumes that 'activity' namespace has been previously defined.
1295 function asActivityActor()
1297 return $this->asActivityNoun('actor');
1301 * Returns an XML string fragment with profile information as an
1302 * Activity Streams noun object with the given element type.
1304 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1305 * previously defined.
1307 * @param string $element one of 'actor', 'subject', 'object', 'target'
1311 function asActivityNoun($element)
1313 $noun = $this->asActivityObject();
1314 return $noun->asString('activity:' . $element);
1317 public function asActivityObject()
1319 $object = new ActivityObject();
1321 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1322 $object->type = $this->getObjectType();
1323 $object->id = $this->getUri();
1324 $object->title = $this->getBestName();
1325 $object->link = $this->getUrl();
1326 $object->summary = $this->getDescription();
1329 $avatar = Avatar::getUploaded($this);
1330 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1331 } catch (NoAvatarException $e) {
1332 // Could not find an original avatar to link
1336 AVATAR_PROFILE_SIZE,
1341 foreach ($sizes as $size) {
1344 $avatar = Avatar::byProfile($this, $size);
1345 $alink = AvatarLink::fromAvatar($avatar);
1346 } catch (NoAvatarException $e) {
1347 $alink = new AvatarLink();
1348 $alink->type = 'image/png';
1349 $alink->height = $size;
1350 $alink->width = $size;
1351 $alink->url = Avatar::defaultImage($size);
1354 $object->avatarLinks[] = $alink;
1357 if (isset($this->lat) && isset($this->lon)) {
1358 $object->geopoint = (float)$this->lat
1359 . ' ' . (float)$this->lon;
1362 $object->poco = PoCo::fromProfile($this);
1364 if ($this->isLocal()) {
1365 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1368 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1375 * Returns the profile's canonical url, not necessarily a uri/unique id
1377 * @return string $profileurl
1379 public function getUrl()
1381 if (empty($this->profileurl) ||
1382 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1383 throw new InvalidUrlException($this->profileurl);
1385 return $this->profileurl;
1388 public function getNickname()
1390 return $this->nickname;
1393 public function getFullname()
1395 return $this->fullname;
1398 public function getDescription()
1404 * Returns the best URI for a profile. Plugins may override.
1406 * @return string $uri
1408 public function getUri()
1412 // give plugins a chance to set the URI
1413 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1415 // check for a local user first
1416 $user = User::getKV('id', $this->id);
1417 if ($user instanceof User) {
1418 $uri = $user->getUri();
1421 Event::handle('EndGetProfileUri', array($this, &$uri));
1428 * Returns an assumed acct: URI for a profile. Plugins are required.
1430 * @return string $uri
1432 public function getAcctUri()
1436 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1437 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1440 if ($acct === null) {
1441 throw new ProfileNoAcctUriException($this);
1447 function hasBlocked($other)
1449 $block = Profile_block::exists($this, $other);
1450 return !empty($block);
1453 function getAtomFeed()
1457 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1458 $user = User::getKV('id', $this->id);
1459 if (!empty($user)) {
1460 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1461 'format' => 'atom'));
1463 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1469 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1471 // TRANS: Exception thrown when trying view "repeated to me".
1472 throw new Exception(_('Not implemented since inbox change.'));
1476 * Get a Profile object by URI. Will call external plugins for help
1477 * using the event StartGetProfileFromURI.
1479 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1481 static function fromUri($uri)
1485 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1486 // Get a local user when plugin lookup (like OStatus) fails
1487 $user = User::getKV('uri', $uri);
1488 if ($user instanceof User) {
1489 $profile = $user->getProfile();
1491 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1494 if (!$profile instanceof Profile) {
1495 throw new UnknownUriException($uri);
1501 function canRead(Notice $notice)
1503 if ($notice->scope & Notice::SITE_SCOPE) {
1504 $user = $this->getUser();
1510 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1511 $replies = $notice->getReplies();
1513 if (!in_array($this->id, $replies)) {
1514 $groups = $notice->getGroups();
1518 foreach ($groups as $group) {
1519 if ($this->isMember($group)) {
1531 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1532 $author = $notice->getProfile();
1533 if (!Subscription::exists($this, $author)) {
1541 static function current()
1543 $user = common_current_user();
1547 $profile = $user->getProfile();
1553 * Magic function called at serialize() time.
1555 * We use this to drop a couple process-specific references
1556 * from DB_DataObject which can cause trouble in future
1559 * @return array of variable names to include in serialization.
1564 $vars = parent::__sleep();
1565 $skip = array('_user', '_group');
1566 return array_diff($vars, $skip);
1569 public function getProfile()
1574 public function sameAs(Profile $other)
1576 return $this->getID() === $other->getID();
1580 * This will perform shortenLinks with the connected User object.
1582 * Won't work on remote profiles or groups, so expect a
1583 * NoSuchUserException if you don't know it's a local User.
1585 * @param string $text String to shorten
1586 * @param boolean $always Disrespect minimum length etc.
1588 * @return string link-shortened $text
1590 public function shortenLinks($text, $always=false)
1592 return $this->getUser()->shortenLinks($text, $always);
1595 public function isPrivateStream()
1597 // We only know of public remote users as of yet...
1598 if (!$this->isLocal()) {
1601 return $this->getUser()->private_stream ? true : false;
1604 public function delPref($namespace, $topic) {
1605 return Profile_prefs::setData($this, $namespace, $topic, null);
1608 public function getPref($namespace, $topic, $default=null) {
1609 // If you want an exception to be thrown, call Profile_prefs::getData directly
1611 return Profile_prefs::getData($this, $namespace, $topic, $default);
1612 } catch (NoResultException $e) {
1617 // The same as getPref but will fall back to common_config value for the same namespace/topic
1618 public function getConfigPref($namespace, $topic)
1620 return Profile_prefs::getConfigData($this, $namespace, $topic);
1623 public function setPref($namespace, $topic, $data) {
1624 return Profile_prefs::setData($this, $namespace, $topic, $data);
1627 public function getConnectedApps($offset=0, $limit=null)
1629 return $this->getUser()->getConnectedApps($offset, $limit);