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)) {
107 $scaled_filename = $imagefile->resize($size);
109 //$scaled = DB_DataObject::factory('avatar');
110 $scaled = new Avatar();
111 $scaled->profile_id = $this->id;
112 $scaled->width = $size;
113 $scaled->height = $size;
114 $scaled->original = false;
115 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
116 $scaled->filename = $scaled_filename;
117 $scaled->url = Avatar::url($scaled_filename);
118 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
120 if (!$scaled->insert()) {
129 function delete_avatars($original=true)
131 $avatar = new Avatar();
132 $avatar->profile_id = $this->id;
134 while ($avatar->fetch()) {
135 if ($avatar->original) {
136 if ($original == false) {
145 function getBestName()
147 return ($this->fullname) ? $this->fullname : $this->nickname;
151 * Get the most recent notice posted by this user, if any.
153 * @return mixed Notice or null
155 function getCurrentNotice()
157 $notice = new Notice();
158 $notice->profile_id = $this->id;
159 // @fixme change this to sort on notice.id only when indexes are updated
160 $notice->orderBy('created DESC, notice.id DESC');
162 if ($notice->find(true)) {
168 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
170 $ids = Notice::stream(array($this, '_streamTaggedDirect'),
172 'profile:notice_ids_tagged:' . $this->id . ':' . $tag,
173 $offset, $limit, $since_id, $max_id);
174 return Notice::getStreamByIds($ids);
177 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
179 // XXX: I'm not sure this is going to be any faster. It probably isn't.
180 $ids = Notice::stream(array($this, '_streamDirect'),
182 'profile:notice_ids:' . $this->id,
183 $offset, $limit, $since_id, $max_id);
185 return Notice::getStreamByIds($ids);
188 function _streamTaggedDirect($tag, $offset, $limit, $since_id, $max_id)
190 // XXX It would be nice to do this without a join
192 $notice = new Notice();
195 "select id from notice join notice_tag on id=notice_id where tag='".
196 $notice->escape($tag) .
197 "' and profile_id=" . $notice->escape($this->id);
199 if ($since_id != 0) {
200 $query .= " and id > $since_id";
204 $query .= " and id < $max_id";
207 $query .= ' order by id DESC';
209 if (!is_null($offset)) {
210 $query .= " LIMIT $limit OFFSET $offset";
213 $notice->query($query);
217 while ($notice->fetch()) {
218 $ids[] = $notice->id;
224 function _streamDirect($offset, $limit, $since_id, $max_id)
226 $notice = new Notice();
228 $notice->profile_id = $this->id;
230 $notice->selectAdd();
231 $notice->selectAdd('id');
233 if ($since_id != 0) {
234 $notice->whereAdd('id > ' . $since_id);
238 $notice->whereAdd('id <= ' . $max_id);
241 $notice->orderBy('id DESC');
243 if (!is_null($offset)) {
244 $notice->limit($offset, $limit);
249 if ($notice->find()) {
250 while ($notice->fetch()) {
251 $ids[] = $notice->id;
258 function isMember($group)
260 $mem = new Group_member();
262 $mem->group_id = $group->id;
263 $mem->profile_id = $this->id;
272 function isAdmin($group)
274 $mem = new Group_member();
276 $mem->group_id = $group->id;
277 $mem->profile_id = $this->id;
287 function getGroups($offset=0, $limit=null)
290 'SELECT user_group.* ' .
291 'FROM user_group JOIN group_member '.
292 'ON user_group.id = group_member.group_id ' .
293 'WHERE group_member.profile_id = %d ' .
294 'ORDER BY group_member.created DESC ';
296 if ($offset>0 && !is_null($limit)) {
298 if (common_config('db','type') == 'pgsql') {
299 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
301 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
306 $groups = new User_group();
308 $cnt = $groups->query(sprintf($qry, $this->id));
313 function avatarUrl($size=AVATAR_PROFILE_SIZE)
315 $avatar = $this->getAvatar($size);
317 return $avatar->displayUrl();
319 return Avatar::defaultImage($size);
323 function getSubscriptions($offset=0, $limit=null)
326 'SELECT profile.* ' .
327 'FROM profile JOIN subscription ' .
328 'ON profile.id = subscription.subscribed ' .
329 'WHERE subscription.subscriber = %d ' .
330 'AND subscription.subscribed != subscription.subscriber ' .
331 'ORDER BY subscription.created DESC ';
333 if ($offset>0 && !is_null($limit)){
334 if (common_config('db','type') == 'pgsql') {
335 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
337 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
341 $profile = new Profile();
343 $profile->query(sprintf($qry, $this->id));
348 function getSubscribers($offset=0, $limit=null)
351 'SELECT profile.* ' .
352 'FROM profile JOIN subscription ' .
353 'ON profile.id = subscription.subscriber ' .
354 'WHERE subscription.subscribed = %d ' .
355 'AND subscription.subscribed != subscription.subscriber ' .
356 'ORDER BY subscription.created DESC ';
358 if ($offset>0 && !is_null($limit)){
360 if (common_config('db','type') == 'pgsql') {
361 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
363 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
368 $profile = new Profile();
370 $cnt = $profile->query(sprintf($qry, $this->id));
375 function getApplications($offset = 0, $limit = null)
379 'FROM oauth_application_user u, oauth_application a ' .
380 'WHERE u.profile_id = %d ' .
381 'AND a.id = u.application_id ' .
382 'AND u.access_type > 0 ' .
383 'ORDER BY u.created DESC ';
386 if (common_config('db','type') == 'pgsql') {
387 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
389 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
393 $application = new Oauth_application();
395 $cnt = $application->query(sprintf($qry, $this->id));
400 function subscriptionCount()
402 $c = common_memcache();
405 $cnt = $c->get(common_cache_key('profile:subscription_count:'.$this->id));
406 if (is_integer($cnt)) {
411 $sub = new Subscription();
412 $sub->subscriber = $this->id;
414 $cnt = (int) $sub->count('distinct subscribed');
416 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
419 $c->set(common_cache_key('profile:subscription_count:'.$this->id), $cnt);
425 function subscriberCount()
427 $c = common_memcache();
429 $cnt = $c->get(common_cache_key('profile:subscriber_count:'.$this->id));
430 if (is_integer($cnt)) {
435 $sub = new Subscription();
436 $sub->subscribed = $this->id;
438 $cnt = (int) $sub->count('distinct subscriber');
440 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
443 $c->set(common_cache_key('profile:subscriber_count:'.$this->id), $cnt);
451 $c = common_memcache();
453 $cnt = $c->get(common_cache_key('profile:fave_count:'.$this->id));
454 if (is_integer($cnt)) {
460 $faves->user_id = $this->id;
461 $cnt = (int) $faves->count('distinct notice_id');
464 $c->set(common_cache_key('profile:fave_count:'.$this->id), $cnt);
470 function noticeCount()
472 $c = common_memcache();
475 $cnt = $c->get(common_cache_key('profile:notice_count:'.$this->id));
476 if (is_integer($cnt)) {
481 $notices = new Notice();
482 $notices->profile_id = $this->id;
483 $cnt = (int) $notices->count('distinct id');
486 $c->set(common_cache_key('profile:notice_count:'.$this->id), $cnt);
492 function blowSubscriberCount()
494 $c = common_memcache();
496 $c->delete(common_cache_key('profile:subscriber_count:'.$this->id));
500 function blowSubscriptionCount()
502 $c = common_memcache();
504 $c->delete(common_cache_key('profile:subscription_count:'.$this->id));
508 function blowFaveCount()
510 $c = common_memcache();
512 $c->delete(common_cache_key('profile:fave_count:'.$this->id));
516 function blowNoticeCount()
518 $c = common_memcache();
520 $c->delete(common_cache_key('profile:notice_count:'.$this->id));
524 static function maxBio()
526 $biolimit = common_config('profile', 'biolimit');
527 // null => use global limit (distinct from 0!)
528 if (is_null($biolimit)) {
529 $biolimit = common_config('site', 'textlimit');
534 static function bioTooLong($bio)
536 $biolimit = self::maxBio();
537 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
542 $this->_deleteNotices();
543 $this->_deleteSubscriptions();
544 $this->_deleteMessages();
545 $this->_deleteTags();
546 $this->_deleteBlocks();
548 $related = array('Avatar',
552 Event::handle('ProfileDeleteRelated', array($this, &$related));
554 foreach ($related as $cls) {
556 $inst->profile_id = $this->id;
563 function _deleteNotices()
565 $notice = new Notice();
566 $notice->profile_id = $this->id;
568 if ($notice->find()) {
569 while ($notice->fetch()) {
570 $other = clone($notice);
576 function _deleteSubscriptions()
578 $sub = new Subscription();
579 $sub->subscriber = $this->id;
582 $subd = new Subscription();
583 $subd->subscribed = $this->id;
587 function _deleteMessages()
589 $msg = new Message();
590 $msg->from_profile = $this->id;
593 $msg = new Message();
594 $msg->to_profile = $this->id;
598 function _deleteTags()
600 $tag = new Profile_tag();
601 $tag->tagged = $this->id;
605 function _deleteBlocks()
607 $block = new Profile_block();
608 $block->blocked = $this->id;
611 $block = new Group_block();
612 $block->blocked = $this->id;
616 // XXX: identical to Notice::getLocation.
618 function getLocation()
622 if (!empty($this->location_id) && !empty($this->location_ns)) {
623 $location = Location::fromId($this->location_id, $this->location_ns);
626 if (is_null($location)) { // no ID, or Location::fromId() failed
627 if (!empty($this->lat) && !empty($this->lon)) {
628 $location = Location::fromLatLon($this->lat, $this->lon);
632 if (is_null($location)) { // still haven't found it!
633 if (!empty($this->location)) {
634 $location = Location::fromName($this->location);
641 function hasRole($name)
644 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
645 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
647 $has_role = !empty($role);
648 Event::handle('EndHasRole', array($this, $name, $has_role));
653 function grantRole($name)
655 $role = new Profile_role();
657 $role->profile_id = $this->id;
659 $role->created = common_sql_now();
661 $result = $role->insert();
664 common_log_db_error($role, 'INSERT', __FILE__);
671 function revokeRole($name)
673 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
677 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
680 $result = $role->delete();
683 common_log_db_error($role, 'DELETE', __FILE__);
684 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
690 function isSandboxed()
692 return $this->hasRole(Profile_role::SANDBOXED);
695 function isSilenced()
697 return $this->hasRole(Profile_role::SILENCED);
702 $this->grantRole(Profile_role::SANDBOXED);
707 $this->revokeRole(Profile_role::SANDBOXED);
712 $this->grantRole(Profile_role::SILENCED);
717 $this->revokeRole(Profile_role::SILENCED);
721 * Does this user have the right to do X?
723 * With our role-based authorization, this is merely a lookup for whether the user
724 * has a particular role. The implementation currently uses a switch statement
725 * to determine if the user has the pre-defined role to exercise the right. Future
726 * implementations may allow per-site roles, and different mappings of roles to rights.
728 * @param $right string Name of the right, usually a constant in class Right
729 * @return boolean whether the user has the right in question
732 function hasRight($right)
735 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
738 case Right::DELETEOTHERSNOTICE:
739 case Right::MAKEGROUPADMIN:
740 case Right::SANDBOXUSER:
741 case Right::SILENCEUSER:
742 case Right::DELETEUSER:
743 $result = $this->hasRole(Profile_role::MODERATOR);
745 case Right::CONFIGURESITE:
746 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
748 case Right::GRANTROLE:
749 case Right::REVOKEROLE:
750 $result = $this->hasRole(Profile_role::OWNER);
752 case Right::NEWNOTICE:
753 case Right::NEWMESSAGE:
754 case Right::SUBSCRIBE:
755 $result = !$this->isSilenced();
757 case Right::PUBLICNOTICE:
758 case Right::EMAILONREPLY:
759 case Right::EMAILONSUBSCRIBE:
760 case Right::EMAILONFAVE:
761 $result = !$this->isSandboxed();
771 function hasRepeated($notice_id)
773 // XXX: not really a pkey, but should work
775 $notice = Memcached_DataObject::pkeyGet('Notice',
776 array('profile_id' => $this->id,
777 'repeat_of' => $notice_id));
779 return !empty($notice);
783 * Returns an XML string fragment with limited profile information
784 * as an Atom <author> element.
786 * Assumes that Atom has been previously set up as the base namespace.
790 function asAtomAuthor()
792 $xs = new XMLStringer(true);
794 $xs->elementStart('author');
795 $xs->element('name', null, $this->nickname);
796 $xs->element('uri', null, $this->getUri());
797 $xs->elementEnd('author');
799 return $xs->getString();
803 * Returns an XML string fragment with profile information as an
804 * Activity Streams <activity:actor> element.
806 * Assumes that 'activity' namespace has been previously defined.
810 function asActivityActor()
812 return $this->asActivityNoun('actor');
816 * Returns an XML string fragment with profile information as an
817 * Activity Streams noun object with the given element type.
819 * Assumes that 'activity', 'georss', and 'poco' namespace has been
820 * previously defined.
822 * @param string $element one of 'actor', 'subject', 'object', 'target'
826 function asActivityNoun($element)
828 $noun = ActivityObject::fromProfile($this);
829 return $noun->asString('activity:' . $element);
833 * Returns the best URI for a profile. Plugins may override.
835 * @return string $uri
841 // give plugins a chance to set the URI
842 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
844 // check for a local user first
845 $user = User::staticGet('id', $this->id);
850 // return OMB profile if any
851 $remote = Remote_profile::staticGet('id', $this->id);
852 if (!empty($remote)) {
856 Event::handle('EndGetProfileUri', array($this, &$uri));
862 function hasBlocked($other)
864 $block = Profile_block::get($this->id, $other->id);