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) {
152 function getBestName()
154 return ($this->fullname) ? $this->fullname : $this->nickname;
158 * Get the most recent notice posted by this user, if any.
160 * @return mixed Notice or null
163 function getCurrentNotice()
165 $notice = $this->getNotices(0, 1);
167 if ($notice->fetch()) {
174 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
176 $ids = Notice::stream(array($this, '_streamTaggedDirect'),
178 'profile:notice_ids_tagged:' . $this->id . ':' . $tag,
179 $offset, $limit, $since_id, $max_id);
180 return Notice::getStreamByIds($ids);
183 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
185 // XXX: I'm not sure this is going to be any faster. It probably isn't.
186 $ids = Notice::stream(array($this, '_streamDirect'),
188 'profile:notice_ids:' . $this->id,
189 $offset, $limit, $since_id, $max_id);
191 return Notice::getStreamByIds($ids);
194 function _streamTaggedDirect($tag, $offset, $limit, $since_id, $max_id)
196 // XXX It would be nice to do this without a join
198 $notice = new Notice();
201 "select id from notice join notice_tag on id=notice_id where tag='".
202 $notice->escape($tag) .
203 "' and profile_id=" . $notice->escape($this->id);
205 if ($since_id != 0) {
206 $query .= " and id > $since_id";
210 $query .= " and id <= $max_id";
213 $query .= ' order by id DESC';
215 if (!is_null($offset)) {
216 $query .= " LIMIT $limit OFFSET $offset";
219 $notice->query($query);
223 while ($notice->fetch()) {
224 $ids[] = $notice->id;
230 function _streamDirect($offset, $limit, $since_id, $max_id)
232 $notice = new Notice();
234 // Temporary hack until notice_profile_id_idx is updated
235 // to (profile_id, id) instead of (profile_id, created, id).
236 // It's been falling back to PRIMARY instead, which is really
237 // very inefficient for a profile that hasn't posted in a few
238 // months. Even though forcing the index will cause a filesort,
239 // it's usually going to be better.
240 if (common_config('db', 'type') == 'mysql') {
243 "select id from notice force index (notice_profile_id_idx) ".
244 "where profile_id=" . $notice->escape($this->id);
246 if ($since_id != 0) {
247 $query .= " and id > $since_id";
251 $query .= " and id <= $max_id";
254 $query .= ' order by id DESC';
256 if (!is_null($offset)) {
257 $query .= " LIMIT $limit OFFSET $offset";
260 $notice->query($query);
264 $notice->profile_id = $this->id;
266 $notice->selectAdd();
267 $notice->selectAdd('id');
269 if ($since_id != 0) {
270 $notice->whereAdd('id > ' . $since_id);
274 $notice->whereAdd('id <= ' . $max_id);
277 $notice->orderBy('id DESC');
279 if (!is_null($offset)) {
280 $notice->limit($offset, $limit);
288 while ($notice->fetch()) {
289 $ids[] = $notice->id;
295 function isMember($group)
297 $mem = new Group_member();
299 $mem->group_id = $group->id;
300 $mem->profile_id = $this->id;
309 function isAdmin($group)
311 $mem = new Group_member();
313 $mem->group_id = $group->id;
314 $mem->profile_id = $this->id;
324 function getGroups($offset=0, $limit=null)
327 'SELECT user_group.* ' .
328 'FROM user_group JOIN group_member '.
329 'ON user_group.id = group_member.group_id ' .
330 'WHERE group_member.profile_id = %d ' .
331 'ORDER BY group_member.created DESC ';
333 if ($offset>0 && !is_null($limit)) {
335 if (common_config('db','type') == 'pgsql') {
336 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
338 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
343 $groups = new User_group();
345 $cnt = $groups->query(sprintf($qry, $this->id));
350 function avatarUrl($size=AVATAR_PROFILE_SIZE)
352 $avatar = $this->getAvatar($size);
354 return $avatar->displayUrl();
356 return Avatar::defaultImage($size);
360 function getSubscriptions($offset=0, $limit=null)
363 'SELECT profile.* ' .
364 'FROM profile JOIN subscription ' .
365 'ON profile.id = subscription.subscribed ' .
366 'WHERE subscription.subscriber = %d ' .
367 'AND subscription.subscribed != subscription.subscriber ' .
368 'ORDER BY subscription.created DESC ';
370 if ($offset>0 && !is_null($limit)){
371 if (common_config('db','type') == 'pgsql') {
372 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
374 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
378 $profile = new Profile();
380 $profile->query(sprintf($qry, $this->id));
385 function getSubscribers($offset=0, $limit=null)
388 'SELECT profile.* ' .
389 'FROM profile JOIN subscription ' .
390 'ON profile.id = subscription.subscriber ' .
391 'WHERE subscription.subscribed = %d ' .
392 'AND subscription.subscribed != subscription.subscriber ' .
393 'ORDER BY subscription.created DESC ';
395 if ($offset>0 && !is_null($limit)){
397 if (common_config('db','type') == 'pgsql') {
398 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
400 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
405 $profile = new Profile();
407 $cnt = $profile->query(sprintf($qry, $this->id));
412 function subscriptionCount()
414 $c = common_memcache();
417 $cnt = $c->get(common_cache_key('profile:subscription_count:'.$this->id));
418 if (is_integer($cnt)) {
423 $sub = new Subscription();
424 $sub->subscriber = $this->id;
426 $cnt = (int) $sub->count('distinct subscribed');
428 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
431 $c->set(common_cache_key('profile:subscription_count:'.$this->id), $cnt);
437 function subscriberCount()
439 $c = common_memcache();
441 $cnt = $c->get(common_cache_key('profile:subscriber_count:'.$this->id));
442 if (is_integer($cnt)) {
447 $sub = new Subscription();
448 $sub->subscribed = $this->id;
449 $sub->whereAdd('subscriber != subscribed');
450 $cnt = (int) $sub->count('distinct subscriber');
453 $c->set(common_cache_key('profile:subscriber_count:'.$this->id), $cnt);
460 * Is this profile subscribed to another profile?
462 * @param Profile $other
465 function isSubscribed($other)
467 return Subscription::exists($this, $other);
471 * Are these two profiles subscribed to each other?
473 * @param Profile $other
476 function mutuallySubscribed($other)
478 return $this->isSubscribed($other) &&
479 $other->isSubscribed($this);
482 function hasFave($notice)
484 $cache = common_memcache();
486 // XXX: Kind of a hack.
488 if (!empty($cache)) {
489 // This is the stream of favorite notices, in rev chron
490 // order. This forces it into cache.
492 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
494 // If it's in the list, then it's a fave
496 if (in_array($notice->id, $ids)) {
500 // If we're not past the end of the cache window,
501 // then the cache has all available faves, so this one
504 if (count($ids) < NOTICE_CACHE_WINDOW) {
508 // Otherwise, cache doesn't have all faves;
509 // fall through to the default
512 $fave = Fave::pkeyGet(array('user_id' => $this->id,
513 'notice_id' => $notice->id));
514 return ((is_null($fave)) ? false : true);
519 $c = common_memcache();
521 $cnt = $c->get(common_cache_key('profile:fave_count:'.$this->id));
522 if (is_integer($cnt)) {
528 $faves->user_id = $this->id;
529 $cnt = (int) $faves->count('distinct notice_id');
532 $c->set(common_cache_key('profile:fave_count:'.$this->id), $cnt);
538 function noticeCount()
540 $c = common_memcache();
543 $cnt = $c->get(common_cache_key('profile:notice_count:'.$this->id));
544 if (is_integer($cnt)) {
549 $notices = new Notice();
550 $notices->profile_id = $this->id;
551 $cnt = (int) $notices->count('distinct id');
554 $c->set(common_cache_key('profile:notice_count:'.$this->id), $cnt);
560 function blowFavesCache()
562 $cache = common_memcache();
564 // Faves don't happen chronologically, so we need to blow
566 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
567 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
568 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
569 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
571 $this->blowFaveCount();
574 function blowSubscriberCount()
576 $c = common_memcache();
578 $c->delete(common_cache_key('profile:subscriber_count:'.$this->id));
582 function blowSubscriptionCount()
584 $c = common_memcache();
586 $c->delete(common_cache_key('profile:subscription_count:'.$this->id));
590 function blowFaveCount()
592 $c = common_memcache();
594 $c->delete(common_cache_key('profile:fave_count:'.$this->id));
598 function blowNoticeCount()
600 $c = common_memcache();
602 $c->delete(common_cache_key('profile:notice_count:'.$this->id));
606 static function maxBio()
608 $biolimit = common_config('profile', 'biolimit');
609 // null => use global limit (distinct from 0!)
610 if (is_null($biolimit)) {
611 $biolimit = common_config('site', 'textlimit');
616 static function bioTooLong($bio)
618 $biolimit = self::maxBio();
619 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
624 $this->_deleteNotices();
625 $this->_deleteSubscriptions();
626 $this->_deleteMessages();
627 $this->_deleteTags();
628 $this->_deleteBlocks();
629 $this->delete_avatars();
631 // Warning: delete() will run on the batch objects,
632 // not on individual objects.
633 $related = array('Reply',
636 Event::handle('ProfileDeleteRelated', array($this, &$related));
638 foreach ($related as $cls) {
640 $inst->profile_id = $this->id;
647 function _deleteNotices()
649 $notice = new Notice();
650 $notice->profile_id = $this->id;
652 if ($notice->find()) {
653 while ($notice->fetch()) {
654 $other = clone($notice);
660 function _deleteSubscriptions()
662 $sub = new Subscription();
663 $sub->subscriber = $this->id;
667 while ($sub->fetch()) {
668 $other = Profile::staticGet('id', $sub->subscribed);
672 if ($other->id == $this->id) {
675 Subscription::cancel($this, $other);
678 $subd = new Subscription();
679 $subd->subscribed = $this->id;
682 while ($subd->fetch()) {
683 $other = Profile::staticGet('id', $subd->subscriber);
687 if ($other->id == $this->id) {
690 Subscription::cancel($other, $this);
693 $self = new Subscription();
695 $self->subscriber = $this->id;
696 $self->subscribed = $this->id;
701 function _deleteMessages()
703 $msg = new Message();
704 $msg->from_profile = $this->id;
707 $msg = new Message();
708 $msg->to_profile = $this->id;
712 function _deleteTags()
714 $tag = new Profile_tag();
715 $tag->tagged = $this->id;
719 function _deleteBlocks()
721 $block = new Profile_block();
722 $block->blocked = $this->id;
725 $block = new Group_block();
726 $block->blocked = $this->id;
730 // XXX: identical to Notice::getLocation.
732 function getLocation()
736 if (!empty($this->location_id) && !empty($this->location_ns)) {
737 $location = Location::fromId($this->location_id, $this->location_ns);
740 if (is_null($location)) { // no ID, or Location::fromId() failed
741 if (!empty($this->lat) && !empty($this->lon)) {
742 $location = Location::fromLatLon($this->lat, $this->lon);
746 if (is_null($location)) { // still haven't found it!
747 if (!empty($this->location)) {
748 $location = Location::fromName($this->location);
755 function hasRole($name)
758 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
759 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
761 $has_role = !empty($role);
762 Event::handle('EndHasRole', array($this, $name, $has_role));
767 function grantRole($name)
769 if (Event::handle('StartGrantRole', array($this, $name))) {
771 $role = new Profile_role();
773 $role->profile_id = $this->id;
775 $role->created = common_sql_now();
777 $result = $role->insert();
780 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
783 Event::handle('EndGrantRole', array($this, $name));
789 function revokeRole($name)
791 if (Event::handle('StartRevokeRole', array($this, $name))) {
793 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
797 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
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; does not exist.'),$name, $this->id));
802 $result = $role->delete();
805 common_log_db_error($role, 'DELETE', __FILE__);
806 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
807 // TRANS: %1$s is the role name, %2$s is the user ID (number).
808 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
811 Event::handle('EndRevokeRole', array($this, $name));
817 function isSandboxed()
819 return $this->hasRole(Profile_role::SANDBOXED);
822 function isSilenced()
824 return $this->hasRole(Profile_role::SILENCED);
829 $this->grantRole(Profile_role::SANDBOXED);
834 $this->revokeRole(Profile_role::SANDBOXED);
839 $this->grantRole(Profile_role::SILENCED);
844 $this->revokeRole(Profile_role::SILENCED);
848 * Does this user have the right to do X?
850 * With our role-based authorization, this is merely a lookup for whether the user
851 * has a particular role. The implementation currently uses a switch statement
852 * to determine if the user has the pre-defined role to exercise the right. Future
853 * implementations may allow per-site roles, and different mappings of roles to rights.
855 * @param $right string Name of the right, usually a constant in class Right
856 * @return boolean whether the user has the right in question
858 function hasRight($right)
862 if ($this->hasRole(Profile_role::DELETED)) {
866 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
869 case Right::DELETEOTHERSNOTICE:
870 case Right::MAKEGROUPADMIN:
871 case Right::SANDBOXUSER:
872 case Right::SILENCEUSER:
873 case Right::DELETEUSER:
874 case Right::DELETEGROUP:
875 $result = $this->hasRole(Profile_role::MODERATOR);
877 case Right::CONFIGURESITE:
878 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
880 case Right::GRANTROLE:
881 case Right::REVOKEROLE:
882 $result = $this->hasRole(Profile_role::OWNER);
884 case Right::NEWNOTICE:
885 case Right::NEWMESSAGE:
886 case Right::SUBSCRIBE:
887 case Right::CREATEGROUP:
888 $result = !$this->isSilenced();
890 case Right::PUBLICNOTICE:
891 case Right::EMAILONREPLY:
892 case Right::EMAILONSUBSCRIBE:
893 case Right::EMAILONFAVE:
894 $result = !$this->isSandboxed();
904 function hasRepeated($notice_id)
906 // XXX: not really a pkey, but should work
908 $notice = Memcached_DataObject::pkeyGet('Notice',
909 array('profile_id' => $this->id,
910 'repeat_of' => $notice_id));
912 return !empty($notice);
916 * Returns an XML string fragment with limited profile information
917 * as an Atom <author> element.
919 * Assumes that Atom has been previously set up as the base namespace.
921 * @param Profile $cur the current authenticated user
925 function asAtomAuthor($cur = null)
927 $xs = new XMLStringer(true);
929 $xs->elementStart('author');
930 $xs->element('name', null, $this->nickname);
931 $xs->element('uri', null, $this->getUri());
934 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
935 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
936 $xs->element('statusnet:profile_info', $attrs, null);
938 $xs->elementEnd('author');
940 return $xs->getString();
944 * Returns an XML string fragment with profile information as an
945 * Activity Streams <activity:actor> element.
947 * Assumes that 'activity' namespace has been previously defined.
951 function asActivityActor()
953 return $this->asActivityNoun('actor');
957 * Returns an XML string fragment with profile information as an
958 * Activity Streams noun object with the given element type.
960 * Assumes that 'activity', 'georss', and 'poco' namespace has been
961 * previously defined.
963 * @param string $element one of 'actor', 'subject', 'object', 'target'
967 function asActivityNoun($element)
969 $noun = ActivityObject::fromProfile($this);
970 return $noun->asString('activity:' . $element);
974 * Returns the best URI for a profile. Plugins may override.
976 * @return string $uri
982 // give plugins a chance to set the URI
983 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
985 // check for a local user first
986 $user = User::staticGet('id', $this->id);
991 // return OMB profile if any
992 $remote = Remote_profile::staticGet('id', $this->id);
993 if (!empty($remote)) {
997 Event::handle('EndGetProfileUri', array($this, &$uri));
1003 function hasBlocked($other)
1005 $block = Profile_block::get($this->id, $other->id);
1007 if (empty($block)) {
1016 function getAtomFeed()
1020 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1021 $user = User::staticGet('id', $this->id);
1022 if (!empty($user)) {
1023 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1024 'format' => 'atom'));
1026 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1032 static function fromURI($uri)
1036 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1037 // Get a local user or remote (OMB 0.1) profile
1038 $user = User::staticGet('uri', $uri);
1039 if (!empty($user)) {
1040 $profile = $user->getProfile();
1042 $remote_profile = Remote_profile::staticGet('uri', $uri);
1043 if (!empty($remote_profile)) {
1044 $profile = Profile::staticGet('id', $remote_profile->profile_id);
1047 Event::handle('EndGetProfileFromURI', array($uri, $profile));