3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, 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 Memcached_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
48 function staticGet($k,$v=NULL) {
49 return Memcached_DataObject::staticGet('Profile',$k,$v);
52 /* the code above is auto generated do not remove the tag below */
57 return User::staticGet('id', $this->id);
60 function getAvatar($width, $height=null)
62 if (is_null($height)) {
65 return Avatar::pkeyGet(array('profile_id' => $this->id,
67 'height' => $height));
70 function getOriginalAvatar()
72 $avatar = DB_DataObject::factory('avatar');
73 $avatar->profile_id = $this->id;
74 $avatar->original = true;
75 if ($avatar->find(true)) {
82 function setOriginal($filename)
84 $imagefile = new ImageFile($this->id, Avatar::path($filename));
86 $avatar = new Avatar();
87 $avatar->profile_id = $this->id;
88 $avatar->width = $imagefile->width;
89 $avatar->height = $imagefile->height;
90 $avatar->mediatype = image_type_to_mime_type($imagefile->type);
91 $avatar->filename = $filename;
92 $avatar->original = true;
93 $avatar->url = Avatar::url($filename);
94 $avatar->created = DB_DataObject_Cast::dateTime(); # current time
96 // XXX: start a transaction here
98 if (!$this->delete_avatars() || !$avatar->insert()) {
99 @unlink(Avatar::path($filename));
103 foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
104 // We don't do a scaled one if original is our scaled size
105 if (!($avatar->width == $size && $avatar->height == $size)) {
106 $scaled_filename = $imagefile->resize($size);
108 //$scaled = DB_DataObject::factory('avatar');
109 $scaled = new Avatar();
110 $scaled->profile_id = $this->id;
111 $scaled->width = $size;
112 $scaled->height = $size;
113 $scaled->original = false;
114 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
115 $scaled->filename = $scaled_filename;
116 $scaled->url = Avatar::url($scaled_filename);
117 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
119 if (!$scaled->insert()) {
129 * Delete attached avatars for this user from the database and filesystem.
130 * This should be used instead of a batch delete() to ensure that files
131 * get removed correctly.
133 * @param boolean $original true to delete only the original-size file
136 function delete_avatars($original=true)
138 $avatar = new Avatar();
139 $avatar->profile_id = $this->id;
141 while ($avatar->fetch()) {
142 if ($avatar->original) {
143 if ($original == false) {
153 * Gets either the full name (if filled) or the nickname.
157 function getBestName()
159 return ($this->fullname) ? $this->fullname : $this->nickname;
163 * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
164 * if no fullname is provided.
168 function getFancyName()
170 if ($this->fullname) {
171 // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
172 return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
174 return $this->nickname;
179 * Get the most recent notice posted by this user, if any.
181 * @return mixed Notice or null
183 function getCurrentNotice()
185 $notice = $this->getNotices(0, 1);
187 if ($notice->fetch()) {
188 if ($notice instanceof ArrayWrapper) {
189 // hack for things trying to work with single notices
190 return $notice->_items[0];
198 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
200 $stream = new TaggedProfileNoticeStream($this, $tag);
202 return $stream->getNotices($offset, $limit, $since_id, $max_id);
205 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
207 $stream = new ProfileNoticeStream($this);
209 return $stream->getNotices($offset, $limit, $since_id, $max_id);
212 function isMember($group)
214 $mem = new Group_member();
216 $mem->group_id = $group->id;
217 $mem->profile_id = $this->id;
226 function isAdmin($group)
228 $mem = new Group_member();
230 $mem->group_id = $group->id;
231 $mem->profile_id = $this->id;
241 function isPendingMember($group)
243 $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
244 'group_id' => $group->id));
245 return !empty($request);
248 function getGroups($offset=0, $limit=null)
251 'SELECT user_group.* ' .
252 'FROM user_group JOIN group_member '.
253 'ON user_group.id = group_member.group_id ' .
254 'WHERE group_member.profile_id = %d ' .
255 'ORDER BY group_member.created DESC ';
257 if ($offset>0 && !is_null($limit)) {
259 if (common_config('db','type') == 'pgsql') {
260 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
262 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
267 $groups = new User_group();
269 $cnt = $groups->query(sprintf($qry, $this->id));
275 * Request to join the given group.
276 * May throw exceptions on failure.
278 * @param User_group $group
279 * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
281 function joinGroup(User_group $group)
284 if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
285 $join = Group_join_queue::saveNew($this, $group);
287 if (Event::handle('StartJoinGroup', array($group, $this))) {
288 $join = Group_member::join($group->id, $this->id);
289 Event::handle('EndJoinGroup', array($group, $this));
293 // Send any applicable notifications...
300 * Leave a group that this profile is a member of.
302 * @param User_group $group
304 function leaveGroup(User_group $group)
306 if (Event::handle('StartLeaveGroup', array($group, $this))) {
307 Group_member::leave($group->id, $this->id);
308 Event::handle('EndLeaveGroup', array($group, $this));
312 function avatarUrl($size=AVATAR_PROFILE_SIZE)
314 $avatar = $this->getAvatar($size);
316 return $avatar->displayUrl();
318 return Avatar::defaultImage($size);
322 function getSubscriptions($offset=0, $limit=null)
324 $subs = Subscription::bySubscriber($this->id,
330 while ($subs->fetch()) {
331 $profile = Profile::staticGet($subs->subscribed);
333 $profiles[] = $profile;
337 return new ArrayWrapper($profiles);
340 function getSubscribers($offset=0, $limit=null)
342 $subs = Subscription::bySubscribed($this->id,
348 while ($subs->fetch()) {
349 $profile = Profile::staticGet($subs->subscriber);
351 $profiles[] = $profile;
355 return new ArrayWrapper($profiles);
359 * Get pending subscribers, who have not yet been approved.
365 function getRequests($offset=0, $limit=null)
368 'SELECT profile.* ' .
369 'FROM profile JOIN subscription_queue '.
370 'ON profile.id = subscription_queue.subscriber ' .
371 'WHERE subscription_queue.subscribed = %d ' .
372 'ORDER BY subscription_queue.created DESC ';
374 if ($limit != null) {
375 if (common_config('db','type') == 'pgsql') {
376 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
378 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
382 $members = new Profile();
384 $members->query(sprintf($qry, $this->id));
388 function subscriptionCount()
390 $c = Cache::instance();
393 $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
394 if (is_integer($cnt)) {
399 $sub = new Subscription();
400 $sub->subscriber = $this->id;
402 $cnt = (int) $sub->count('distinct subscribed');
404 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
407 $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
413 function subscriberCount()
415 $c = Cache::instance();
417 $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
418 if (is_integer($cnt)) {
423 $sub = new Subscription();
424 $sub->subscribed = $this->id;
425 $sub->whereAdd('subscriber != subscribed');
426 $cnt = (int) $sub->count('distinct subscriber');
429 $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
436 * Is this profile subscribed to another profile?
438 * @param Profile $other
441 function isSubscribed($other)
443 return Subscription::exists($this, $other);
447 * Check if a pending subscription request is outstanding for this...
449 * @param Profile $other
452 function hasPendingSubscription($other)
454 return Subscription_queue::exists($this, $other);
458 * Are these two profiles subscribed to each other?
460 * @param Profile $other
463 function mutuallySubscribed($other)
465 return $this->isSubscribed($other) &&
466 $other->isSubscribed($this);
469 function hasFave($notice)
471 $cache = Cache::instance();
473 // XXX: Kind of a hack.
475 if (!empty($cache)) {
476 // This is the stream of favorite notices, in rev chron
477 // order. This forces it into cache.
479 $ids = Fave::idStream($this->id, 0, CachingNoticeStream::CACHE_WINDOW);
481 // If it's in the list, then it's a fave
483 if (in_array($notice->id, $ids)) {
487 // If we're not past the end of the cache window,
488 // then the cache has all available faves, so this one
491 if (count($ids) < CachingNoticeStream::CACHE_WINDOW) {
495 // Otherwise, cache doesn't have all faves;
496 // fall through to the default
499 $fave = Fave::pkeyGet(array('user_id' => $this->id,
500 'notice_id' => $notice->id));
501 return ((is_null($fave)) ? false : true);
506 $c = Cache::instance();
508 $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
509 if (is_integer($cnt)) {
515 $faves->user_id = $this->id;
516 $cnt = (int) $faves->count('distinct notice_id');
519 $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
525 function noticeCount()
527 $c = Cache::instance();
530 $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
531 if (is_integer($cnt)) {
536 $notices = new Notice();
537 $notices->profile_id = $this->id;
538 $cnt = (int) $notices->count('distinct id');
541 $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
547 function blowFavesCache()
549 $cache = Cache::instance();
551 // Faves don't happen chronologically, so we need to blow
553 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
554 $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
555 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
556 $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
558 $this->blowFaveCount();
561 function blowSubscriberCount()
563 $c = Cache::instance();
565 $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
569 function blowSubscriptionCount()
571 $c = Cache::instance();
573 $c->delete(Cache::key('profile:subscription_count:'.$this->id));
577 function blowFaveCount()
579 $c = Cache::instance();
581 $c->delete(Cache::key('profile:fave_count:'.$this->id));
585 function blowNoticeCount()
587 $c = Cache::instance();
589 $c->delete(Cache::key('profile:notice_count:'.$this->id));
593 static function maxBio()
595 $biolimit = common_config('profile', 'biolimit');
596 // null => use global limit (distinct from 0!)
597 if (is_null($biolimit)) {
598 $biolimit = common_config('site', 'textlimit');
603 static function bioTooLong($bio)
605 $biolimit = self::maxBio();
606 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
611 $this->_deleteNotices();
612 $this->_deleteSubscriptions();
613 $this->_deleteMessages();
614 $this->_deleteTags();
615 $this->_deleteBlocks();
616 $this->delete_avatars();
618 // Warning: delete() will run on the batch objects,
619 // not on individual objects.
620 $related = array('Reply',
623 Event::handle('ProfileDeleteRelated', array($this, &$related));
625 foreach ($related as $cls) {
627 $inst->profile_id = $this->id;
634 function _deleteNotices()
636 $notice = new Notice();
637 $notice->profile_id = $this->id;
639 if ($notice->find()) {
640 while ($notice->fetch()) {
641 $other = clone($notice);
647 function _deleteSubscriptions()
649 $sub = new Subscription();
650 $sub->subscriber = $this->id;
654 while ($sub->fetch()) {
655 $other = Profile::staticGet('id', $sub->subscribed);
659 if ($other->id == $this->id) {
662 Subscription::cancel($this, $other);
665 $subd = new Subscription();
666 $subd->subscribed = $this->id;
669 while ($subd->fetch()) {
670 $other = Profile::staticGet('id', $subd->subscriber);
674 if ($other->id == $this->id) {
677 Subscription::cancel($other, $this);
680 $self = new Subscription();
682 $self->subscriber = $this->id;
683 $self->subscribed = $this->id;
688 function _deleteMessages()
690 $msg = new Message();
691 $msg->from_profile = $this->id;
694 $msg = new Message();
695 $msg->to_profile = $this->id;
699 function _deleteTags()
701 $tag = new Profile_tag();
702 $tag->tagged = $this->id;
706 function _deleteBlocks()
708 $block = new Profile_block();
709 $block->blocked = $this->id;
712 $block = new Group_block();
713 $block->blocked = $this->id;
717 // XXX: identical to Notice::getLocation.
719 function getLocation()
723 if (!empty($this->location_id) && !empty($this->location_ns)) {
724 $location = Location::fromId($this->location_id, $this->location_ns);
727 if (is_null($location)) { // no ID, or Location::fromId() failed
728 if (!empty($this->lat) && !empty($this->lon)) {
729 $location = Location::fromLatLon($this->lat, $this->lon);
733 if (is_null($location)) { // still haven't found it!
734 if (!empty($this->location)) {
735 $location = Location::fromName($this->location);
742 function hasRole($name)
745 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
746 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
748 $has_role = !empty($role);
749 Event::handle('EndHasRole', array($this, $name, $has_role));
754 function grantRole($name)
756 if (Event::handle('StartGrantRole', array($this, $name))) {
758 $role = new Profile_role();
760 $role->profile_id = $this->id;
762 $role->created = common_sql_now();
764 $result = $role->insert();
767 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
770 if ($name == 'owner') {
771 User::blow('user:site_owner');
774 Event::handle('EndGrantRole', array($this, $name));
780 function revokeRole($name)
782 if (Event::handle('StartRevokeRole', array($this, $name))) {
784 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
788 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
789 // TRANS: %1$s is the role name, %2$s is the user ID (number).
790 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
793 $result = $role->delete();
796 common_log_db_error($role, 'DELETE', __FILE__);
797 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
798 // TRANS: %1$s is the role name, %2$s is the user ID (number).
799 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
802 if ($name == 'owner') {
803 User::blow('user:site_owner');
806 Event::handle('EndRevokeRole', array($this, $name));
812 function isSandboxed()
814 return $this->hasRole(Profile_role::SANDBOXED);
817 function isSilenced()
819 return $this->hasRole(Profile_role::SILENCED);
824 $this->grantRole(Profile_role::SANDBOXED);
829 $this->revokeRole(Profile_role::SANDBOXED);
834 $this->grantRole(Profile_role::SILENCED);
839 $this->revokeRole(Profile_role::SILENCED);
843 * Does this user have the right to do X?
845 * With our role-based authorization, this is merely a lookup for whether the user
846 * has a particular role. The implementation currently uses a switch statement
847 * to determine if the user has the pre-defined role to exercise the right. Future
848 * implementations may allow per-site roles, and different mappings of roles to rights.
850 * @param $right string Name of the right, usually a constant in class Right
851 * @return boolean whether the user has the right in question
853 function hasRight($right)
857 if ($this->hasRole(Profile_role::DELETED)) {
861 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
864 case Right::DELETEOTHERSNOTICE:
865 case Right::MAKEGROUPADMIN:
866 case Right::SANDBOXUSER:
867 case Right::SILENCEUSER:
868 case Right::DELETEUSER:
869 case Right::DELETEGROUP:
870 $result = $this->hasRole(Profile_role::MODERATOR);
872 case Right::CONFIGURESITE:
873 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
875 case Right::GRANTROLE:
876 case Right::REVOKEROLE:
877 $result = $this->hasRole(Profile_role::OWNER);
879 case Right::NEWNOTICE:
880 case Right::NEWMESSAGE:
881 case Right::SUBSCRIBE:
882 case Right::CREATEGROUP:
883 $result = !$this->isSilenced();
885 case Right::PUBLICNOTICE:
886 case Right::EMAILONREPLY:
887 case Right::EMAILONSUBSCRIBE:
888 case Right::EMAILONFAVE:
889 $result = !$this->isSandboxed();
891 case Right::WEBLOGIN:
892 $result = !$this->isSilenced();
895 $result = !$this->isSilenced();
897 case Right::BACKUPACCOUNT:
898 $result = common_config('profile', 'backup');
900 case Right::RESTOREACCOUNT:
901 $result = common_config('profile', 'restore');
903 case Right::DELETEACCOUNT:
904 $result = common_config('profile', 'delete');
906 case Right::MOVEACCOUNT:
907 $result = common_config('profile', 'move');
917 function hasRepeated($notice_id)
919 // XXX: not really a pkey, but should work
921 $notice = Memcached_DataObject::pkeyGet('Notice',
922 array('profile_id' => $this->id,
923 'repeat_of' => $notice_id));
925 return !empty($notice);
929 * Returns an XML string fragment with limited profile information
930 * as an Atom <author> element.
932 * Assumes that Atom has been previously set up as the base namespace.
934 * @param Profile $cur the current authenticated user
938 function asAtomAuthor($cur = null)
940 $xs = new XMLStringer(true);
942 $xs->elementStart('author');
943 $xs->element('name', null, $this->nickname);
944 $xs->element('uri', null, $this->getUri());
947 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
948 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
949 $xs->element('statusnet:profile_info', $attrs, null);
951 $xs->elementEnd('author');
953 return $xs->getString();
957 * Extra profile info for atom entries
959 * Clients use some extra profile info in the atom stream.
960 * This gives it to them.
962 * @param User $cur Current user
964 * @return array representation of <statusnet:profile_info> element or null
967 function profileInfo($cur)
969 $profileInfoAttr = array('local_id' => $this->id);
972 // Whether the current user is a subscribed to this profile
973 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
974 // Whether the current user is has blocked this profile
975 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
978 return array('statusnet:profile_info', $profileInfoAttr, null);
982 * Returns an XML string fragment with profile information as an
983 * Activity Streams <activity:actor> element.
985 * Assumes that 'activity' namespace has been previously defined.
989 function asActivityActor()
991 return $this->asActivityNoun('actor');
995 * Returns an XML string fragment with profile information as an
996 * Activity Streams noun object with the given element type.
998 * Assumes that 'activity', 'georss', and 'poco' namespace has been
999 * previously defined.
1001 * @param string $element one of 'actor', 'subject', 'object', 'target'
1005 function asActivityNoun($element)
1007 $noun = ActivityObject::fromProfile($this);
1008 return $noun->asString('activity:' . $element);
1012 * Returns the best URI for a profile. Plugins may override.
1014 * @return string $uri
1020 // give plugins a chance to set the URI
1021 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1023 // check for a local user first
1024 $user = User::staticGet('id', $this->id);
1026 if (!empty($user)) {
1029 // return OMB profile if any
1030 $remote = Remote_profile::staticGet('id', $this->id);
1031 if (!empty($remote)) {
1032 $uri = $remote->uri;
1035 Event::handle('EndGetProfileUri', array($this, &$uri));
1041 function hasBlocked($other)
1043 $block = Profile_block::get($this->id, $other->id);
1045 if (empty($block)) {
1054 function getAtomFeed()
1058 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1059 $user = User::staticGet('id', $this->id);
1060 if (!empty($user)) {
1061 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1062 'format' => 'atom'));
1064 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1070 static function fromURI($uri)
1074 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1075 // Get a local user or remote (OMB 0.1) profile
1076 $user = User::staticGet('uri', $uri);
1077 if (!empty($user)) {
1078 $profile = $user->getProfile();
1080 $remote_profile = Remote_profile::staticGet('uri', $uri);
1081 if (!empty($remote_profile)) {
1082 $profile = Profile::staticGet('id', $remote_profile->profile_id);
1085 Event::handle('EndGetProfileFromURI', array($uri, $profile));
1091 function canRead(Notice $notice)
1093 if ($notice->scope & Notice::SITE_SCOPE) {
1094 $user = $this->getUser();
1100 if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1101 $replies = $notice->getReplies();
1103 if (!in_array($this->id, $replies)) {
1104 $groups = $notice->getGroups();
1108 foreach ($groups as $group) {
1109 if ($this->isMember($group)) {
1121 if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1122 $author = $notice->getProfile();
1123 if (!Subscription::exists($this, $author)) {