3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
23 * Table Definition for profile
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
27 class Profile extends Managed_DataObject
30 /* the code below is auto generated do not remove the above tag */
32 public $__table = 'profile'; // table name
33 public $id; // int(4) primary_key not_null
34 public $nickname; // varchar(64) multiple_key not_null
35 public $fullname; // varchar(255) multiple_key
36 public $profileurl; // varchar(255)
37 public $homepage; // varchar(255) multiple_key
38 public $bio; // text() multiple_key
39 public $location; // varchar(255) multiple_key
40 public $lat; // decimal(10,7)
41 public $lon; // decimal(10,7)
42 public $location_id; // int(4)
43 public $location_ns; // int(4)
44 public $created; // datetime() not_null
45 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
47 public static function schemaDef()
50 'description' => 'local and remote users have profiles',
52 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
53 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
54 'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
55 'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
56 'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
57 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
58 'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
59 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
60 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
61 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
62 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
64 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
65 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
67 'primary key' => array('id'),
69 'profile_nickname_idx' => array('nickname'),
73 // Add a fulltext index
75 if (common_config('search', 'type') == 'fulltext') {
76 $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
82 function multiGet($keyCol, $keyVals, $skipNulls=true)
84 return parent::multiGet('Profile', $keyCol, $keyVals, $skipNulls);
87 /* the code above is auto generated do not remove the tag below */
90 protected $_user = -1; // Uninitialized value distinct from null
94 if (is_int($this->_user) && $this->_user == -1) {
95 $this->_user = User::getKV('id', $this->id);
103 function getAvatar($width, $height=null)
105 if (is_null($height)) {
109 $avatar = $this->_getAvatar($width);
111 if (empty($avatar)) {
113 if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
114 $avatar = Avatar::pkeyGet(
116 'profile_id' => $this->id,
121 Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
124 $this->_fillAvatar($width, $avatar);
130 // XXX: @Fix me gargargar
131 function _getAvatar($width)
133 if (empty($this->_avatars)) {
134 $this->_avatars = array();
137 // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
138 // the previously used profile! Please shoot me now! --Zach
139 if (array_key_exists($width, $this->_avatars)) {
140 // Don't return cached avatar unless it's really for this profile
141 if ($this->_avatars[$width]->profile_id == $this->id) {
142 return $this->_avatars[$width];
149 function _fillAvatar($width, $avatar)
151 //common_debug("Storing avatar of width: {$avatar->width} and profile_id {$avatar->profile_id} in profile {$this->id}.");
152 $this->_avatars[$width] = $avatar;
156 function getOriginalAvatar()
158 $avatar = DB_DataObject::factory('avatar');
159 $avatar->profile_id = $this->id;
160 $avatar->original = true;
161 if ($avatar->find(true)) {
168 function setOriginal($filename)
170 $imagefile = new ImageFile($this->id, Avatar::path($filename));
172 $avatar = new Avatar();
173 $avatar->profile_id = $this->id;
174 $avatar->width = $imagefile->width;
175 $avatar->height = $imagefile->height;
176 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
177 $avatar->filename = $filename;
178 $avatar->original = true;
179 $avatar->url = Avatar::url($filename);
180 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
182 // XXX: start a transaction here
184 if (!$this->delete_avatars() || !$avatar->insert()) {
185 @unlink(Avatar::path($filename));
189 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
190 // We don't do a scaled one if original is our scaled size
191 if (!($avatar->width == $size && $avatar->height == $size)) {
192 $scaled_filename = $imagefile->resize($size);
194 //$scaled = DB_DataObject::factory('avatar');
195 $scaled = new Avatar();
196 $scaled->profile_id = $this->id;
197 $scaled->width = $size;
198 $scaled->height = $size;
199 $scaled->original = false;
200 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
201 $scaled->filename = $scaled_filename;
202 $scaled->url = Avatar::url($scaled_filename);
203 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
205 if (!$scaled->insert()) {
215 * Delete attached avatars for this user from the database and filesystem.
216 * This should be used instead of a batch delete() to ensure that files
217 * get removed correctly.
219 * @param boolean $original true to delete only the original-size file
222 function delete_avatars($original=true)
224 $avatar = new Avatar();
225 $avatar->profile_id = $this->id;
227 while ($avatar->fetch()) {
228 if ($avatar->original) {
229 if ($original == false) {
239 * Gets either the full name (if filled) or the nickname.
243 function getBestName()
245 return ($this->fullname) ? $this->fullname : $this->nickname;
249 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
250 * if no fullname is provided.
254 function getFancyName()
256 if ($this->fullname) {
257 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
258 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
260 return $this->nickname;
265 * Get the most recent notice posted by this user, if any.
267 * @return mixed Notice or null
269 function getCurrentNotice()
271 $notice = $this->getNotices(0, 1);
273 if ($notice->fetch()) {
274 if ($notice instanceof ArrayWrapper) {
275 // hack for things trying to work with single notices
276 return $notice->_items[0];
284 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
286 $stream = new TaggedProfileNoticeStream($this, $tag);
288 return $stream->getNotices($offset, $limit, $since_id, $max_id);
291 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
293 $stream = new ProfileNoticeStream($this);
295 return $stream->getNotices($offset, $limit, $since_id, $max_id);
298 function isMember($group)
300 $groups = $this->getGroups(0, null);
301 $gs = $groups->fetchAll();
302 foreach ($gs as $g) {
303 if ($group->id == $g->id) {
310 function isAdmin($group)
312 $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
313 'group_id' => $group->id));
314 return (!empty($gm) && $gm->is_admin);
317 function isPendingMember($group)
319 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
320 'group_id' => $group->id));
321 return !empty($request);
324 function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
328 $keypart = sprintf('profile:groups:%d', $this->id);
330 $idstring = self::cacheGet($keypart);
332 if ($idstring !== false) {
333 $ids = explode(',', $idstring);
335 $gm = new Group_member();
337 $gm->profile_id = $this->id;
340 while ($gm->fetch()) {
341 $ids[] = $gm->group_id;
345 self::cacheSet($keypart, implode(',', $ids));
348 if (!is_null($offset) && !is_null($limit)) {
349 $ids = array_slice($ids, $offset, $limit);
352 return User_group::multiGet('id', $ids);
355 function isTagged($peopletag)
357 $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
358 'tagged' => $this->id,
359 'tag' => $peopletag->tag));
363 function canTag($tagged)
365 if (empty($tagged)) {
369 if ($tagged->id == $this->id) {
373 $all = common_config('peopletag', 'allow_tagging', 'all');
374 $local = common_config('peopletag', 'allow_tagging', 'local');
375 $remote = common_config('peopletag', 'allow_tagging', 'remote');
376 $subs = common_config('peopletag', 'allow_tagging', 'subs');
382 $tagged_user = $tagged->getUser();
383 if (!empty($tagged_user)) {
388 return (Subscription::exists($this, $tagged) ||
389 Subscription::exists($tagged, $this));
390 } else if ($remote) {
396 function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
400 $keypart = sprintf('profile:lists:%d', $this->id);
402 $idstr = self::cacheGet($keypart);
404 if ($idstr !== false) {
405 $ids = explode(',', $idstr);
407 $list = new Profile_list();
409 $list->selectAdd('id');
410 $list->tagger = $this->id;
411 $list->selectAdd('id as "cursor"');
414 $list->whereAdd('id > '.$since_id);
418 $list->whereAdd('id <= '.$max_id);
421 if($offset>=0 && !is_null($limit)) {
422 $list->limit($offset, $limit);
425 $list->orderBy('id DESC');
428 while ($list->fetch()) {
433 self::cacheSet($keypart, implode(',', $ids));
436 $showPrivate = (($auth_user instanceof User ||
437 $auth_user instanceof Profile) &&
438 $auth_user->id === $this->id);
442 foreach ($ids as $id) {
443 $list = Profile_list::getKV('id', $id);
445 ($showPrivate || !$list->private)) {
447 if (!isset($list->cursor)) {
448 $list->cursor = $list->id;
455 return new ArrayWrapper($lists);
459 * Get tags that other people put on this profile, in reverse-chron order
461 * @param (Profile|User) $auth_user Authorized user (used for privacy)
462 * @param int $offset Offset from latest
463 * @param int $limit Max number to get
464 * @param datetime $since_id max date
465 * @param datetime $max_id min date
467 * @return Profile_list resulting lists
470 function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
472 $list = new Profile_list();
474 $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
475 'from profile_tag join profile_list '.
476 'on (profile_tag.tagger = profile_list.tagger ' .
477 ' and profile_tag.tag = profile_list.tag) ' .
478 'where profile_tag.tagged = %d ',
482 if ($auth_user instanceof User || $auth_user instanceof Profile) {
483 $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
484 'OR ( profile_list.tagger = %d AND ' .
485 'profile_list.private = true ) )',
488 $qry .= 'AND profile_list.private = 0 ';
492 $qry .= sprintf('AND (cursor > %d) ', $since_id);
496 $qry .= sprintf('AND (cursor < %d) ', $max_id);
499 $qry .= 'ORDER BY profile_tag.modified DESC ';
501 if ($offset >= 0 && !is_null($limit)) {
502 $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
509 function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
511 $tags = new Profile_list();
512 $tags->private = true;
513 $tags->tagger = $this->id;
516 $tags->whereAdd('id > '.$since_id);
520 $tags->whereAdd('id <= '.$max_id);
523 if($offset>=0 && !is_null($limit)) {
524 $tags->limit($offset, $limit);
527 $tags->orderBy('id DESC');
533 function hasLocalTags()
535 $tags = new Profile_tag();
537 $tags->joinAdd(array('tagger', 'user:id'));
538 $tags->whereAdd('tagged = '.$this->id);
539 $tags->whereAdd('tagger != '.$this->id);
544 return ($tags->N == 0) ? false : true;
547 function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
549 $lists = new Profile_list();
550 $subs = new Profile_tag_subscription();
552 $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
554 #@fixme: postgres (round(date_part('epoch', my_date)))
555 $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
557 $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
560 $lists->whereAdd('cursor > '.$since_id);
564 $lists->whereAdd('cursor <= '.$max_id);
567 if($offset>=0 && !is_null($limit)) {
568 $lists->limit($offset, $limit);
571 $lists->orderBy('"cursor" DESC');
578 * Request to join the given group.
579 * May throw exceptions on failure.
581 * @param User_group $group
582 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
584 function joinGroup(User_group $group)
587 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
588 $join = Group_join_queue::saveNew($this, $group);
590 if (Event::handle('StartJoinGroup', array($group, $this))) {
591 $join = Group_member::join($group->id, $this->id);
592 self::blow('profile:groups:%d', $this->id);
593 self::blow('group:member_ids:%d', $group->id);
594 self::blow('group:member_count:%d', $group->id);
595 Event::handle('EndJoinGroup', array($group, $this));
599 // Send any applicable notifications...
606 * Leave a group that this profile is a member of.
608 * @param User_group $group
610 function leaveGroup(User_group $group)
612 if (Event::handle('StartLeaveGroup', array($group, $this))) {
613 Group_member::leave($group->id, $this->id);
614 self::blow('profile:groups:%d', $this->id);
615 self::blow('group:member_ids:%d', $group->id);
616 self::blow('group:member_count:%d', $group->id);
617 Event::handle('EndLeaveGroup', array($group, $this));
621 function avatarUrl($size=AVATAR_PROFILE_SIZE)
623 $avatar = $this->getAvatar($size);
625 return $avatar->displayUrl();
627 return Avatar::defaultImage($size);
631 function getSubscriptions($offset=0, $limit=null)
633 $subs = Subscription::bySubscriber($this->id,
639 while ($subs->fetch()) {
640 $profile = Profile::getKV($subs->subscribed);
642 $profiles[] = $profile;
646 return new ArrayWrapper($profiles);
649 function getSubscribers($offset=0, $limit=null)
651 $subs = Subscription::bySubscribed($this->id,
657 while ($subs->fetch()) {
658 $profile = Profile::getKV($subs->subscriber);
660 $profiles[] = $profile;
664 return new ArrayWrapper($profiles);
667 function getTaggedSubscribers($tag)
670 'SELECT profile.* ' .
671 'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
672 'ON profile.id = subscription.subscriber ' .
673 'AND profile.id = profile_tag.tagged ' .
674 'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
675 'WHERE subscription.subscribed = %d ' .
676 'AND subscription.subscribed != subscription.subscriber ' .
677 'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
678 'AND profile_list.private = false ' .
679 'ORDER BY subscription.created DESC';
681 $profile = new Profile();
684 $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
686 while ($profile->fetch()) {
687 $tagged[] = clone($profile);
693 * Get pending subscribers, who have not yet been approved.
699 function getRequests($offset=0, $limit=null)
702 'SELECT profile.* ' .
703 'FROM profile JOIN subscription_queue '.
704 'ON profile.id = subscription_queue.subscriber ' .
705 'WHERE subscription_queue.subscribed = %d ' .
706 'ORDER BY subscription_queue.created DESC ';
708 if ($limit != null) {
709 if (common_config('db','type') == 'pgsql') {
710 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
712 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
716 $members = new Profile();
718 $members->query(sprintf($qry, $this->id));
722 function subscriptionCount()
724 $c = Cache::instance();
727 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
728 if (is_integer($cnt)) {
733 $sub = new Subscription();
734 $sub->subscriber = $this->id;
736 $cnt = (int) $sub->count('distinct subscribed');
738 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
741 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
747 function subscriberCount()
749 $c = Cache::instance();
751 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
752 if (is_integer($cnt)) {
757 $sub = new Subscription();
758 $sub->subscribed = $this->id;
759 $sub->whereAdd('subscriber != subscribed');
760 $cnt = (int) $sub->count('distinct subscriber');
763 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
770 * Is this profile subscribed to another profile?
772 * @param Profile $other
775 function isSubscribed($other)
777 return Subscription::exists($this, $other);
781 * Check if a pending subscription request is outstanding for this...
783 * @param Profile $other
786 function hasPendingSubscription($other)
788 return Subscription_queue::exists($this, $other);
792 * Are these two profiles subscribed to each other?
794 * @param Profile $other
797 function mutuallySubscribed($other)
799 return $this->isSubscribed($other) &&
800 $other->isSubscribed($this);
803 function hasFave($notice)
805 $fave = Fave::pkeyGet(array('user_id' => $this->id,
806 'notice_id' => $notice->id));
807 return ((is_null($fave)) ? false : true);
812 $c = Cache::instance();
814 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
815 if (is_integer($cnt)) {
821 $faves->user_id = $this->id;
822 $cnt = (int) $faves->count('notice_id');
825 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
831 function noticeCount()
833 $c = Cache::instance();
836 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
837 if (is_integer($cnt)) {
842 $notices = new Notice();
843 $notices->profile_id = $this->id;
844 $cnt = (int) $notices->count('distinct id');
847 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
853 function blowFavesCache()
855 $cache = Cache::instance();
857 // Faves don't happen chronologically, so we need to blow
859 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
860 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
861 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
862 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
864 $this->blowFaveCount();
867 function blowSubscriberCount()
869 $c = Cache::instance();
871 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
875 function blowSubscriptionCount()
877 $c = Cache::instance();
879 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
883 function blowFaveCount()
885 $c = Cache::instance();
887 $c->delete(Cache::key('profile:fave_count:'.$this->id));
891 function blowNoticeCount()
893 $c = Cache::instance();
895 $c->delete(Cache::key('profile:notice_count:'.$this->id));
899 static function maxBio()
901 $biolimit = common_config('profile', 'biolimit');
902 // null => use global limit (distinct from 0!)
903 if (is_null($biolimit)) {
904 $biolimit = common_config('site', 'textlimit');
909 static function bioTooLong($bio)
911 $biolimit = self::maxBio();
912 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
917 $this->_deleteNotices();
918 $this->_deleteSubscriptions();
919 $this->_deleteMessages();
920 $this->_deleteTags();
921 $this->_deleteBlocks();
922 $this->delete_avatars();
924 // Warning: delete() will run on the batch objects,
925 // not on individual objects.
926 $related = array('Reply',
929 Event::handle('ProfileDeleteRelated', array($this, &$related));
931 foreach ($related as $cls) {
933 $inst->profile_id = $this->id;
940 function _deleteNotices()
942 $notice = new Notice();
943 $notice->profile_id = $this->id;
945 if ($notice->find()) {
946 while ($notice->fetch()) {
947 $other = clone($notice);
953 function _deleteSubscriptions()
955 $sub = new Subscription();
956 $sub->subscriber = $this->id;
960 while ($sub->fetch()) {
961 $other = Profile::getKV('id', $sub->subscribed);
965 if ($other->id == $this->id) {
968 Subscription::cancel($this, $other);
971 $subd = new Subscription();
972 $subd->subscribed = $this->id;
975 while ($subd->fetch()) {
976 $other = Profile::getKV('id', $subd->subscriber);
980 if ($other->id == $this->id) {
983 Subscription::cancel($other, $this);
986 $self = new Subscription();
988 $self->subscriber = $this->id;
989 $self->subscribed = $this->id;
994 function _deleteMessages()
996 $msg = new Message();
997 $msg->from_profile = $this->id;
1000 $msg = new Message();
1001 $msg->to_profile = $this->id;
1005 function _deleteTags()
1007 $tag = new Profile_tag();
1008 $tag->tagged = $this->id;
1012 function _deleteBlocks()
1014 $block = new Profile_block();
1015 $block->blocked = $this->id;
1018 $block = new Group_block();
1019 $block->blocked = $this->id;
1023 // XXX: identical to Notice::getLocation.
1025 function getLocation()
1029 if (!empty($this->location_id) && !empty($this->location_ns)) {
1030 $location = Location::fromId($this->location_id, $this->location_ns);
1033 if (is_null($location)) { // no ID, or Location::fromId() failed
1034 if (!empty($this->lat) && !empty($this->lon)) {
1035 $location = Location::fromLatLon($this->lat, $this->lon);
1039 if (is_null($location)) { // still haven't found it!
1040 if (!empty($this->location)) {
1041 $location = Location::fromName($this->location);
1048 function hasRole($name)
1051 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1052 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1054 $has_role = !empty($role);
1055 Event::handle('EndHasRole', array($this, $name, $has_role));
1060 function grantRole($name)
1062 if (Event::handle('StartGrantRole', array($this, $name))) {
1064 $role = new Profile_role();
1066 $role->profile_id = $this->id;
1067 $role->role = $name;
1068 $role->created = common_sql_now();
1070 $result = $role->insert();
1073 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1076 if ($name == 'owner') {
1077 User::blow('user:site_owner');
1080 Event::handle('EndGrantRole', array($this, $name));
1086 function revokeRole($name)
1088 if (Event::handle('StartRevokeRole', array($this, $name))) {
1090 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1094 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1095 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1096 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1099 $result = $role->delete();
1102 common_log_db_error($role, 'DELETE', __FILE__);
1103 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1104 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1105 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1108 if ($name == 'owner') {
1109 User::blow('user:site_owner');
1112 Event::handle('EndRevokeRole', array($this, $name));
1118 function isSandboxed()
1120 return $this->hasRole(Profile_role::SANDBOXED);
1123 function isSilenced()
1125 return $this->hasRole(Profile_role::SILENCED);
1130 $this->grantRole(Profile_role::SANDBOXED);
1133 function unsandbox()
1135 $this->revokeRole(Profile_role::SANDBOXED);
1140 $this->grantRole(Profile_role::SILENCED);
1141 if (common_config('notice', 'hidespam')) {
1142 $this->flushVisibility();
1146 function unsilence()
1148 $this->revokeRole(Profile_role::SILENCED);
1149 if (common_config('notice', 'hidespam')) {
1150 $this->flushVisibility();
1154 function flushVisibility()
1157 $stream = new ProfileNoticeStream($this, $this);
1158 $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1159 foreach ($ids as $id) {
1160 self::blow('notice:in-scope-for:%d:null', $id);
1165 * Does this user have the right to do X?
1167 * With our role-based authorization, this is merely a lookup for whether the user
1168 * has a particular role. The implementation currently uses a switch statement
1169 * to determine if the user has the pre-defined role to exercise the right. Future
1170 * implementations may allow per-site roles, and different mappings of roles to rights.
1172 * @param $right string Name of the right, usually a constant in class Right
1173 * @return boolean whether the user has the right in question
1175 function hasRight($right)
1179 if ($this->hasRole(Profile_role::DELETED)) {
1183 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1186 case Right::DELETEOTHERSNOTICE:
1187 case Right::MAKEGROUPADMIN:
1188 case Right::SANDBOXUSER:
1189 case Right::SILENCEUSER:
1190 case Right::DELETEUSER:
1191 case Right::DELETEGROUP:
1192 case Right::TRAINSPAM:
1193 case Right::REVIEWSPAM:
1194 $result = $this->hasRole(Profile_role::MODERATOR);
1196 case Right::CONFIGURESITE:
1197 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1199 case Right::GRANTROLE:
1200 case Right::REVOKEROLE:
1201 $result = $this->hasRole(Profile_role::OWNER);
1203 case Right::NEWNOTICE:
1204 case Right::NEWMESSAGE:
1205 case Right::SUBSCRIBE:
1206 case Right::CREATEGROUP:
1207 $result = !$this->isSilenced();
1209 case Right::PUBLICNOTICE:
1210 case Right::EMAILONREPLY:
1211 case Right::EMAILONSUBSCRIBE:
1212 case Right::EMAILONFAVE:
1213 $result = !$this->isSandboxed();
1215 case Right::WEBLOGIN:
1216 $result = !$this->isSilenced();
1219 $result = !$this->isSilenced();
1221 case Right::BACKUPACCOUNT:
1222 $result = common_config('profile', 'backup');
1224 case Right::RESTOREACCOUNT:
1225 $result = common_config('profile', 'restore');
1227 case Right::DELETEACCOUNT:
1228 $result = common_config('profile', 'delete');
1230 case Right::MOVEACCOUNT:
1231 $result = common_config('profile', 'move');
1241 function hasRepeated($notice_id)
1243 // XXX: not really a pkey, but should work
1245 $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1246 'repeat_of' => $notice_id));
1248 return !empty($notice);
1252 * Returns an XML string fragment with limited profile information
1253 * as an Atom <author> element.
1255 * Assumes that Atom has been previously set up as the base namespace.
1257 * @param Profile $cur the current authenticated user
1261 function asAtomAuthor($cur = null)
1263 $xs = new XMLStringer(true);
1265 $xs->elementStart('author');
1266 $xs->element('name', null, $this->nickname);
1267 $xs->element('uri', null, $this->getUri());
1270 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1271 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1272 $xs->element('statusnet:profile_info', $attrs, null);
1274 $xs->elementEnd('author');
1276 return $xs->getString();
1280 * Extra profile info for atom entries
1282 * Clients use some extra profile info in the atom stream.
1283 * This gives it to them.
1285 * @param User $cur Current user
1287 * @return array representation of <statusnet:profile_info> element or null
1290 function profileInfo($cur)
1292 $profileInfoAttr = array('local_id' => $this->id);
1295 // Whether the current user is a subscribed to this profile
1296 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1297 // Whether the current user is has blocked this profile
1298 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
1301 return array('statusnet:profile_info', $profileInfoAttr, null);
1305 * Returns an XML string fragment with profile information as an
1306 * Activity Streams <activity:actor> element.
1308 * Assumes that 'activity' namespace has been previously defined.
1312 function asActivityActor()
1314 return $this->asActivityNoun('actor');
1318 * Returns an XML string fragment with profile information as an
1319 * Activity Streams noun object with the given element type.
1321 * Assumes that 'activity', 'georss', and 'poco' namespace has been
1322 * previously defined.
1324 * @param string $element one of 'actor', 'subject', 'object', 'target'
1328 function asActivityNoun($element)
1330 $noun = ActivityObject::fromProfile($this);
1331 return $noun->asString('activity:' . $element);
1335 * Returns the best URI for a profile. Plugins may override.
1337 * @return string $uri
1343 // give plugins a chance to set the URI
1344 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1346 // check for a local user first
1347 $user = User::getKV('id', $this->id);
1349 if (!empty($user)) {
1353 Event::handle('EndGetProfileUri', array($this, &$uri));
1359 function hasBlocked($other)
1361 $block = Profile_block::get($this->id, $other->id);
1363 if (empty($block)) {
1372 function getAtomFeed()
1376 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1377 $user = User::getKV('id', $this->id);
1378 if (!empty($user)) {
1379 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1380 'format' => 'atom'));
1382 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1388 static function fromURI($uri)
1392 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1393 // Get a local user or remote (OMB 0.1) profile
1394 $user = User::getKV('uri', $uri);
1395 if (!empty($user)) {
1396 $profile = $user->getProfile();
1398 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1404 function canRead(Notice $notice)
1406 if ($notice->scope & Notice::SITE_SCOPE) {
1407 $user = $this->getUser();
1413 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1414 $replies = $notice->getReplies();
1416 if (!in_array($this->id, $replies)) {
1417 $groups = $notice->getGroups();
1421 foreach ($groups as $group) {
1422 if ($this->isMember($group)) {
1434 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1435 $author = $notice->getProfile();
1436 if (!Subscription::exists($this, $author)) {
1444 static function current()
1446 $user = common_current_user();
1450 $profile = $user->getProfile();
1456 * Magic function called at serialize() time.
1458 * We use this to drop a couple process-specific references
1459 * from DB_DataObject which can cause trouble in future
1462 * @return array of variable names to include in serialization.
1467 $vars = parent::__sleep();
1468 $skip = array('_user', '_avatars');
1469 return array_diff($vars, $skip);
1472 static function fillAvatars(&$profiles, $width)
1475 foreach ($profiles as $profile) {
1476 if (!empty($profile)) {
1477 $ids[] = $profile->id;
1481 $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1482 'height' => $width));
1484 foreach ($profiles as $profile) {
1485 if (!empty($profile)) { // ???
1486 $profile->_fillAvatar($width, $avatars[$profile->id]);
1491 // Can't seem to find how to fix this.
1493 function getProfile()
1498 static function pivotGet($key, $values, $otherCols=array()) {
1499 return Memcached_DataObject::pivotGet('Profile', $key, $values, $otherCols);