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 followed by nickname in parens
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
184 function getCurrentNotice()
186 $notice = $this->getNotices(0, 1);
188 if ($notice->fetch()) {
195 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
197 $ids = Notice::stream(array($this, '_streamTaggedDirect'),
199 'profile:notice_ids_tagged:' . $this->id . ':' . $tag,
200 $offset, $limit, $since_id, $max_id);
201 return Notice::getStreamByIds($ids);
204 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
206 // XXX: I'm not sure this is going to be any faster. It probably isn't.
207 $ids = Notice::stream(array($this, '_streamDirect'),
209 'profile:notice_ids:' . $this->id,
210 $offset, $limit, $since_id, $max_id);
212 return Notice::getStreamByIds($ids);
215 function _streamTaggedDirect($tag, $offset, $limit, $since_id, $max_id)
217 // XXX It would be nice to do this without a join
219 $notice = new Notice();
222 "select id from notice join notice_tag on id=notice_id where tag='".
223 $notice->escape($tag) .
224 "' and profile_id=" . $notice->escape($this->id);
226 if ($since_id != 0) {
227 $query .= " and id > $since_id";
231 $query .= " and id <= $max_id";
234 $query .= ' order by id DESC';
236 if (!is_null($offset)) {
237 $query .= " LIMIT $limit OFFSET $offset";
240 $notice->query($query);
244 while ($notice->fetch()) {
245 $ids[] = $notice->id;
251 function _streamDirect($offset, $limit, $since_id, $max_id)
253 $notice = new Notice();
255 // Temporary hack until notice_profile_id_idx is updated
256 // to (profile_id, id) instead of (profile_id, created, id).
257 // It's been falling back to PRIMARY instead, which is really
258 // very inefficient for a profile that hasn't posted in a few
259 // months. Even though forcing the index will cause a filesort,
260 // it's usually going to be better.
261 if (common_config('db', 'type') == 'mysql') {
264 "select id from notice force index (notice_profile_id_idx) ".
265 "where profile_id=" . $notice->escape($this->id);
267 if ($since_id != 0) {
268 $query .= " and id > $since_id";
272 $query .= " and id <= $max_id";
275 $query .= ' order by id DESC';
277 if (!is_null($offset)) {
278 $query .= " LIMIT $limit OFFSET $offset";
281 $notice->query($query);
285 $notice->profile_id = $this->id;
287 $notice->selectAdd();
288 $notice->selectAdd('id');
290 if ($since_id != 0) {
291 $notice->whereAdd('id > ' . $since_id);
295 $notice->whereAdd('id <= ' . $max_id);
298 $notice->orderBy('id DESC');
300 if (!is_null($offset)) {
301 $notice->limit($offset, $limit);
309 while ($notice->fetch()) {
310 $ids[] = $notice->id;
316 function isMember($group)
318 $mem = new Group_member();
320 $mem->group_id = $group->id;
321 $mem->profile_id = $this->id;
330 function isAdmin($group)
332 $mem = new Group_member();
334 $mem->group_id = $group->id;
335 $mem->profile_id = $this->id;
345 function getGroups($offset=0, $limit=null)
348 'SELECT user_group.* ' .
349 'FROM user_group JOIN group_member '.
350 'ON user_group.id = group_member.group_id ' .
351 'WHERE group_member.profile_id = %d ' .
352 'ORDER BY group_member.created DESC ';
354 if ($offset>0 && !is_null($limit)) {
356 if (common_config('db','type') == 'pgsql') {
357 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
359 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
364 $groups = new User_group();
366 $cnt = $groups->query(sprintf($qry, $this->id));
371 function avatarUrl($size=AVATAR_PROFILE_SIZE)
373 $avatar = $this->getAvatar($size);
375 return $avatar->displayUrl();
377 return Avatar::defaultImage($size);
381 function getSubscriptions($offset=0, $limit=null)
383 $subs = Subscription::bySubscriber($this->id,
389 while ($subs->fetch()) {
390 $profiles[] = Profile::staticGet($subs->subscribed);
393 return new ArrayWrapper($profiles);
396 function getSubscribers($offset=0, $limit=null)
398 $subs = Subscription::bySubscribed($this->id,
404 while ($subs->fetch()) {
405 $profiles[] = Profile::staticGet($subs->subscriber);
408 return new ArrayWrapper($profiles);
411 function subscriptionCount()
413 $c = common_memcache();
416 $cnt = $c->get(common_cache_key('profile:subscription_count:'.$this->id));
417 if (is_integer($cnt)) {
422 $sub = new Subscription();
423 $sub->subscriber = $this->id;
425 $cnt = (int) $sub->count('distinct subscribed');
427 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
430 $c->set(common_cache_key('profile:subscription_count:'.$this->id), $cnt);
436 function subscriberCount()
438 $c = common_memcache();
440 $cnt = $c->get(common_cache_key('profile:subscriber_count:'.$this->id));
441 if (is_integer($cnt)) {
446 $sub = new Subscription();
447 $sub->subscribed = $this->id;
448 $sub->whereAdd('subscriber != subscribed');
449 $cnt = (int) $sub->count('distinct subscriber');
452 $c->set(common_cache_key('profile:subscriber_count:'.$this->id), $cnt);
459 * Is this profile subscribed to another profile?
461 * @param Profile $other
464 function isSubscribed($other)
466 return Subscription::exists($this, $other);
470 * Are these two profiles subscribed to each other?
472 * @param Profile $other
475 function mutuallySubscribed($other)
477 return $this->isSubscribed($other) &&
478 $other->isSubscribed($this);
481 function hasFave($notice)
483 $cache = common_memcache();
485 // XXX: Kind of a hack.
487 if (!empty($cache)) {
488 // This is the stream of favorite notices, in rev chron
489 // order. This forces it into cache.
491 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
493 // If it's in the list, then it's a fave
495 if (in_array($notice->id, $ids)) {
499 // If we're not past the end of the cache window,
500 // then the cache has all available faves, so this one
503 if (count($ids) < NOTICE_CACHE_WINDOW) {
507 // Otherwise, cache doesn't have all faves;
508 // fall through to the default
511 $fave = Fave::pkeyGet(array('user_id' => $this->id,
512 'notice_id' => $notice->id));
513 return ((is_null($fave)) ? false : true);
518 $c = common_memcache();
520 $cnt = $c->get(common_cache_key('profile:fave_count:'.$this->id));
521 if (is_integer($cnt)) {
527 $faves->user_id = $this->id;
528 $cnt = (int) $faves->count('distinct notice_id');
531 $c->set(common_cache_key('profile:fave_count:'.$this->id), $cnt);
537 function noticeCount()
539 $c = common_memcache();
542 $cnt = $c->get(common_cache_key('profile:notice_count:'.$this->id));
543 if (is_integer($cnt)) {
548 $notices = new Notice();
549 $notices->profile_id = $this->id;
550 $cnt = (int) $notices->count('distinct id');
553 $c->set(common_cache_key('profile:notice_count:'.$this->id), $cnt);
559 function blowFavesCache()
561 $cache = common_memcache();
563 // Faves don't happen chronologically, so we need to blow
565 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
566 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
567 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
568 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
570 $this->blowFaveCount();
573 function blowSubscriberCount()
575 $c = common_memcache();
577 $c->delete(common_cache_key('profile:subscriber_count:'.$this->id));
581 function blowSubscriptionCount()
583 $c = common_memcache();
585 $c->delete(common_cache_key('profile:subscription_count:'.$this->id));
589 function blowFaveCount()
591 $c = common_memcache();
593 $c->delete(common_cache_key('profile:fave_count:'.$this->id));
597 function blowNoticeCount()
599 $c = common_memcache();
601 $c->delete(common_cache_key('profile:notice_count:'.$this->id));
605 static function maxBio()
607 $biolimit = common_config('profile', 'biolimit');
608 // null => use global limit (distinct from 0!)
609 if (is_null($biolimit)) {
610 $biolimit = common_config('site', 'textlimit');
615 static function bioTooLong($bio)
617 $biolimit = self::maxBio();
618 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
623 $this->_deleteNotices();
624 $this->_deleteSubscriptions();
625 $this->_deleteMessages();
626 $this->_deleteTags();
627 $this->_deleteBlocks();
628 $this->delete_avatars();
630 // Warning: delete() will run on the batch objects,
631 // not on individual objects.
632 $related = array('Reply',
635 Event::handle('ProfileDeleteRelated', array($this, &$related));
637 foreach ($related as $cls) {
639 $inst->profile_id = $this->id;
646 function _deleteNotices()
648 $notice = new Notice();
649 $notice->profile_id = $this->id;
651 if ($notice->find()) {
652 while ($notice->fetch()) {
653 $other = clone($notice);
659 function _deleteSubscriptions()
661 $sub = new Subscription();
662 $sub->subscriber = $this->id;
666 while ($sub->fetch()) {
667 $other = Profile::staticGet('id', $sub->subscribed);
671 if ($other->id == $this->id) {
674 Subscription::cancel($this, $other);
677 $subd = new Subscription();
678 $subd->subscribed = $this->id;
681 while ($subd->fetch()) {
682 $other = Profile::staticGet('id', $subd->subscriber);
686 if ($other->id == $this->id) {
689 Subscription::cancel($other, $this);
692 $self = new Subscription();
694 $self->subscriber = $this->id;
695 $self->subscribed = $this->id;
700 function _deleteMessages()
702 $msg = new Message();
703 $msg->from_profile = $this->id;
706 $msg = new Message();
707 $msg->to_profile = $this->id;
711 function _deleteTags()
713 $tag = new Profile_tag();
714 $tag->tagged = $this->id;
718 function _deleteBlocks()
720 $block = new Profile_block();
721 $block->blocked = $this->id;
724 $block = new Group_block();
725 $block->blocked = $this->id;
729 // XXX: identical to Notice::getLocation.
731 function getLocation()
735 if (!empty($this->location_id) && !empty($this->location_ns)) {
736 $location = Location::fromId($this->location_id, $this->location_ns);
739 if (is_null($location)) { // no ID, or Location::fromId() failed
740 if (!empty($this->lat) && !empty($this->lon)) {
741 $location = Location::fromLatLon($this->lat, $this->lon);
745 if (is_null($location)) { // still haven't found it!
746 if (!empty($this->location)) {
747 $location = Location::fromName($this->location);
754 function hasRole($name)
757 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
758 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
760 $has_role = !empty($role);
761 Event::handle('EndHasRole', array($this, $name, $has_role));
766 function grantRole($name)
768 if (Event::handle('StartGrantRole', array($this, $name))) {
770 $role = new Profile_role();
772 $role->profile_id = $this->id;
774 $role->created = common_sql_now();
776 $result = $role->insert();
779 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
782 Event::handle('EndGrantRole', array($this, $name));
788 function revokeRole($name)
790 if (Event::handle('StartRevokeRole', array($this, $name))) {
792 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
796 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
797 // TRANS: %1$s is the role name, %2$s is the user ID (number).
798 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
801 $result = $role->delete();
804 common_log_db_error($role, 'DELETE', __FILE__);
805 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
806 // TRANS: %1$s is the role name, %2$s is the user ID (number).
807 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
810 Event::handle('EndRevokeRole', array($this, $name));
816 function isSandboxed()
818 return $this->hasRole(Profile_role::SANDBOXED);
821 function isSilenced()
823 return $this->hasRole(Profile_role::SILENCED);
828 $this->grantRole(Profile_role::SANDBOXED);
833 $this->revokeRole(Profile_role::SANDBOXED);
838 $this->grantRole(Profile_role::SILENCED);
843 $this->revokeRole(Profile_role::SILENCED);
847 * Does this user have the right to do X?
849 * With our role-based authorization, this is merely a lookup for whether the user
850 * has a particular role. The implementation currently uses a switch statement
851 * to determine if the user has the pre-defined role to exercise the right. Future
852 * implementations may allow per-site roles, and different mappings of roles to rights.
854 * @param $right string Name of the right, usually a constant in class Right
855 * @return boolean whether the user has the right in question
857 function hasRight($right)
861 if ($this->hasRole(Profile_role::DELETED)) {
865 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
868 case Right::DELETEOTHERSNOTICE:
869 case Right::MAKEGROUPADMIN:
870 case Right::SANDBOXUSER:
871 case Right::SILENCEUSER:
872 case Right::DELETEUSER:
873 case Right::DELETEGROUP:
874 $result = $this->hasRole(Profile_role::MODERATOR);
876 case Right::CONFIGURESITE:
877 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
879 case Right::GRANTROLE:
880 case Right::REVOKEROLE:
881 $result = $this->hasRole(Profile_role::OWNER);
883 case Right::NEWNOTICE:
884 case Right::NEWMESSAGE:
885 case Right::SUBSCRIBE:
886 $result = !$this->isSilenced();
888 case Right::PUBLICNOTICE:
889 case Right::EMAILONREPLY:
890 case Right::EMAILONSUBSCRIBE:
891 case Right::EMAILONFAVE:
892 $result = !$this->isSandboxed();
894 case Right::BACKUPACCOUNT:
895 $result = common_config('profile', 'backup');
897 case Right::RESTOREACCOUNT:
898 $result = common_config('profile', 'restore');
900 case Right::DELETEACCOUNT:
901 $result = common_config('profile', 'delete');
903 case Right::MOVEACCOUNT:
904 $result = common_config('profile', 'move');
914 function hasRepeated($notice_id)
916 // XXX: not really a pkey, but should work
918 $notice = Memcached_DataObject::pkeyGet('Notice',
919 array('profile_id' => $this->id,
920 'repeat_of' => $notice_id));
922 return !empty($notice);
926 * Returns an XML string fragment with limited profile information
927 * as an Atom <author> element.
929 * Assumes that Atom has been previously set up as the base namespace.
931 * @param Profile $cur the current authenticated user
935 function asAtomAuthor($cur = null)
937 $xs = new XMLStringer(true);
939 $xs->elementStart('author');
940 $xs->element('name', null, $this->nickname);
941 $xs->element('uri', null, $this->getUri());
944 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
945 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
946 $xs->element('statusnet:profile_info', $attrs, null);
948 $xs->elementEnd('author');
950 return $xs->getString();
954 * Returns an XML string fragment with profile information as an
955 * Activity Streams <activity:actor> element.
957 * Assumes that 'activity' namespace has been previously defined.
961 function asActivityActor()
963 return $this->asActivityNoun('actor');
967 * Returns an XML string fragment with profile information as an
968 * Activity Streams noun object with the given element type.
970 * Assumes that 'activity', 'georss', and 'poco' namespace has been
971 * previously defined.
973 * @param string $element one of 'actor', 'subject', 'object', 'target'
977 function asActivityNoun($element)
979 $noun = ActivityObject::fromProfile($this);
980 return $noun->asString('activity:' . $element);
984 * Returns the best URI for a profile. Plugins may override.
986 * @return string $uri
992 // give plugins a chance to set the URI
993 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
995 // check for a local user first
996 $user = User::staticGet('id', $this->id);
1001 // return OMB profile if any
1002 $remote = Remote_profile::staticGet('id', $this->id);
1003 if (!empty($remote)) {
1004 $uri = $remote->uri;
1007 Event::handle('EndGetProfileUri', array($this, &$uri));
1013 function hasBlocked($other)
1015 $block = Profile_block::get($this->id, $other->id);
1017 if (empty($block)) {
1026 function getAtomFeed()
1030 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1031 $user = User::staticGet('id', $this->id);
1032 if (!empty($user)) {
1033 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1034 'format' => 'atom'));
1036 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1042 static function fromURI($uri)
1046 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1047 // Get a local user or remote (OMB 0.1) profile
1048 $user = User::staticGet('uri', $uri);
1049 if (!empty($user)) {
1050 $profile = $user->getProfile();
1052 $remote_profile = Remote_profile::staticGet('uri', $uri);
1053 if (!empty($remote_profile)) {
1054 $profile = Profile::staticGet('id', $remote_profile->profile_id);
1057 Event::handle('EndGetProfileFromURI', array($uri, $profile));