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('GNUSOCIAL')) { exit(1); }
23 * Table Definition for profile
25 class Profile extends Managed_DataObject
27 public $__table = 'profile'; // table name
28 public $id; // int(4) primary_key not_null
29 public $nickname; // varchar(64) multiple_key not_null
30 public $fullname; // text()
31 public $profileurl; // text()
32 public $homepage; // text()
33 public $bio; // text() multiple_key
34 public $location; // text()
35 public $lat; // decimal(10,7)
36 public $lon; // decimal(10,7)
37 public $location_id; // int(4)
38 public $location_ns; // int(4)
39 public $created; // datetime() not_null
40 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
42 public static function schemaDef()
45 'description' => 'local and remote users have profiles',
47 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
48 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8mb4_general_ci'),
49 'fullname' => array('type' => 'text', 'description' => 'display name', 'collate' => 'utf8mb4_general_ci'),
50 'profileurl' => array('type' => 'text', 'description' => 'URL, cached so we dont regenerate'),
51 'homepage' => array('type' => 'text', 'description' => 'identifying URL', 'collate' => 'utf8mb4_general_ci'),
52 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8mb4_general_ci'),
53 'location' => array('type' => 'text', 'description' => 'physical location', 'collate' => 'utf8mb4_general_ci'),
54 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
55 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
56 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
57 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
59 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
60 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
62 'primary key' => array('id'),
64 'profile_nickname_idx' => array('nickname'),
68 // Add a fulltext index
70 if (common_config('search', 'type') == 'fulltext') {
71 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
77 public static function getByEmail($email)
79 // in the future, profiles should have emails stored...
80 $user = User::getKV('email', $email);
81 if (!($user instanceof User)) {
82 throw new NoSuchUserException(array('email'=>$email));
84 return $user->getProfile();
87 protected $_user = array();
89 public function getUser()
91 if (!isset($this->_user[$this->id])) {
92 $user = User::getKV('id', $this->id);
93 if (!$user instanceof User) {
94 throw new NoSuchUserException(array('id'=>$this->id));
96 $this->_user[$this->id] = $user;
98 return $this->_user[$this->id];
101 protected $_group = array();
103 public function getGroup()
105 if (!isset($this->_group[$this->id])) {
106 $group = User_group::getKV('profile_id', $this->id);
107 if (!$group instanceof User_group) {
108 throw new NoSuchGroupException(array('profile_id'=>$this->id));
110 $this->_group[$this->id] = $group;
112 return $this->_group[$this->id];
115 public function isGroup()
120 } catch (NoSuchGroupException $e) {
125 public function isLocal()
129 } catch (NoSuchUserException $e) {
135 // Returns false if the user has no password (which will always
136 // be the case for remote users). This can be the case for OpenID
137 // logins or other mechanisms which don't store a password hash.
138 public function hasPassword()
141 return $this->getUser()->hasPassword();
142 } catch (NoSuchUserException $e) {
147 public function getObjectType()
149 // FIXME: More types... like peopletags and whatever
150 if ($this->isGroup()) {
151 return ActivityObject::GROUP;
153 return ActivityObject::PERSON;
157 public function getAvatar($width, $height=null)
159 return Avatar::byProfile($this, $width, $height);
162 public function setOriginal($filename)
164 if ($this->isGroup()) {
165 // Until Group avatars are handled just like profile avatars.
166 return $this->getGroup()->setOriginal($filename);
169 $imagefile = new ImageFile(null, Avatar::path($filename));
171 $avatar = new Avatar();
172 $avatar->profile_id = $this->id;
173 $avatar->width = $imagefile->width;
174 $avatar->height = $imagefile->height;
175 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
176 $avatar->filename = $filename;
177 $avatar->original = true;
178 $avatar->url = Avatar::url($filename);
179 $avatar->created = common_sql_now();
181 // XXX: start a transaction here
182 if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
183 // If we can't delete the old avatars, let's abort right here.
184 @unlink(Avatar::path($filename));
192 * Gets either the full name (if filled) or the nickname.
196 function getBestName()
198 return ($this->fullname) ? $this->fullname : $this->nickname;
202 * Takes the currently scoped profile into account to give a name
203 * to list in notice streams. Preferences may differ between profiles.
205 function getStreamName()
207 $user = common_current_user();
208 if ($user instanceof User && $user->streamNicknames()) {
209 return $this->nickname;
212 return $this->getBestName();
216 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
217 * if no fullname is provided.
221 function getFancyName()
223 if ($this->fullname) {
224 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
225 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
227 return $this->nickname;
232 * Get the most recent notice posted by this user, if any.
234 * @return mixed Notice or null
236 function getCurrentNotice()
238 $notice = $this->getNotices(0, 1);
240 if ($notice->fetch()) {
241 if ($notice instanceof ArrayWrapper) {
242 // hack for things trying to work with single notices
243 return $notice->_items[0];
251 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
253 return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
256 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
258 $stream = new TaggedProfileNoticeStream($this, $tag);
260 return $stream->getNotices($offset, $limit, $since_id, $max_id);
263 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
265 $stream = new ProfileNoticeStream($this, $scoped);
267 return $stream->getNotices($offset, $limit, $since_id, $max_id);
270 function isMember(User_group $group)
272 $groups = $this->getGroups(0, null);
273 while ($groups instanceof User_group && $groups->fetch()) {
274 if ($groups->id == $group->id) {
281 function isAdmin(User_group $group)
283 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
284 'group_id' => $group->id));
285 return (!empty($gm) && $gm->is_admin);
288 function isPendingMember($group)
290 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
291 'group_id' => $group->id));
292 return !empty($request);
295 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
299 $keypart = sprintf('profile:groups:%d', $this->id);
301 $idstring = self::cacheGet($keypart);
303 if ($idstring !== false) {
304 $ids = explode(',', $idstring);
306 $gm = new Group_member();
308 $gm->profile_id = $this->id;
311 while ($gm->fetch()) {
312 $ids[] = $gm->group_id;
316 self::cacheSet($keypart, implode(',', $ids));
319 if (!is_null($offset) && !is_null($limit)) {
320 $ids = array_slice($ids, $offset, $limit);
324 return User_group::multiGet('id', $ids);
325 } catch (NoResultException $e) {
326 return null; // throw exception when we handle it everywhere
330 function getGroupCount() {
331 $groups = $this->getGroups(0, null);
332 return $groups instanceof User_group
337 function isTagged($peopletag)
339 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
340 'tagged' => $this->id,
341 'tag' => $peopletag->tag));
345 function canTag($tagged)
347 if (empty($tagged)) {
351 if ($tagged->id == $this->id) {
355 $all = common_config('peopletag', 'allow_tagging', 'all');
356 $local = common_config('peopletag', 'allow_tagging', 'local');
357 $remote = common_config('peopletag', 'allow_tagging', 'remote');
358 $subs = common_config('peopletag', 'allow_tagging', 'subs');
364 $tagged_user = $tagged->getUser();
365 if (!empty($tagged_user)) {
370 return (Subscription::exists($this, $tagged) ||
371 Subscription::exists($tagged, $this));
372 } else if ($remote) {
378 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
382 $keypart = sprintf('profile:lists:%d', $this->id);
384 $idstr = self::cacheGet($keypart);
386 if ($idstr !== false) {
387 $ids = explode(',', $idstr);
389 $list = new Profile_list();
391 $list->selectAdd('id');
392 $list->tagger = $this->id;
393 $list->selectAdd('id as "cursor"');
396 $list->whereAdd('id > '.$since_id);
400 $list->whereAdd('id <= '.$max_id);
403 if($offset>=0 && !is_null($limit)) {
404 $list->limit($offset, $limit);
407 $list->orderBy('id DESC');
410 while ($list->fetch()) {
415 self::cacheSet($keypart, implode(',', $ids));
418 $showPrivate = (($auth_user instanceof User ||
419 $auth_user instanceof Profile) &&
420 $auth_user->id === $this->id);
424 foreach ($ids as $id) {
425 $list = Profile_list::getKV('id', $id);
427 ($showPrivate || !$list->private)) {
429 if (!isset($list->cursor)) {
430 $list->cursor = $list->id;
437 return new ArrayWrapper($lists);
441 * Get tags that other people put on this profile, in reverse-chron order
443 * @param (Profile|User) $auth_user Authorized user (used for privacy)
444 * @param int $offset Offset from latest
445 * @param int $limit Max number to get
446 * @param datetime $since_id max date
447 * @param datetime $max_id min date
449 * @return Profile_list resulting lists
452 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
454 $list = new Profile_list();
456 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
457 'from profile_tag join profile_list '.
458 'on (profile_tag.tagger = profile_list.tagger ' .
459 ' and profile_tag.tag = profile_list.tag) ' .
460 'where profile_tag.tagged = %d ',
464 if ($auth_user instanceof User || $auth_user instanceof Profile) {
465 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
466 'OR ( profile_list.tagger = %d AND ' .
467 'profile_list.private = true ) )',
470 $qry .= 'AND profile_list.private = 0 ';
474 $qry .= sprintf('AND (cursor > %d) ', $since_id);
478 $qry .= sprintf('AND (cursor < %d) ', $max_id);
481 $qry .= 'ORDER BY profile_tag.modified DESC ';
483 if ($offset >= 0 && !is_null($limit)) {
484 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
491 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
493 $tags = new Profile_list();
494 $tags->private = true;
495 $tags->tagger = $this->id;
498 $tags->whereAdd('id > '.$since_id);
502 $tags->whereAdd('id <= '.$max_id);
505 if($offset>=0 && !is_null($limit)) {
506 $tags->limit($offset, $limit);
509 $tags->orderBy('id DESC');
515 function hasLocalTags()
517 $tags = new Profile_tag();
519 $tags->joinAdd(array('tagger', 'user:id'));
520 $tags->whereAdd('tagged = '.$this->id);
521 $tags->whereAdd('tagger != '.$this->id);
526 return ($tags->N == 0) ? false : true;
529 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
531 $lists = new Profile_list();
532 $subs = new Profile_tag_subscription();
534 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
536 #@fixme: postgres (round(date_part('epoch', my_date)))
537 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
539 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
542 $lists->whereAdd('cursor > '.$since_id);
546 $lists->whereAdd('cursor <= '.$max_id);
549 if($offset>=0 && !is_null($limit)) {
550 $lists->limit($offset, $limit);
553 $lists->orderBy('"cursor" DESC');
560 * Request to join the given group.
561 * May throw exceptions on failure.
563 * @param User_group $group
564 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
566 function joinGroup(User_group $group)
569 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
570 $join = Group_join_queue::saveNew($this, $group);
572 if (Event::handle('StartJoinGroup', array($group, $this))) {
573 $join = Group_member::join($group->id, $this->id);
574 self::blow('profile:groups:%d', $this->id);
575 self::blow('group:member_ids:%d', $group->id);
576 self::blow('group:member_count:%d', $group->id);
577 Event::handle('EndJoinGroup', array($group, $this));
581 // Send any applicable notifications...
588 * Leave a group that this profile is a member of.
590 * @param User_group $group
592 function leaveGroup(User_group $group)
594 if (Event::handle('StartLeaveGroup', array($group, $this))) {
595 Group_member::leave($group->id, $this->id);
596 self::blow('profile:groups:%d', $this->id);
597 self::blow('group:member_ids:%d', $group->id);
598 self::blow('group:member_count:%d', $group->id);
599 Event::handle('EndLeaveGroup', array($group, $this));
603 function avatarUrl($size=AVATAR_PROFILE_SIZE)
605 return Avatar::urlByProfile($this, $size);
608 function getSubscribed($offset=0, $limit=null)
610 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
612 $profiles = Profile::multiGet('id', $subs);
613 } catch (NoResultException $e) {
619 function getSubscribers($offset=0, $limit=null)
621 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
623 $profiles = Profile::multiGet('id', $subs);
624 } catch (NoResultException $e) {
630 function getTaggedSubscribers($tag, $offset=0, $limit=null)
633 'SELECT profile.* ' .
634 'FROM profile JOIN subscription ' .
635 'ON profile.id = subscription.subscriber ' .
636 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
637 'AND profile_tag.tagger = subscription.subscribed) ' .
638 'WHERE subscription.subscribed = %d ' .
639 "AND profile_tag.tag = '%s' " .
640 'AND subscription.subscribed != subscription.subscriber ' .
641 'ORDER BY subscription.created DESC ';
644 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
647 $profile = new Profile();
649 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
654 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
657 'SELECT profile.* ' .
658 'FROM profile JOIN subscription ' .
659 'ON profile.id = subscription.subscribed ' .
660 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
661 'AND profile_tag.tagger = subscription.subscriber) ' .
662 'WHERE subscription.subscriber = %d ' .
663 "AND profile_tag.tag = '%s' " .
664 'AND subscription.subscribed != subscription.subscriber ' .
665 'ORDER BY subscription.created DESC ';
667 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
669 $profile = new Profile();
671 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
677 * Get pending subscribers, who have not yet been approved.
683 function getRequests($offset=0, $limit=null)
686 'SELECT profile.* ' .
687 'FROM profile JOIN subscription_queue '.
688 'ON profile.id = subscription_queue.subscriber ' .
689 'WHERE subscription_queue.subscribed = %d ' .
690 'ORDER BY subscription_queue.created DESC ';
692 if ($limit != null) {
693 if (common_config('db','type') == 'pgsql') {
694 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
696 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
700 $members = new Profile();
702 $members->query(sprintf($qry, $this->id));
706 function subscriptionCount()
708 $c = Cache::instance();
711 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
712 if (is_integer($cnt)) {
717 $sub = new Subscription();
718 $sub->subscriber = $this->id;
720 $cnt = (int) $sub->count('distinct subscribed');
722 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
725 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
731 function subscriberCount()
733 $c = Cache::instance();
735 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
736 if (is_integer($cnt)) {
741 $sub = new Subscription();
742 $sub->subscribed = $this->id;
743 $sub->whereAdd('subscriber != subscribed');
744 $cnt = (int) $sub->count('distinct subscriber');
747 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
754 * Is this profile subscribed to another profile?
756 * @param Profile $other
759 function isSubscribed(Profile $other)
761 return Subscription::exists($this, $other);
765 * Check if a pending subscription request is outstanding for this...
767 * @param Profile $other
770 function hasPendingSubscription(Profile $other)
772 return Subscription_queue::exists($this, $other);
776 * Are these two profiles subscribed to each other?
778 * @param Profile $other
781 function mutuallySubscribed(Profile $other)
783 return $this->isSubscribed($other) &&
784 $other->isSubscribed($this);
787 function noticeCount()
789 $c = Cache::instance();
792 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
793 if (is_integer($cnt)) {
798 $notices = new Notice();
799 $notices->profile_id = $this->id;
800 $cnt = (int) $notices->count('distinct id');
803 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
809 function blowSubscriberCount()
811 $c = Cache::instance();
813 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
817 function blowSubscriptionCount()
819 $c = Cache::instance();
821 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
825 function blowNoticeCount()
827 $c = Cache::instance();
829 $c->delete(Cache::key('profile:notice_count:'.$this->id));
833 static function maxBio()
835 $biolimit = common_config('profile', 'biolimit');
836 // null => use global limit (distinct from 0!)
837 if (is_null($biolimit)) {
838 $biolimit = common_config('site', 'textlimit');
843 static function bioTooLong($bio)
845 $biolimit = self::maxBio();
846 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
849 function update($dataObject=false)
851 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
853 $local = $this->getUser();
854 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
855 $origuser = clone($local);
856 $local->nickname = $this->nickname;
857 // updateWithKeys throws exception on failure.
858 $local->updateWithKeys($origuser);
860 // Clear the site owner, in case nickname changed
861 if ($local->hasRole(Profile_role::OWNER)) {
862 User::blow('user:site_owner');
864 } catch (NoSuchUserException $e) {
869 return parent::update($dataObject);
872 function delete($useWhere=false)
874 // just in case it hadn't been done before... (usually set before adding deluser to queue handling!)
875 if (!$this->hasRole(Profile_role::DELETED)) {
876 $this->grantRole(Profile_role::DELETED);
879 $this->_deleteNotices();
880 $this->_deleteSubscriptions();
881 $this->_deleteTags();
882 $this->_deleteBlocks();
883 $this->_deleteAttentions();
884 Avatar::deleteFromProfile($this, true);
886 // Warning: delete() will run on the batch objects,
887 // not on individual objects.
888 $related = array('Reply',
891 Event::handle('ProfileDeleteRelated', array($this, &$related));
893 foreach ($related as $cls) {
895 $inst->profile_id = $this->id;
899 $localuser = User::getKV('id', $this->id);
900 if ($localuser instanceof User) {
901 $localuser->delete();
904 return parent::delete($useWhere);
907 function _deleteNotices()
909 $notice = new Notice();
910 $notice->profile_id = $this->id;
912 if ($notice->find()) {
913 while ($notice->fetch()) {
914 $other = clone($notice);
920 function _deleteSubscriptions()
922 $sub = new Subscription();
923 $sub->subscriber = $this->id;
927 while ($sub->fetch()) {
928 $other = Profile::getKV('id', $sub->subscribed);
932 if ($other->id == $this->id) {
935 Subscription::cancel($this, $other);
938 $subd = new Subscription();
939 $subd->subscribed = $this->id;
942 while ($subd->fetch()) {
943 $other = Profile::getKV('id', $subd->subscriber);
947 if ($other->id == $this->id) {
950 Subscription::cancel($other, $this);
953 $self = new Subscription();
955 $self->subscriber = $this->id;
956 $self->subscribed = $this->id;
961 function _deleteTags()
963 $tag = new Profile_tag();
964 $tag->tagged = $this->id;
968 function _deleteBlocks()
970 $block = new Profile_block();
971 $block->blocked = $this->id;
974 $block = new Group_block();
975 $block->blocked = $this->id;
979 function _deleteAttentions()
981 $att = new Attention();
982 $att->profile_id = $this->getID();
985 while ($att->fetch()) {
986 // Can't do delete() on the object directly since it won't remove all of it
987 $other = clone($att);
993 // XXX: identical to Notice::getLocation.
995 public function getLocation()
999 if (!empty($this->location_id) && !empty($this->location_ns)) {
1000 $location = Location::fromId($this->location_id, $this->location_ns);
1003 if (is_null($location)) { // no ID, or Location::fromId() failed
1004 if (!empty($this->lat) && !empty($this->lon)) {
1005 $location = Location::fromLatLon($this->lat, $this->lon);
1009 if (is_null($location)) { // still haven't found it!
1010 if (!empty($this->location)) {
1011 $location = Location::fromName($this->location);
1018 public function shareLocation()
1020 $cfg = common_config('location', 'share');
1022 if ($cfg == 'always') {
1024 } else if ($cfg == 'never') {
1027 $share = common_config('location', 'sharedefault');
1029 // Check if user has a personal setting for this
1030 $prefs = User_location_prefs::getKV('user_id', $this->id);
1032 if (!empty($prefs)) {
1033 $share = $prefs->share_location;
1041 function hasRole($name)
1044 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1045 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1047 $has_role = !empty($role);
1048 Event::handle('EndHasRole', array($this, $name, $has_role));
1053 function grantRole($name)
1055 if (Event::handle('StartGrantRole', array($this, $name))) {
1057 $role = new Profile_role();
1059 $role->profile_id = $this->id;
1060 $role->role = $name;
1061 $role->created = common_sql_now();
1063 $result = $role->insert();
1066 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1069 if ($name == 'owner') {
1070 User::blow('user:site_owner');
1073 Event::handle('EndGrantRole', array($this, $name));
1079 function revokeRole($name)
1081 if (Event::handle('StartRevokeRole', array($this, $name))) {
1083 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1087 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1088 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1089 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1092 $result = $role->delete();
1095 common_log_db_error($role, 'DELETE', __FILE__);
1096 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1097 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1098 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1101 if ($name == 'owner') {
1102 User::blow('user:site_owner');
1105 Event::handle('EndRevokeRole', array($this, $name));
1111 function isSandboxed()
1113 return $this->hasRole(Profile_role::SANDBOXED);
1116 function isSilenced()
1118 return $this->hasRole(Profile_role::SILENCED);
1123 $this->grantRole(Profile_role::SANDBOXED);
1126 function unsandbox()
1128 $this->revokeRole(Profile_role::SANDBOXED);
1133 $this->grantRole(Profile_role::SILENCED);
1134 if (common_config('notice', 'hidespam')) {
1135 $this->flushVisibility();
1139 function unsilence()
1141 $this->revokeRole(Profile_role::SILENCED);
1142 if (common_config('notice', 'hidespam')) {
1143 $this->flushVisibility();
1147 function flushVisibility()
1150 $stream = new ProfileNoticeStream($this, $this);
1151 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1152 foreach ($ids as $id) {
1153 self::blow('notice:in-scope-for:%d:null', $id);
1158 * Does this user have the right to do X?
1160 * With our role-based authorization, this is merely a lookup for whether the user
1161 * has a particular role. The implementation currently uses a switch statement
1162 * to determine if the user has the pre-defined role to exercise the right. Future
1163 * implementations may allow per-site roles, and different mappings of roles to rights.
1165 * @param $right string Name of the right, usually a constant in class Right
1166 * @return boolean whether the user has the right in question
1168 public function hasRight($right)
1172 if ($this->hasRole(Profile_role::DELETED)) {
1176 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1179 case Right::DELETEOTHERSNOTICE:
1180 case Right::MAKEGROUPADMIN:
1181 case Right::SANDBOXUSER:
1182 case Right::SILENCEUSER:
1183 case Right::DELETEUSER:
1184 case Right::DELETEGROUP:
1185 case Right::TRAINSPAM:
1186 case Right::REVIEWSPAM:
1187 $result = $this->hasRole(Profile_role::MODERATOR);
1189 case Right::CONFIGURESITE:
1190 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1192 case Right::GRANTROLE:
1193 case Right::REVOKEROLE:
1194 $result = $this->hasRole(Profile_role::OWNER);
1196 case Right::NEWNOTICE:
1197 case Right::NEWMESSAGE:
1198 case Right::SUBSCRIBE:
1199 case Right::CREATEGROUP:
1200 $result = !$this->isSilenced();
1202 case Right::PUBLICNOTICE:
1203 case Right::EMAILONREPLY:
1204 case Right::EMAILONSUBSCRIBE:
1205 case Right::EMAILONFAVE:
1206 $result = !$this->isSandboxed();
1208 case Right::WEBLOGIN:
1209 $result = !$this->isSilenced();
1212 $result = !$this->isSilenced();
1214 case Right::BACKUPACCOUNT:
1215 $result = common_config('profile', 'backup');
1217 case Right::RESTOREACCOUNT:
1218 $result = common_config('profile', 'restore');
1220 case Right::DELETEACCOUNT:
1221 $result = common_config('profile', 'delete');
1223 case Right::MOVEACCOUNT:
1224 $result = common_config('profile', 'move');
1234 // FIXME: Can't put Notice typing here due to ArrayWrapper
1235 public function hasRepeated($notice)
1237 // XXX: not really a pkey, but should work
1239 $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
1240 'repeat_of' => $notice->getID(),
1241 'verb' => ActivityVerb::SHARE));
1243 return !empty($notice);
1247 * Returns an XML string fragment with limited profile information
1248 * as an Atom <author> element.
1250 * Assumes that Atom has been previously set up as the base namespace.
1252 * @param Profile $cur the current authenticated user
1256 function asAtomAuthor($cur = null)
1258 $xs = new XMLStringer(true);
1260 $xs->elementStart('author');
1261 $xs->element('name', null, $this->nickname);
1262 $xs->element('uri', null, $this->getUri());
1265 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1266 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1267 $xs->element('statusnet:profile_info', $attrs, null);
1269 $xs->elementEnd('author');
1271 return $xs->getString();
1275 * Extra profile info for atom entries
1277 * Clients use some extra profile info in the atom stream.
1278 * This gives it to them.
1280 * @param Profile $scoped The currently logged in/scoped profile
1282 * @return array representation of <statusnet:profile_info> element or null
1285 function profileInfo(Profile $scoped=null)
1287 $profileInfoAttr = array('local_id' => $this->id);
1289 if ($scoped instanceof Profile) {
1290 // Whether the current user is a subscribed to this profile
1291 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1292 // Whether the current user is has blocked this profile
1293 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1296 return array('statusnet:profile_info', $profileInfoAttr, null);
1300 * Returns an XML string fragment with profile information as an
1301 * Activity Streams <activity:actor> element.
1303 * Assumes that 'activity' namespace has been previously defined.
1307 function asActivityActor()
1309 return $this->asActivityNoun('actor');
1313 * Returns an XML string fragment with profile information as an
1314 * Activity Streams noun object with the given element type.
1316 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1317 * previously defined.
1319 * @param string $element one of 'actor', 'subject', 'object', 'target'
1323 function asActivityNoun($element)
1325 $noun = $this->asActivityObject();
1326 return $noun->asString('activity:' . $element);
1329 public function asActivityObject()
1331 $object = new ActivityObject();
1333 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1334 $object->type = $this->getObjectType();
1335 $object->id = $this->getUri();
1336 $object->title = $this->getBestName();
1337 $object->link = $this->getUrl();
1338 $object->summary = $this->getDescription();
1341 $avatar = Avatar::getUploaded($this);
1342 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1343 } catch (NoAvatarException $e) {
1344 // Could not find an original avatar to link
1348 AVATAR_PROFILE_SIZE,
1353 foreach ($sizes as $size) {
1356 $avatar = Avatar::byProfile($this, $size);
1357 $alink = AvatarLink::fromAvatar($avatar);
1358 } catch (NoAvatarException $e) {
1359 $alink = new AvatarLink();
1360 $alink->type = 'image/png';
1361 $alink->height = $size;
1362 $alink->width = $size;
1363 $alink->url = Avatar::defaultImage($size);
1366 $object->avatarLinks[] = $alink;
1369 if (isset($this->lat) && isset($this->lon)) {
1370 $object->geopoint = (float)$this->lat
1371 . ' ' . (float)$this->lon;
1374 $object->poco = PoCo::fromProfile($this);
1376 if ($this->isLocal()) {
1377 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1380 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1387 * Returns the profile's canonical url, not necessarily a uri/unique id
1389 * @return string $profileurl
1391 public function getUrl()
1393 if (empty($this->profileurl) ||
1394 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1395 throw new InvalidUrlException($this->profileurl);
1397 return $this->profileurl;
1400 public function getNickname()
1402 return $this->nickname;
1405 public function getFullname()
1407 return $this->fullname;
1410 public function getHomepage()
1412 return $this->homepage;
1415 public function getDescription()
1421 * Returns the best URI for a profile. Plugins may override.
1423 * @return string $uri
1425 public function getUri()
1429 // give plugins a chance to set the URI
1430 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1432 // check for a local user first
1433 $user = User::getKV('id', $this->id);
1434 if ($user instanceof User) {
1435 $uri = $user->getUri();
1437 $group = User_group::getKV('profile_id', $this->id);
1438 if ($group instanceof User_group) {
1439 $uri = $group->getUri();
1443 Event::handle('EndGetProfileUri', array($this, &$uri));
1450 * Returns an assumed acct: URI for a profile. Plugins are required.
1452 * @return string $uri
1454 public function getAcctUri()
1458 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1459 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1462 if ($acct === null) {
1463 throw new ProfileNoAcctUriException($this);
1469 function hasBlocked($other)
1471 $block = Profile_block::exists($this, $other);
1472 return !empty($block);
1475 function getAtomFeed()
1479 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1480 $user = User::getKV('id', $this->id);
1481 if (!empty($user)) {
1482 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1483 'format' => 'atom'));
1485 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1491 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1493 // TRANS: Exception thrown when trying view "repeated to me".
1494 throw new Exception(_('Not implemented since inbox change.'));
1498 * Get a Profile object by URI. Will call external plugins for help
1499 * using the event StartGetProfileFromURI.
1501 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1503 static function fromUri($uri)
1507 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1508 // Get a local user when plugin lookup (like OStatus) fails
1509 $user = User::getKV('uri', $uri);
1510 if ($user instanceof User) {
1511 $profile = $user->getProfile();
1513 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1516 if (!$profile instanceof Profile) {
1517 throw new UnknownUriException($uri);
1523 function canRead(Notice $notice)
1525 if ($notice->scope & Notice::SITE_SCOPE) {
1526 $user = $this->getUser();
1532 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1533 $replies = $notice->getReplies();
1535 if (!in_array($this->id, $replies)) {
1536 $groups = $notice->getGroups();
1540 foreach ($groups as $group) {
1541 if ($this->isMember($group)) {
1553 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1554 $author = $notice->getProfile();
1555 if (!Subscription::exists($this, $author)) {
1563 static function current()
1565 $user = common_current_user();
1569 $profile = $user->getProfile();
1575 * Magic function called at serialize() time.
1577 * We use this to drop a couple process-specific references
1578 * from DB_DataObject which can cause trouble in future
1581 * @return array of variable names to include in serialization.
1586 $vars = parent::__sleep();
1587 $skip = array('_user', '_group');
1588 return array_diff($vars, $skip);
1591 public function getProfile()
1597 * Test whether the given profile is the same as the current class,
1598 * for testing identities.
1600 * @param Profile $other The other profile, usually from Action's $this->scoped
1604 public function sameAs(Profile $other=null)
1606 if (is_null($other)) {
1607 // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
1610 return $this->getID() === $other->getID();
1614 * This will perform shortenLinks with the connected User object.
1616 * Won't work on remote profiles or groups, so expect a
1617 * NoSuchUserException if you don't know it's a local User.
1619 * @param string $text String to shorten
1620 * @param boolean $always Disrespect minimum length etc.
1622 * @return string link-shortened $text
1624 public function shortenLinks($text, $always=false)
1626 return $this->getUser()->shortenLinks($text, $always);
1629 public function isPrivateStream()
1631 // We only know of public remote users as of yet...
1632 if (!$this->isLocal()) {
1635 return $this->getUser()->private_stream ? true : false;
1638 public function delPref($namespace, $topic) {
1639 return Profile_prefs::setData($this, $namespace, $topic, null);
1642 public function getPref($namespace, $topic, $default=null) {
1643 // If you want an exception to be thrown, call Profile_prefs::getData directly
1645 return Profile_prefs::getData($this, $namespace, $topic, $default);
1646 } catch (NoResultException $e) {
1651 // The same as getPref but will fall back to common_config value for the same namespace/topic
1652 public function getConfigPref($namespace, $topic)
1654 return Profile_prefs::getConfigData($this, $namespace, $topic);
1657 public function setPref($namespace, $topic, $data) {
1658 return Profile_prefs::setData($this, $namespace, $topic, $data);
1661 public function getConnectedApps($offset=0, $limit=null)
1663 return $this->getUser()->getConnectedApps($offset, $limit);