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' => 'utf8_general_ci'),
52 'fullname' => array('type' => 'varchar', 'length' => 191, 'description' => 'display name', 'collate' => 'utf8_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' => 'utf8_general_ci'),
55 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
56 'location' => array('type' => 'varchar', 'length' => 191, 'description' => 'physical location', 'collate' => 'utf8_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 getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
247 $stream = new TaggedProfileNoticeStream($this, $tag);
249 return $stream->getNotices($offset, $limit, $since_id, $max_id);
252 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
254 $stream = new ProfileNoticeStream($this, $scoped);
256 return $stream->getNotices($offset, $limit, $since_id, $max_id);
259 function isMember(User_group $group)
261 $groups = $this->getGroups(0, null);
262 while ($groups instanceof User_group && $groups->fetch()) {
263 if ($groups->id == $group->id) {
270 function isAdmin(User_group $group)
272 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
273 'group_id' => $group->id));
274 return (!empty($gm) && $gm->is_admin);
277 function isPendingMember($group)
279 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
280 'group_id' => $group->id));
281 return !empty($request);
284 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
288 $keypart = sprintf('profile:groups:%d', $this->id);
290 $idstring = self::cacheGet($keypart);
292 if ($idstring !== false) {
293 $ids = explode(',', $idstring);
295 $gm = new Group_member();
297 $gm->profile_id = $this->id;
300 while ($gm->fetch()) {
301 $ids[] = $gm->group_id;
305 self::cacheSet($keypart, implode(',', $ids));
308 if (!is_null($offset) && !is_null($limit)) {
309 $ids = array_slice($ids, $offset, $limit);
313 return User_group::multiGet('id', $ids);
314 } catch (NoResultException $e) {
315 return null; // throw exception when we handle it everywhere
319 function getGroupCount() {
320 $groups = $this->getGroups(0, null);
321 return $groups instanceof User_group
326 function isTagged($peopletag)
328 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
329 'tagged' => $this->id,
330 'tag' => $peopletag->tag));
334 function canTag($tagged)
336 if (empty($tagged)) {
340 if ($tagged->id == $this->id) {
344 $all = common_config('peopletag', 'allow_tagging', 'all');
345 $local = common_config('peopletag', 'allow_tagging', 'local');
346 $remote = common_config('peopletag', 'allow_tagging', 'remote');
347 $subs = common_config('peopletag', 'allow_tagging', 'subs');
353 $tagged_user = $tagged->getUser();
354 if (!empty($tagged_user)) {
359 return (Subscription::exists($this, $tagged) ||
360 Subscription::exists($tagged, $this));
361 } else if ($remote) {
367 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
371 $keypart = sprintf('profile:lists:%d', $this->id);
373 $idstr = self::cacheGet($keypart);
375 if ($idstr !== false) {
376 $ids = explode(',', $idstr);
378 $list = new Profile_list();
380 $list->selectAdd('id');
381 $list->tagger = $this->id;
382 $list->selectAdd('id as "cursor"');
385 $list->whereAdd('id > '.$since_id);
389 $list->whereAdd('id <= '.$max_id);
392 if($offset>=0 && !is_null($limit)) {
393 $list->limit($offset, $limit);
396 $list->orderBy('id DESC');
399 while ($list->fetch()) {
404 self::cacheSet($keypart, implode(',', $ids));
407 $showPrivate = (($auth_user instanceof User ||
408 $auth_user instanceof Profile) &&
409 $auth_user->id === $this->id);
413 foreach ($ids as $id) {
414 $list = Profile_list::getKV('id', $id);
416 ($showPrivate || !$list->private)) {
418 if (!isset($list->cursor)) {
419 $list->cursor = $list->id;
426 return new ArrayWrapper($lists);
430 * Get tags that other people put on this profile, in reverse-chron order
432 * @param (Profile|User) $auth_user Authorized user (used for privacy)
433 * @param int $offset Offset from latest
434 * @param int $limit Max number to get
435 * @param datetime $since_id max date
436 * @param datetime $max_id min date
438 * @return Profile_list resulting lists
441 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
443 $list = new Profile_list();
445 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
446 'from profile_tag join profile_list '.
447 'on (profile_tag.tagger = profile_list.tagger ' .
448 ' and profile_tag.tag = profile_list.tag) ' .
449 'where profile_tag.tagged = %d ',
453 if ($auth_user instanceof User || $auth_user instanceof Profile) {
454 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
455 'OR ( profile_list.tagger = %d AND ' .
456 'profile_list.private = true ) )',
459 $qry .= 'AND profile_list.private = 0 ';
463 $qry .= sprintf('AND (cursor > %d) ', $since_id);
467 $qry .= sprintf('AND (cursor < %d) ', $max_id);
470 $qry .= 'ORDER BY profile_tag.modified DESC ';
472 if ($offset >= 0 && !is_null($limit)) {
473 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
480 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
482 $tags = new Profile_list();
483 $tags->private = true;
484 $tags->tagger = $this->id;
487 $tags->whereAdd('id > '.$since_id);
491 $tags->whereAdd('id <= '.$max_id);
494 if($offset>=0 && !is_null($limit)) {
495 $tags->limit($offset, $limit);
498 $tags->orderBy('id DESC');
504 function hasLocalTags()
506 $tags = new Profile_tag();
508 $tags->joinAdd(array('tagger', 'user:id'));
509 $tags->whereAdd('tagged = '.$this->id);
510 $tags->whereAdd('tagger != '.$this->id);
515 return ($tags->N == 0) ? false : true;
518 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
520 $lists = new Profile_list();
521 $subs = new Profile_tag_subscription();
523 $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
525 #@fixme: postgres (round(date_part('epoch', my_date)))
526 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
528 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
531 $lists->whereAdd('cursor > '.$since_id);
535 $lists->whereAdd('cursor <= '.$max_id);
538 if($offset>=0 && !is_null($limit)) {
539 $lists->limit($offset, $limit);
542 $lists->orderBy('"cursor" DESC');
549 * Request to join the given group.
550 * May throw exceptions on failure.
552 * @param User_group $group
553 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
555 function joinGroup(User_group $group)
558 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
559 $join = Group_join_queue::saveNew($this, $group);
561 if (Event::handle('StartJoinGroup', array($group, $this))) {
562 $join = Group_member::join($group->id, $this->id);
563 self::blow('profile:groups:%d', $this->id);
564 self::blow('group:member_ids:%d', $group->id);
565 self::blow('group:member_count:%d', $group->id);
566 Event::handle('EndJoinGroup', array($group, $this));
570 // Send any applicable notifications...
577 * Leave a group that this profile is a member of.
579 * @param User_group $group
581 function leaveGroup(User_group $group)
583 if (Event::handle('StartLeaveGroup', array($group, $this))) {
584 Group_member::leave($group->id, $this->id);
585 self::blow('profile:groups:%d', $this->id);
586 self::blow('group:member_ids:%d', $group->id);
587 self::blow('group:member_count:%d', $group->id);
588 Event::handle('EndLeaveGroup', array($group, $this));
592 function avatarUrl($size=AVATAR_PROFILE_SIZE)
594 return Avatar::urlByProfile($this, $size);
597 function getSubscribed($offset=0, $limit=null)
599 $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
601 $profiles = Profile::multiGet('id', $subs);
602 } catch (NoResultException $e) {
608 function getSubscribers($offset=0, $limit=null)
610 $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
612 $profiles = Profile::multiGet('id', $subs);
613 } catch (NoResultException $e) {
619 function getTaggedSubscribers($tag, $offset=0, $limit=null)
622 'SELECT profile.* ' .
623 'FROM profile JOIN subscription ' .
624 'ON profile.id = subscription.subscriber ' .
625 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
626 'AND profile_tag.tagger = subscription.subscribed) ' .
627 'WHERE subscription.subscribed = %d ' .
628 "AND profile_tag.tag = '%s' " .
629 'AND subscription.subscribed != subscription.subscriber ' .
630 'ORDER BY subscription.created DESC ';
633 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
636 $profile = new Profile();
638 $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
643 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
646 'SELECT profile.* ' .
647 'FROM profile JOIN subscription ' .
648 'ON profile.id = subscription.subscribed ' .
649 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
650 'AND profile_tag.tagger = subscription.subscriber) ' .
651 'WHERE subscription.subscriber = %d ' .
652 "AND profile_tag.tag = '%s' " .
653 'AND subscription.subscribed != subscription.subscriber ' .
654 'ORDER BY subscription.created DESC ';
656 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
658 $profile = new Profile();
660 $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
666 * Get pending subscribers, who have not yet been approved.
672 function getRequests($offset=0, $limit=null)
675 'SELECT profile.* ' .
676 'FROM profile JOIN subscription_queue '.
677 'ON profile.id = subscription_queue.subscriber ' .
678 'WHERE subscription_queue.subscribed = %d ' .
679 'ORDER BY subscription_queue.created DESC ';
681 if ($limit != null) {
682 if (common_config('db','type') == 'pgsql') {
683 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
685 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
689 $members = new Profile();
691 $members->query(sprintf($qry, $this->id));
695 function subscriptionCount()
697 $c = Cache::instance();
700 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
701 if (is_integer($cnt)) {
706 $sub = new Subscription();
707 $sub->subscriber = $this->id;
709 $cnt = (int) $sub->count('distinct subscribed');
711 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
714 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
720 function subscriberCount()
722 $c = Cache::instance();
724 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
725 if (is_integer($cnt)) {
730 $sub = new Subscription();
731 $sub->subscribed = $this->id;
732 $sub->whereAdd('subscriber != subscribed');
733 $cnt = (int) $sub->count('distinct subscriber');
736 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
743 * Is this profile subscribed to another profile?
745 * @param Profile $other
748 function isSubscribed(Profile $other)
750 return Subscription::exists($this, $other);
754 * Check if a pending subscription request is outstanding for this...
756 * @param Profile $other
759 function hasPendingSubscription(Profile $other)
761 return Subscription_queue::exists($this, $other);
765 * Are these two profiles subscribed to each other?
767 * @param Profile $other
770 function mutuallySubscribed(Profile $other)
772 return $this->isSubscribed($other) &&
773 $other->isSubscribed($this);
776 function noticeCount()
778 $c = Cache::instance();
781 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
782 if (is_integer($cnt)) {
787 $notices = new Notice();
788 $notices->profile_id = $this->id;
789 $cnt = (int) $notices->count('distinct id');
792 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
798 function blowSubscriberCount()
800 $c = Cache::instance();
802 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
806 function blowSubscriptionCount()
808 $c = Cache::instance();
810 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
814 function blowNoticeCount()
816 $c = Cache::instance();
818 $c->delete(Cache::key('profile:notice_count:'.$this->id));
822 static function maxBio()
824 $biolimit = common_config('profile', 'biolimit');
825 // null => use global limit (distinct from 0!)
826 if (is_null($biolimit)) {
827 $biolimit = common_config('site', 'textlimit');
832 static function bioTooLong($bio)
834 $biolimit = self::maxBio();
835 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
838 function update($dataObject=false)
840 if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
842 $local = $this->getUser();
843 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
844 $origuser = clone($local);
845 $local->nickname = $this->nickname;
846 // updateWithKeys throws exception on failure.
847 $local->updateWithKeys($origuser);
849 // Clear the site owner, in case nickname changed
850 if ($local->hasRole(Profile_role::OWNER)) {
851 User::blow('user:site_owner');
853 } catch (NoSuchUserException $e) {
858 return parent::update($dataObject);
861 function delete($useWhere=false)
863 $this->_deleteNotices();
864 $this->_deleteSubscriptions();
865 $this->_deleteTags();
866 $this->_deleteBlocks();
867 $this->_deleteAttentions();
868 Avatar::deleteFromProfile($this, true);
870 // Warning: delete() will run on the batch objects,
871 // not on individual objects.
872 $related = array('Reply',
875 Event::handle('ProfileDeleteRelated', array($this, &$related));
877 foreach ($related as $cls) {
879 $inst->profile_id = $this->id;
883 $localuser = User::getKV('id', $this->id);
884 if ($localuser instanceof User) {
885 $localuser->delete();
888 return parent::delete($useWhere);
891 function _deleteNotices()
893 $notice = new Notice();
894 $notice->profile_id = $this->id;
896 if ($notice->find()) {
897 while ($notice->fetch()) {
898 $other = clone($notice);
904 function _deleteSubscriptions()
906 $sub = new Subscription();
907 $sub->subscriber = $this->id;
911 while ($sub->fetch()) {
912 $other = Profile::getKV('id', $sub->subscribed);
916 if ($other->id == $this->id) {
919 Subscription::cancel($this, $other);
922 $subd = new Subscription();
923 $subd->subscribed = $this->id;
926 while ($subd->fetch()) {
927 $other = Profile::getKV('id', $subd->subscriber);
931 if ($other->id == $this->id) {
934 Subscription::cancel($other, $this);
937 $self = new Subscription();
939 $self->subscriber = $this->id;
940 $self->subscribed = $this->id;
945 function _deleteTags()
947 $tag = new Profile_tag();
948 $tag->tagged = $this->id;
952 function _deleteBlocks()
954 $block = new Profile_block();
955 $block->blocked = $this->id;
958 $block = new Group_block();
959 $block->blocked = $this->id;
963 function _deleteAttentions()
965 $att = new Attention();
966 $att->profile_id = $this->getID();
969 while ($att->fetch()) {
970 // Can't do delete() on the object directly since it won't remove all of it
971 $other = clone($att);
977 // XXX: identical to Notice::getLocation.
979 public function getLocation()
983 if (!empty($this->location_id) && !empty($this->location_ns)) {
984 $location = Location::fromId($this->location_id, $this->location_ns);
987 if (is_null($location)) { // no ID, or Location::fromId() failed
988 if (!empty($this->lat) && !empty($this->lon)) {
989 $location = Location::fromLatLon($this->lat, $this->lon);
993 if (is_null($location)) { // still haven't found it!
994 if (!empty($this->location)) {
995 $location = Location::fromName($this->location);
1002 public function shareLocation()
1004 $cfg = common_config('location', 'share');
1006 if ($cfg == 'always') {
1008 } else if ($cfg == 'never') {
1011 $share = common_config('location', 'sharedefault');
1013 // Check if user has a personal setting for this
1014 $prefs = User_location_prefs::getKV('user_id', $this->id);
1016 if (!empty($prefs)) {
1017 $share = $prefs->share_location;
1025 function hasRole($name)
1028 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1029 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1031 $has_role = !empty($role);
1032 Event::handle('EndHasRole', array($this, $name, $has_role));
1037 function grantRole($name)
1039 if (Event::handle('StartGrantRole', array($this, $name))) {
1041 $role = new Profile_role();
1043 $role->profile_id = $this->id;
1044 $role->role = $name;
1045 $role->created = common_sql_now();
1047 $result = $role->insert();
1050 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1053 if ($name == 'owner') {
1054 User::blow('user:site_owner');
1057 Event::handle('EndGrantRole', array($this, $name));
1063 function revokeRole($name)
1065 if (Event::handle('StartRevokeRole', array($this, $name))) {
1067 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1071 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1072 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1073 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1076 $result = $role->delete();
1079 common_log_db_error($role, 'DELETE', __FILE__);
1080 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1081 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1082 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1085 if ($name == 'owner') {
1086 User::blow('user:site_owner');
1089 Event::handle('EndRevokeRole', array($this, $name));
1095 function isSandboxed()
1097 return $this->hasRole(Profile_role::SANDBOXED);
1100 function isSilenced()
1102 return $this->hasRole(Profile_role::SILENCED);
1107 $this->grantRole(Profile_role::SANDBOXED);
1110 function unsandbox()
1112 $this->revokeRole(Profile_role::SANDBOXED);
1117 $this->grantRole(Profile_role::SILENCED);
1118 if (common_config('notice', 'hidespam')) {
1119 $this->flushVisibility();
1123 function unsilence()
1125 $this->revokeRole(Profile_role::SILENCED);
1126 if (common_config('notice', 'hidespam')) {
1127 $this->flushVisibility();
1131 function flushVisibility()
1134 $stream = new ProfileNoticeStream($this, $this);
1135 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1136 foreach ($ids as $id) {
1137 self::blow('notice:in-scope-for:%d:null', $id);
1142 * Does this user have the right to do X?
1144 * With our role-based authorization, this is merely a lookup for whether the user
1145 * has a particular role. The implementation currently uses a switch statement
1146 * to determine if the user has the pre-defined role to exercise the right. Future
1147 * implementations may allow per-site roles, and different mappings of roles to rights.
1149 * @param $right string Name of the right, usually a constant in class Right
1150 * @return boolean whether the user has the right in question
1152 public function hasRight($right)
1156 if ($this->hasRole(Profile_role::DELETED)) {
1160 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1163 case Right::DELETEOTHERSNOTICE:
1164 case Right::MAKEGROUPADMIN:
1165 case Right::SANDBOXUSER:
1166 case Right::SILENCEUSER:
1167 case Right::DELETEUSER:
1168 case Right::DELETEGROUP:
1169 case Right::TRAINSPAM:
1170 case Right::REVIEWSPAM:
1171 $result = $this->hasRole(Profile_role::MODERATOR);
1173 case Right::CONFIGURESITE:
1174 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1176 case Right::GRANTROLE:
1177 case Right::REVOKEROLE:
1178 $result = $this->hasRole(Profile_role::OWNER);
1180 case Right::NEWNOTICE:
1181 case Right::NEWMESSAGE:
1182 case Right::SUBSCRIBE:
1183 case Right::CREATEGROUP:
1184 $result = !$this->isSilenced();
1186 case Right::PUBLICNOTICE:
1187 case Right::EMAILONREPLY:
1188 case Right::EMAILONSUBSCRIBE:
1189 case Right::EMAILONFAVE:
1190 $result = !$this->isSandboxed();
1192 case Right::WEBLOGIN:
1193 $result = !$this->isSilenced();
1196 $result = !$this->isSilenced();
1198 case Right::BACKUPACCOUNT:
1199 $result = common_config('profile', 'backup');
1201 case Right::RESTOREACCOUNT:
1202 $result = common_config('profile', 'restore');
1204 case Right::DELETEACCOUNT:
1205 $result = common_config('profile', 'delete');
1207 case Right::MOVEACCOUNT:
1208 $result = common_config('profile', 'move');
1218 // FIXME: Can't put Notice typing here due to ArrayWrapper
1219 public function hasRepeated($notice)
1221 // XXX: not really a pkey, but should work
1223 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1224 'repeat_of' => $notice->id));
1226 return !empty($notice);
1230 * Returns an XML string fragment with limited profile information
1231 * as an Atom <author> element.
1233 * Assumes that Atom has been previously set up as the base namespace.
1235 * @param Profile $cur the current authenticated user
1239 function asAtomAuthor($cur = null)
1241 $xs = new XMLStringer(true);
1243 $xs->elementStart('author');
1244 $xs->element('name', null, $this->nickname);
1245 $xs->element('uri', null, $this->getUri());
1248 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1249 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1250 $xs->element('statusnet:profile_info', $attrs, null);
1252 $xs->elementEnd('author');
1254 return $xs->getString();
1258 * Extra profile info for atom entries
1260 * Clients use some extra profile info in the atom stream.
1261 * This gives it to them.
1263 * @param Profile $scoped The currently logged in/scoped profile
1265 * @return array representation of <statusnet:profile_info> element or null
1268 function profileInfo(Profile $scoped=null)
1270 $profileInfoAttr = array('local_id' => $this->id);
1272 if ($scoped instanceof Profile) {
1273 // Whether the current user is a subscribed to this profile
1274 $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1275 // Whether the current user is has blocked this profile
1276 $profileInfoAttr['blocking'] = $scoped->hasBlocked($this) ? 'true' : 'false';
1279 return array('statusnet:profile_info', $profileInfoAttr, null);
1283 * Returns an XML string fragment with profile information as an
1284 * Activity Streams <activity:actor> element.
1286 * Assumes that 'activity' namespace has been previously defined.
1290 function asActivityActor()
1292 return $this->asActivityNoun('actor');
1296 * Returns an XML string fragment with profile information as an
1297 * Activity Streams noun object with the given element type.
1299 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1300 * previously defined.
1302 * @param string $element one of 'actor', 'subject', 'object', 'target'
1306 function asActivityNoun($element)
1308 $noun = $this->asActivityObject();
1309 return $noun->asString('activity:' . $element);
1312 public function asActivityObject()
1314 $object = new ActivityObject();
1316 if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1317 $object->type = $this->getObjectType();
1318 $object->id = $this->getUri();
1319 $object->title = $this->getBestName();
1320 $object->link = $this->getUrl();
1321 $object->summary = $this->getDescription();
1324 $avatar = Avatar::getUploaded($this);
1325 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1326 } catch (NoAvatarException $e) {
1327 // Could not find an original avatar to link
1331 AVATAR_PROFILE_SIZE,
1336 foreach ($sizes as $size) {
1339 $avatar = Avatar::byProfile($this, $size);
1340 $alink = AvatarLink::fromAvatar($avatar);
1341 } catch (NoAvatarException $e) {
1342 $alink = new AvatarLink();
1343 $alink->type = 'image/png';
1344 $alink->height = $size;
1345 $alink->width = $size;
1346 $alink->url = Avatar::defaultImage($size);
1349 $object->avatarLinks[] = $alink;
1352 if (isset($this->lat) && isset($this->lon)) {
1353 $object->geopoint = (float)$this->lat
1354 . ' ' . (float)$this->lon;
1357 $object->poco = PoCo::fromProfile($this);
1359 if ($this->isLocal()) {
1360 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1363 Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1370 * Returns the profile's canonical url, not necessarily a uri/unique id
1372 * @return string $profileurl
1374 public function getUrl()
1376 if (empty($this->profileurl) ||
1377 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1378 throw new InvalidUrlException($this->profileurl);
1380 return $this->profileurl;
1383 public function getNickname()
1385 return $this->nickname;
1388 public function getFullname()
1390 return $this->fullname;
1393 public function getDescription()
1399 * Returns the best URI for a profile. Plugins may override.
1401 * @return string $uri
1403 public function getUri()
1407 // give plugins a chance to set the URI
1408 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1410 // check for a local user first
1411 $user = User::getKV('id', $this->id);
1412 if ($user instanceof User) {
1413 $uri = $user->getUri();
1416 Event::handle('EndGetProfileUri', array($this, &$uri));
1423 * Returns an assumed acct: URI for a profile. Plugins are required.
1425 * @return string $uri
1427 public function getAcctUri()
1431 if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1432 Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1435 if ($acct === null) {
1436 throw new ProfileNoAcctUriException($this);
1442 function hasBlocked($other)
1444 $block = Profile_block::exists($this, $other);
1445 return !empty($block);
1448 function getAtomFeed()
1452 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1453 $user = User::getKV('id', $this->id);
1454 if (!empty($user)) {
1455 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1456 'format' => 'atom'));
1458 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1464 public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1466 // TRANS: Exception thrown when trying view "repeated to me".
1467 throw new Exception(_('Not implemented since inbox change.'));
1471 * Get a Profile object by URI. Will call external plugins for help
1472 * using the event StartGetProfileFromURI.
1474 * @param string $uri A unique identifier for a resource (profile/group/whatever)
1476 static function fromUri($uri)
1480 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1481 // Get a local user when plugin lookup (like OStatus) fails
1482 $user = User::getKV('uri', $uri);
1483 if ($user instanceof User) {
1484 $profile = $user->getProfile();
1486 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1489 if (!$profile instanceof Profile) {
1490 throw new UnknownUriException($uri);
1496 function canRead(Notice $notice)
1498 if ($notice->scope & Notice::SITE_SCOPE) {
1499 $user = $this->getUser();
1505 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1506 $replies = $notice->getReplies();
1508 if (!in_array($this->id, $replies)) {
1509 $groups = $notice->getGroups();
1513 foreach ($groups as $group) {
1514 if ($this->isMember($group)) {
1526 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1527 $author = $notice->getProfile();
1528 if (!Subscription::exists($this, $author)) {
1536 static function current()
1538 $user = common_current_user();
1542 $profile = $user->getProfile();
1548 * Magic function called at serialize() time.
1550 * We use this to drop a couple process-specific references
1551 * from DB_DataObject which can cause trouble in future
1554 * @return array of variable names to include in serialization.
1559 $vars = parent::__sleep();
1560 $skip = array('_user', '_group');
1561 return array_diff($vars, $skip);
1564 public function getProfile()
1570 * This will perform shortenLinks with the connected User object.
1572 * Won't work on remote profiles or groups, so expect a
1573 * NoSuchUserException if you don't know it's a local User.
1575 * @param string $text String to shorten
1576 * @param boolean $always Disrespect minimum length etc.
1578 * @return string link-shortened $text
1580 public function shortenLinks($text, $always=false)
1582 return $this->getUser()->shortenLinks($text, $always);
1585 public function isPrivateStream()
1587 // We only know of public remote users as of yet...
1588 if (!$this->isLocal()) {
1591 return $this->getUser()->private_stream ? true : false;
1594 public function delPref($namespace, $topic) {
1595 return Profile_prefs::setData($this, $namespace, $topic, null);
1598 public function getPref($namespace, $topic, $default=null) {
1599 // If you want an exception to be thrown, call Profile_prefs::getData directly
1601 return Profile_prefs::getData($this, $namespace, $topic, $default);
1602 } catch (NoResultException $e) {
1607 // The same as getPref but will fall back to common_config value for the same namespace/topic
1608 public function getConfigPref($namespace, $topic)
1610 return Profile_prefs::getConfigData($this, $namespace, $topic);
1613 public function setPref($namespace, $topic, $data) {
1614 return Profile_prefs::setData($this, $namespace, $topic, $data);