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 $profile = Profile::staticGet($subs->subscribed);
359 $profiles[] = $profile;
363 return new ArrayWrapper($profiles);
366 function getSubscribers($offset=0, $limit=null)
368 $subs = Subscription::bySubscribed($this->id,
374 while ($subs->fetch()) {
375 $profile = Profile::staticGet($subs->subscriber);
377 $profiles[] = $profile;
381 return new ArrayWrapper($profiles);
384 function subscriptionCount()
386 $c = common_memcache();
389 $cnt = $c->get(common_cache_key('profile:subscription_count:'.$this->id));
390 if (is_integer($cnt)) {
395 $sub = new Subscription();
396 $sub->subscriber = $this->id;
398 $cnt = (int) $sub->count('distinct subscribed');
400 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
403 $c->set(common_cache_key('profile:subscription_count:'.$this->id), $cnt);
409 function subscriberCount()
411 $c = common_memcache();
413 $cnt = $c->get(common_cache_key('profile:subscriber_count:'.$this->id));
414 if (is_integer($cnt)) {
419 $sub = new Subscription();
420 $sub->subscribed = $this->id;
421 $sub->whereAdd('subscriber != subscribed');
422 $cnt = (int) $sub->count('distinct subscriber');
425 $c->set(common_cache_key('profile:subscriber_count:'.$this->id), $cnt);
432 * Is this profile subscribed to another profile?
434 * @param Profile $other
437 function isSubscribed($other)
439 return Subscription::exists($this, $other);
443 * Are these two profiles subscribed to each other?
445 * @param Profile $other
448 function mutuallySubscribed($other)
450 return $this->isSubscribed($other) &&
451 $other->isSubscribed($this);
454 function hasFave($notice)
456 $cache = common_memcache();
458 // XXX: Kind of a hack.
460 if (!empty($cache)) {
461 // This is the stream of favorite notices, in rev chron
462 // order. This forces it into cache.
464 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
466 // If it's in the list, then it's a fave
468 if (in_array($notice->id, $ids)) {
472 // If we're not past the end of the cache window,
473 // then the cache has all available faves, so this one
476 if (count($ids) < NOTICE_CACHE_WINDOW) {
480 // Otherwise, cache doesn't have all faves;
481 // fall through to the default
484 $fave = Fave::pkeyGet(array('user_id' => $this->id,
485 'notice_id' => $notice->id));
486 return ((is_null($fave)) ? false : true);
491 $c = common_memcache();
493 $cnt = $c->get(common_cache_key('profile:fave_count:'.$this->id));
494 if (is_integer($cnt)) {
500 $faves->user_id = $this->id;
501 $cnt = (int) $faves->count('distinct notice_id');
504 $c->set(common_cache_key('profile:fave_count:'.$this->id), $cnt);
510 function noticeCount()
512 $c = common_memcache();
515 $cnt = $c->get(common_cache_key('profile:notice_count:'.$this->id));
516 if (is_integer($cnt)) {
521 $notices = new Notice();
522 $notices->profile_id = $this->id;
523 $cnt = (int) $notices->count('distinct id');
526 $c->set(common_cache_key('profile:notice_count:'.$this->id), $cnt);
532 function blowFavesCache()
534 $cache = common_memcache();
536 // Faves don't happen chronologically, so we need to blow
538 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
539 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
540 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
541 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
543 $this->blowFaveCount();
546 function blowSubscriberCount()
548 $c = common_memcache();
550 $c->delete(common_cache_key('profile:subscriber_count:'.$this->id));
554 function blowSubscriptionCount()
556 $c = common_memcache();
558 $c->delete(common_cache_key('profile:subscription_count:'.$this->id));
562 function blowFaveCount()
564 $c = common_memcache();
566 $c->delete(common_cache_key('profile:fave_count:'.$this->id));
570 function blowNoticeCount()
572 $c = common_memcache();
574 $c->delete(common_cache_key('profile:notice_count:'.$this->id));
578 static function maxBio()
580 $biolimit = common_config('profile', 'biolimit');
581 // null => use global limit (distinct from 0!)
582 if (is_null($biolimit)) {
583 $biolimit = common_config('site', 'textlimit');
588 static function bioTooLong($bio)
590 $biolimit = self::maxBio();
591 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
596 $this->_deleteNotices();
597 $this->_deleteSubscriptions();
598 $this->_deleteMessages();
599 $this->_deleteTags();
600 $this->_deleteBlocks();
601 $this->delete_avatars();
603 // Warning: delete() will run on the batch objects,
604 // not on individual objects.
605 $related = array('Reply',
608 Event::handle('ProfileDeleteRelated', array($this, &$related));
610 foreach ($related as $cls) {
612 $inst->profile_id = $this->id;
619 function _deleteNotices()
621 $notice = new Notice();
622 $notice->profile_id = $this->id;
624 if ($notice->find()) {
625 while ($notice->fetch()) {
626 $other = clone($notice);
632 function _deleteSubscriptions()
634 $sub = new Subscription();
635 $sub->subscriber = $this->id;
639 while ($sub->fetch()) {
640 $other = Profile::staticGet('id', $sub->subscribed);
644 if ($other->id == $this->id) {
647 Subscription::cancel($this, $other);
650 $subd = new Subscription();
651 $subd->subscribed = $this->id;
654 while ($subd->fetch()) {
655 $other = Profile::staticGet('id', $subd->subscriber);
659 if ($other->id == $this->id) {
662 Subscription::cancel($other, $this);
665 $self = new Subscription();
667 $self->subscriber = $this->id;
668 $self->subscribed = $this->id;
673 function _deleteMessages()
675 $msg = new Message();
676 $msg->from_profile = $this->id;
679 $msg = new Message();
680 $msg->to_profile = $this->id;
684 function _deleteTags()
686 $tag = new Profile_tag();
687 $tag->tagged = $this->id;
691 function _deleteBlocks()
693 $block = new Profile_block();
694 $block->blocked = $this->id;
697 $block = new Group_block();
698 $block->blocked = $this->id;
702 // XXX: identical to Notice::getLocation.
704 function getLocation()
708 if (!empty($this->location_id) && !empty($this->location_ns)) {
709 $location = Location::fromId($this->location_id, $this->location_ns);
712 if (is_null($location)) { // no ID, or Location::fromId() failed
713 if (!empty($this->lat) && !empty($this->lon)) {
714 $location = Location::fromLatLon($this->lat, $this->lon);
718 if (is_null($location)) { // still haven't found it!
719 if (!empty($this->location)) {
720 $location = Location::fromName($this->location);
727 function hasRole($name)
730 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
731 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
733 $has_role = !empty($role);
734 Event::handle('EndHasRole', array($this, $name, $has_role));
739 function grantRole($name)
741 if (Event::handle('StartGrantRole', array($this, $name))) {
743 $role = new Profile_role();
745 $role->profile_id = $this->id;
747 $role->created = common_sql_now();
749 $result = $role->insert();
752 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
755 Event::handle('EndGrantRole', array($this, $name));
761 function revokeRole($name)
763 if (Event::handle('StartRevokeRole', array($this, $name))) {
765 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
769 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
770 // TRANS: %1$s is the role name, %2$s is the user ID (number).
771 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
774 $result = $role->delete();
777 common_log_db_error($role, 'DELETE', __FILE__);
778 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
779 // TRANS: %1$s is the role name, %2$s is the user ID (number).
780 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
783 Event::handle('EndRevokeRole', array($this, $name));
789 function isSandboxed()
791 return $this->hasRole(Profile_role::SANDBOXED);
794 function isSilenced()
796 return $this->hasRole(Profile_role::SILENCED);
801 $this->grantRole(Profile_role::SANDBOXED);
806 $this->revokeRole(Profile_role::SANDBOXED);
811 $this->grantRole(Profile_role::SILENCED);
816 $this->revokeRole(Profile_role::SILENCED);
820 * Does this user have the right to do X?
822 * With our role-based authorization, this is merely a lookup for whether the user
823 * has a particular role. The implementation currently uses a switch statement
824 * to determine if the user has the pre-defined role to exercise the right. Future
825 * implementations may allow per-site roles, and different mappings of roles to rights.
827 * @param $right string Name of the right, usually a constant in class Right
828 * @return boolean whether the user has the right in question
830 function hasRight($right)
834 if ($this->hasRole(Profile_role::DELETED)) {
838 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
841 case Right::DELETEOTHERSNOTICE:
842 case Right::MAKEGROUPADMIN:
843 case Right::SANDBOXUSER:
844 case Right::SILENCEUSER:
845 case Right::DELETEUSER:
846 case Right::DELETEGROUP:
847 $result = $this->hasRole(Profile_role::MODERATOR);
849 case Right::CONFIGURESITE:
850 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
852 case Right::GRANTROLE:
853 case Right::REVOKEROLE:
854 $result = $this->hasRole(Profile_role::OWNER);
856 case Right::NEWNOTICE:
857 case Right::NEWMESSAGE:
858 case Right::SUBSCRIBE:
859 case Right::CREATEGROUP:
860 $result = !$this->isSilenced();
862 case Right::PUBLICNOTICE:
863 case Right::EMAILONREPLY:
864 case Right::EMAILONSUBSCRIBE:
865 case Right::EMAILONFAVE:
866 $result = !$this->isSandboxed();
868 case Right::BACKUPACCOUNT:
869 $result = common_config('profile', 'backup');
871 case Right::RESTOREACCOUNT:
872 $result = common_config('profile', 'restore');
874 case Right::DELETEACCOUNT:
875 $result = common_config('profile', 'delete');
877 case Right::MOVEACCOUNT:
878 $result = common_config('profile', 'move');
888 function hasRepeated($notice_id)
890 // XXX: not really a pkey, but should work
892 $notice = Memcached_DataObject::pkeyGet('Notice',
893 array('profile_id' => $this->id,
894 'repeat_of' => $notice_id));
896 return !empty($notice);
900 * Returns an XML string fragment with limited profile information
901 * as an Atom <author> element.
903 * Assumes that Atom has been previously set up as the base namespace.
905 * @param Profile $cur the current authenticated user
909 function asAtomAuthor($cur = null)
911 $xs = new XMLStringer(true);
913 $xs->elementStart('author');
914 $xs->element('name', null, $this->nickname);
915 $xs->element('uri', null, $this->getUri());
918 $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
919 $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
920 $xs->element('statusnet:profile_info', $attrs, null);
922 $xs->elementEnd('author');
924 return $xs->getString();
928 * Extra profile info for atom entries
930 * Clients use some extra profile info in the atom stream.
931 * This gives it to them.
933 * @param User $cur Current user
935 * @return array representation of <statusnet:profile_info> element or null
938 function profileInfo($cur)
940 $profileInfoAttr = array('local_id' => $this->id);
943 // Whether the current user is a subscribed to this profile
944 $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
945 // Whether the current user is has blocked this profile
946 $profileInfoAttr['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
949 return array('statusnet:profile_info', $profileInfoAttr, null);
953 * Returns an XML string fragment with profile information as an
954 * Activity Streams <activity:actor> element.
956 * Assumes that 'activity' namespace has been previously defined.
960 function asActivityActor()
962 return $this->asActivityNoun('actor');
966 * Returns an XML string fragment with profile information as an
967 * Activity Streams noun object with the given element type.
969 * Assumes that 'activity', 'georss', and 'poco' namespace has been
970 * previously defined.
972 * @param string $element one of 'actor', 'subject', 'object', 'target'
976 function asActivityNoun($element)
978 $noun = ActivityObject::fromProfile($this);
979 return $noun->asString('activity:' . $element);
983 * Returns the best URI for a profile. Plugins may override.
985 * @return string $uri
991 // give plugins a chance to set the URI
992 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
994 // check for a local user first
995 $user = User::staticGet('id', $this->id);
1000 // return OMB profile if any
1001 $remote = Remote_profile::staticGet('id', $this->id);
1002 if (!empty($remote)) {
1003 $uri = $remote->uri;
1006 Event::handle('EndGetProfileUri', array($this, &$uri));
1012 function hasBlocked($other)
1014 $block = Profile_block::get($this->id, $other->id);
1016 if (empty($block)) {
1025 function getAtomFeed()
1029 if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1030 $user = User::staticGet('id', $this->id);
1031 if (!empty($user)) {
1032 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1033 'format' => 'atom'));
1035 Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1041 static function fromURI($uri)
1045 if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1046 // Get a local user or remote (OMB 0.1) profile
1047 $user = User::staticGet('uri', $uri);
1048 if (!empty($user)) {
1049 $profile = $user->getProfile();
1051 $remote_profile = Remote_profile::staticGet('uri', $uri);
1052 if (!empty($remote_profile)) {
1053 $profile = Profile::staticGet('id', $remote_profile->profile_id);
1056 Event::handle('EndGetProfileFromURI', array($uri, $profile));