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
218 // (necessary to do it efficiently on accounts with long history)
220 $notice = new Notice();
223 "select id from notice join notice_tag on id=notice_id where tag='".
224 $notice->escape($tag) .
225 "' and profile_id=" . intval($this->id);
227 $since = Notice::whereSinceId($since_id, 'id', 'notice.created');
229 $query .= " and ($since)";
232 $max = Notice::whereMaxId($max_id, 'id', 'notice.created');
234 $query .= " and ($max)";
237 $query .= ' order by notice.created DESC, id DESC';
239 if (!is_null($offset)) {
240 $query .= " LIMIT " . intval($limit) . " OFFSET " . intval($offset);
243 $notice->query($query);
247 while ($notice->fetch()) {
248 $ids[] = $notice->id;
254 function _streamDirect($offset, $limit, $since_id, $max_id)
256 $notice = new Notice();
258 $notice->profile_id = $this->id;
260 $notice->selectAdd();
261 $notice->selectAdd('id');
263 Notice::addWhereSinceId($notice, $since_id);
264 Notice::addWhereMaxId($notice, $max_id);
266 $notice->orderBy('created DESC, id DESC');
268 if (!is_null($offset)) {
269 $notice->limit($offset, $limit);
276 while ($notice->fetch()) {
277 $ids[] = $notice->id;
283 function isMember($group)
285 $mem = new Group_member();
287 $mem->group_id = $group->id;
288 $mem->profile_id = $this->id;
297 function isAdmin($group)
299 $mem = new Group_member();
301 $mem->group_id = $group->id;
302 $mem->profile_id = $this->id;
312 function getGroups($offset=0, $limit=null)
315 'SELECT user_group.* ' .
316 'FROM user_group JOIN group_member '.
317 'ON user_group.id = group_member.group_id ' .
318 'WHERE group_member.profile_id = %d ' .
319 'ORDER BY group_member.created DESC ';
321 if ($offset>0 && !is_null($limit)) {
323 if (common_config('db','type') == 'pgsql') {
324 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
326 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
331 $groups = new User_group();
333 $cnt = $groups->query(sprintf($qry, $this->id));
338 function avatarUrl($size=AVATAR_PROFILE_SIZE)
340 $avatar = $this->getAvatar($size);
342 return $avatar->displayUrl();
344 return Avatar::defaultImage($size);
348 function getSubscriptions($offset=0, $limit=null)
350 $subs = Subscription::bySubscriber($this->id,
356 while ($subs->fetch()) {
357 $profiles[] = Profile::staticGet($subs->subscribed);
360 return new ArrayWrapper($profiles);
363 function getSubscribers($offset=0, $limit=null)
365 $subs = Subscription::bySubscribed($this->id,
371 while ($subs->fetch()) {
372 $profiles[] = Profile::staticGet($subs->subscriber);
375 return new ArrayWrapper($profiles);
378 function subscriptionCount()
380 $c = common_memcache();
383 $cnt = $c->get(common_cache_key('profile:subscription_count:'.$this->id));
384 if (is_integer($cnt)) {
389 $sub = new Subscription();
390 $sub->subscriber = $this->id;
392 $cnt = (int) $sub->count('distinct subscribed');
394 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
397 $c->set(common_cache_key('profile:subscription_count:'.$this->id), $cnt);
403 function subscriberCount()
405 $c = common_memcache();
407 $cnt = $c->get(common_cache_key('profile:subscriber_count:'.$this->id));
408 if (is_integer($cnt)) {
413 $sub = new Subscription();
414 $sub->subscribed = $this->id;
415 $sub->whereAdd('subscriber != subscribed');
416 $cnt = (int) $sub->count('distinct subscriber');
419 $c->set(common_cache_key('profile:subscriber_count:'.$this->id), $cnt);
426 * Is this profile subscribed to another profile?
428 * @param Profile $other
431 function isSubscribed($other)
433 return Subscription::exists($this, $other);
437 * Are these two profiles subscribed to each other?
439 * @param Profile $other
442 function mutuallySubscribed($other)
444 return $this->isSubscribed($other) &&
445 $other->isSubscribed($this);
448 function hasFave($notice)
450 $cache = common_memcache();
452 // XXX: Kind of a hack.
454 if (!empty($cache)) {
455 // This is the stream of favorite notices, in rev chron
456 // order. This forces it into cache.
458 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
460 // If it's in the list, then it's a fave
462 if (in_array($notice->id, $ids)) {
466 // If we're not past the end of the cache window,
467 // then the cache has all available faves, so this one
470 if (count($ids) < NOTICE_CACHE_WINDOW) {
474 // Otherwise, cache doesn't have all faves;
475 // fall through to the default
478 $fave = Fave::pkeyGet(array('user_id' => $this->id,
479 'notice_id' => $notice->id));
480 return ((is_null($fave)) ? false : true);
485 $c = common_memcache();
487 $cnt = $c->get(common_cache_key('profile:fave_count:'.$this->id));
488 if (is_integer($cnt)) {
494 $faves->user_id = $this->id;
495 $cnt = (int) $faves->count('distinct notice_id');
498 $c->set(common_cache_key('profile:fave_count:'.$this->id), $cnt);
504 function noticeCount()
506 $c = common_memcache();
509 $cnt = $c->get(common_cache_key('profile:notice_count:'.$this->id));
510 if (is_integer($cnt)) {
515 $notices = new Notice();
516 $notices->profile_id = $this->id;
517 $cnt = (int) $notices->count('distinct id');
520 $c->set(common_cache_key('profile:notice_count:'.$this->id), $cnt);
526 function blowFavesCache()
528 $cache = common_memcache();
530 // Faves don't happen chronologically, so we need to blow
532 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
533 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
534 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
535 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
537 $this->blowFaveCount();
540 function blowSubscriberCount()
542 $c = common_memcache();
544 $c->delete(common_cache_key('profile:subscriber_count:'.$this->id));
548 function blowSubscriptionCount()
550 $c = common_memcache();
552 $c->delete(common_cache_key('profile:subscription_count:'.$this->id));
556 function blowFaveCount()
558 $c = common_memcache();
560 $c->delete(common_cache_key('profile:fave_count:'.$this->id));
564 function blowNoticeCount()
566 $c = common_memcache();
568 $c->delete(common_cache_key('profile:notice_count:'.$this->id));
572 static function maxBio()
574 $biolimit = common_config('profile', 'biolimit');
575 // null => use global limit (distinct from 0!)
576 if (is_null($biolimit)) {
577 $biolimit = common_config('site', 'textlimit');
582 static function bioTooLong($bio)
584 $biolimit = self::maxBio();
585 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
590 $this->_deleteNotices();
591 $this->_deleteSubscriptions();
592 $this->_deleteMessages();
593 $this->_deleteTags();
594 $this->_deleteBlocks();
595 $this->delete_avatars();
597 // Warning: delete() will run on the batch objects,
598 // not on individual objects.
599 $related = array('Reply',
602 Event::handle('ProfileDeleteRelated', array($this, &$related));
604 foreach ($related as $cls) {
606 $inst->profile_id = $this->id;
613 function _deleteNotices()
615 $notice = new Notice();
616 $notice->profile_id = $this->id;
618 if ($notice->find()) {
619 while ($notice->fetch()) {
620 $other = clone($notice);
626 function _deleteSubscriptions()
628 $sub = new Subscription();
629 $sub->subscriber = $this->id;
633 while ($sub->fetch()) {
634 $other = Profile::staticGet('id', $sub->subscribed);
638 if ($other->id == $this->id) {
641 Subscription::cancel($this, $other);
644 $subd = new Subscription();
645 $subd->subscribed = $this->id;
648 while ($subd->fetch()) {
649 $other = Profile::staticGet('id', $subd->subscriber);
653 if ($other->id == $this->id) {
656 Subscription::cancel($other, $this);
659 $self = new Subscription();
661 $self->subscriber = $this->id;
662 $self->subscribed = $this->id;
667 function _deleteMessages()
669 $msg = new Message();
670 $msg->from_profile = $this->id;
673 $msg = new Message();
674 $msg->to_profile = $this->id;
678 function _deleteTags()
680 $tag = new Profile_tag();
681 $tag->tagged = $this->id;
685 function _deleteBlocks()
687 $block = new Profile_block();
688 $block->blocked = $this->id;
691 $block = new Group_block();
692 $block->blocked = $this->id;
696 // XXX: identical to Notice::getLocation.
698 function getLocation()
702 if (!empty($this->location_id) && !empty($this->location_ns)) {
703 $location = Location::fromId($this->location_id, $this->location_ns);
706 if (is_null($location)) { // no ID, or Location::fromId() failed
707 if (!empty($this->lat) && !empty($this->lon)) {
708 $location = Location::fromLatLon($this->lat, $this->lon);
712 if (is_null($location)) { // still haven't found it!
713 if (!empty($this->location)) {
714 $location = Location::fromName($this->location);
721 function hasRole($name)
724 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
725 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
727 $has_role = !empty($role);
728 Event::handle('EndHasRole', array($this, $name, $has_role));
733 function grantRole($name)
735 if (Event::handle('StartGrantRole', array($this, $name))) {
737 $role = new Profile_role();
739 $role->profile_id = $this->id;
741 $role->created = common_sql_now();
743 $result = $role->insert();
746 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
749 Event::handle('EndGrantRole', array($this, $name));
755 function revokeRole($name)
757 if (Event::handle('StartRevokeRole', array($this, $name))) {
759 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
763 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
764 // TRANS: %1$s is the role name, %2$s is the user ID (number).
765 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
768 $result = $role->delete();
771 common_log_db_error($role, 'DELETE', __FILE__);
772 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
773 // TRANS: %1$s is the role name, %2$s is the user ID (number).
774 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
777 Event::handle('EndRevokeRole', array($this, $name));
783 function isSandboxed()
785 return $this->hasRole(Profile_role::SANDBOXED);
788 function isSilenced()
790 return $this->hasRole(Profile_role::SILENCED);
795 $this->grantRole(Profile_role::SANDBOXED);
800 $this->revokeRole(Profile_role::SANDBOXED);
805 $this->grantRole(Profile_role::SILENCED);
810 $this->revokeRole(Profile_role::SILENCED);
814 * Does this user have the right to do X?
816 * With our role-based authorization, this is merely a lookup for whether the user
817 * has a particular role. The implementation currently uses a switch statement
818 * to determine if the user has the pre-defined role to exercise the right. Future
819 * implementations may allow per-site roles, and different mappings of roles to rights.
821 * @param $right string Name of the right, usually a constant in class Right
822 * @return boolean whether the user has the right in question
824 function hasRight($right)
828 if ($this->hasRole(Profile_role::DELETED)) {
832 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
835 case Right::DELETEOTHERSNOTICE:
836 case Right::MAKEGROUPADMIN:
837 case Right::SANDBOXUSER:
838 case Right::SILENCEUSER:
839 case Right::DELETEUSER:
840 case Right::DELETEGROUP:
841 $result = $this->hasRole(Profile_role::MODERATOR);
843 case Right::CONFIGURESITE:
844 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
846 case Right::GRANTROLE:
847 case Right::REVOKEROLE:
848 $result = $this->hasRole(Profile_role::OWNER);
850 case Right::NEWNOTICE:
851 case Right::NEWMESSAGE:
852 case Right::SUBSCRIBE:
853 $result = !$this->isSilenced();
855 case Right::PUBLICNOTICE:
856 case Right::EMAILONREPLY:
857 case Right::EMAILONSUBSCRIBE:
858 case Right::EMAILONFAVE:
859 $result = !$this->isSandboxed();
869 function hasRepeated($notice_id)
871 // XXX: not really a pkey, but should work
873 $notice = Memcached_DataObject::pkeyGet('Notice',
874 array('profile_id' => $this->id,
875 'repeat_of' => $notice_id));
877 return !empty($notice);
881 * Returns an XML string fragment with limited profile information
882 * as an Atom <author> element.
884 * Assumes that Atom has been previously set up as the base namespace.
886 * @param Profile $cur the current authenticated user
890 function asAtomAuthor($cur = null)
892 $xs = new XMLStringer(true);
894 $xs->elementStart('author');
895 $xs->element('name', null, $this->nickname);
896 $xs->element('uri', null, $this->getUri());
899 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
900 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
901 $xs->element('statusnet:profile_info', $attrs, null);
903 $xs->elementEnd('author');
905 return $xs->getString();
909 * Returns an XML string fragment with profile information as an
910 * Activity Streams <activity:actor> element.
912 * Assumes that 'activity' namespace has been previously defined.
916 function asActivityActor()
918 return $this->asActivityNoun('actor');
922 * Returns an XML string fragment with profile information as an
923 * Activity Streams noun object with the given element type.
925 * Assumes that 'activity', 'georss', and 'poco' namespace has been
926 * previously defined.
928 * @param string $element one of 'actor', 'subject', 'object', 'target'
932 function asActivityNoun($element)
934 $noun = ActivityObject::fromProfile($this);
935 return $noun->asString('activity:' . $element);
939 * Returns the best URI for a profile. Plugins may override.
941 * @return string $uri
947 // give plugins a chance to set the URI
948 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
950 // check for a local user first
951 $user = User::staticGet('id', $this->id);
956 // return OMB profile if any
957 $remote = Remote_profile::staticGet('id', $this->id);
958 if (!empty($remote)) {
962 Event::handle('EndGetProfileUri', array($this, &$uri));
968 function hasBlocked($other)
970 $block = Profile_block::get($this->id, $other->id);
981 function getAtomFeed()
985 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
986 $user = User::staticGet('id', $this->id);
988 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
989 'format' => 'atom'));
991 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
997 static function fromURI($uri)
1001 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1002 // Get a local user or remote (OMB 0.1) profile
1003 $user = User::staticGet('uri', $uri);
1004 if (!empty($user)) {
1005 $profile = $user->getProfile();
1007 $remote_profile = Remote_profile::staticGet('uri', $uri);
1008 if (!empty($remote_profile)) {
1009 $profile = Profile::staticGet('id', $remote_profile->profile_id);
1012 Event::handle('EndGetProfileFromURI', array($uri, $profile));