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;
583 while ($sub->fetch()) {
584 $other = Profile::staticGet('id', $sub->subscribed);
588 if ($other->id == $this->id) {
591 Subscription::cancel($this, $other);
594 $subd = new Subscription();
595 $subd->subscribed = $this->id;
598 while ($subd->fetch()) {
599 $other = Profile::staticGet('id', $subd->subscriber);
603 if ($other->id == $this->id) {
606 Subscription::cancel($other, $this);
609 $self = new Subscription();
611 $self->subscriber = $this->id;
612 $self->subscribed = $this->id;
617 function _deleteMessages()
619 $msg = new Message();
620 $msg->from_profile = $this->id;
623 $msg = new Message();
624 $msg->to_profile = $this->id;
628 function _deleteTags()
630 $tag = new Profile_tag();
631 $tag->tagged = $this->id;
635 function _deleteBlocks()
637 $block = new Profile_block();
638 $block->blocked = $this->id;
641 $block = new Group_block();
642 $block->blocked = $this->id;
646 // XXX: identical to Notice::getLocation.
648 function getLocation()
652 if (!empty($this->location_id) && !empty($this->location_ns)) {
653 $location = Location::fromId($this->location_id, $this->location_ns);
656 if (is_null($location)) { // no ID, or Location::fromId() failed
657 if (!empty($this->lat) && !empty($this->lon)) {
658 $location = Location::fromLatLon($this->lat, $this->lon);
662 if (is_null($location)) { // still haven't found it!
663 if (!empty($this->location)) {
664 $location = Location::fromName($this->location);
671 function hasRole($name)
674 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
675 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
677 $has_role = !empty($role);
678 Event::handle('EndHasRole', array($this, $name, $has_role));
683 function grantRole($name)
685 $role = new Profile_role();
687 $role->profile_id = $this->id;
689 $role->created = common_sql_now();
691 $result = $role->insert();
694 common_log_db_error($role, 'INSERT', __FILE__);
701 function revokeRole($name)
703 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
707 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
710 $result = $role->delete();
713 common_log_db_error($role, 'DELETE', __FILE__);
714 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
720 function isSandboxed()
722 return $this->hasRole(Profile_role::SANDBOXED);
725 function isSilenced()
727 return $this->hasRole(Profile_role::SILENCED);
732 $this->grantRole(Profile_role::SANDBOXED);
737 $this->revokeRole(Profile_role::SANDBOXED);
742 $this->grantRole(Profile_role::SILENCED);
747 $this->revokeRole(Profile_role::SILENCED);
751 * Does this user have the right to do X?
753 * With our role-based authorization, this is merely a lookup for whether the user
754 * has a particular role. The implementation currently uses a switch statement
755 * to determine if the user has the pre-defined role to exercise the right. Future
756 * implementations may allow per-site roles, and different mappings of roles to rights.
758 * @param $right string Name of the right, usually a constant in class Right
759 * @return boolean whether the user has the right in question
762 function hasRight($right)
765 if ($this->hasRole(Profile_role::DELETED)) {
768 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
771 case Right::DELETEOTHERSNOTICE:
772 case Right::MAKEGROUPADMIN:
773 case Right::SANDBOXUSER:
774 case Right::SILENCEUSER:
775 case Right::DELETEUSER:
776 $result = $this->hasRole(Profile_role::MODERATOR);
778 case Right::CONFIGURESITE:
779 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
781 case Right::GRANTROLE:
782 case Right::REVOKEROLE:
783 $result = $this->hasRole(Profile_role::OWNER);
785 case Right::NEWNOTICE:
786 case Right::NEWMESSAGE:
787 case Right::SUBSCRIBE:
788 $result = !$this->isSilenced();
790 case Right::PUBLICNOTICE:
791 case Right::EMAILONREPLY:
792 case Right::EMAILONSUBSCRIBE:
793 case Right::EMAILONFAVE:
794 $result = !$this->isSandboxed();
804 function hasRepeated($notice_id)
806 // XXX: not really a pkey, but should work
808 $notice = Memcached_DataObject::pkeyGet('Notice',
809 array('profile_id' => $this->id,
810 'repeat_of' => $notice_id));
812 return !empty($notice);
816 * Returns an XML string fragment with limited profile information
817 * as an Atom <author> element.
819 * Assumes that Atom has been previously set up as the base namespace.
823 function asAtomAuthor()
825 $xs = new XMLStringer(true);
827 $xs->elementStart('author');
828 $xs->element('name', null, $this->nickname);
829 $xs->element('uri', null, $this->getUri());
830 $xs->elementEnd('author');
832 return $xs->getString();
836 * Returns an XML string fragment with profile information as an
837 * Activity Streams <activity:actor> element.
839 * Assumes that 'activity' namespace has been previously defined.
843 function asActivityActor()
845 return $this->asActivityNoun('actor');
849 * Returns an XML string fragment with profile information as an
850 * Activity Streams noun object with the given element type.
852 * Assumes that 'activity', 'georss', and 'poco' namespace has been
853 * previously defined.
855 * @param string $element one of 'actor', 'subject', 'object', 'target'
859 function asActivityNoun($element)
861 $noun = ActivityObject::fromProfile($this);
862 return $noun->asString('activity:' . $element);
866 * Returns the best URI for a profile. Plugins may override.
868 * @return string $uri
874 // give plugins a chance to set the URI
875 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
877 // check for a local user first
878 $user = User::staticGet('id', $this->id);
883 // return OMB profile if any
884 $remote = Remote_profile::staticGet('id', $this->id);
885 if (!empty($remote)) {
889 Event::handle('EndGetProfileUri', array($this, &$uri));
895 function hasBlocked($other)
897 $block = Profile_block::get($this->id, $other->id);