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;
150 # Get latest notice on or before date; default now
151 function getCurrentNotice($dt=null)
153 $notice = new Notice();
154 $notice->profile_id = $this->id;
156 $notice->whereAdd('created < "' . $dt . '"');
158 $notice->orderBy('created DESC, notice.id DESC');
160 if ($notice->find(true)) {
166 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, $since=null)
168 $ids = Notice::stream(array($this, '_streamTaggedDirect'),
170 'profile:notice_ids_tagged:' . $this->id . ':' . $tag,
171 $offset, $limit, $since_id, $max_id, $since);
172 return Notice::getStreamByIds($ids);
175 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, $since=null)
177 // XXX: I'm not sure this is going to be any faster. It probably isn't.
178 $ids = Notice::stream(array($this, '_streamDirect'),
180 'profile:notice_ids:' . $this->id,
181 $offset, $limit, $since_id, $max_id, $since);
183 return Notice::getStreamByIds($ids);
186 function _streamTaggedDirect($tag, $offset, $limit, $since_id, $max_id, $since)
188 // XXX It would be nice to do this without a join
190 $notice = new Notice();
193 "select id from notice join notice_tag on id=notice_id where tag='".
194 $notice->escape($tag) .
195 "' and profile_id=" . $notice->escape($this->id);
197 if ($since_id != 0) {
198 $query .= " and id > $since_id";
202 $query .= " and id < $max_id";
205 if (!is_null($since)) {
206 $query .= " and created > '" . date('Y-m-d H:i:s', $since) . "'";
209 $query .= ' order by id DESC';
211 if (!is_null($offset)) {
212 $query .= " LIMIT $limit OFFSET $offset";
215 $notice->query($query);
219 while ($notice->fetch()) {
220 $ids[] = $notice->id;
226 function _streamDirect($offset, $limit, $since_id, $max_id, $since = null)
228 $notice = new Notice();
230 $notice->profile_id = $this->id;
232 $notice->selectAdd();
233 $notice->selectAdd('id');
235 if ($since_id != 0) {
236 $notice->whereAdd('id > ' . $since_id);
240 $notice->whereAdd('id <= ' . $max_id);
243 if (!is_null($since)) {
244 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
247 $notice->orderBy('id DESC');
249 if (!is_null($offset)) {
250 $notice->limit($offset, $limit);
255 if ($notice->find()) {
256 while ($notice->fetch()) {
257 $ids[] = $notice->id;
264 function isMember($group)
266 $mem = new Group_member();
268 $mem->group_id = $group->id;
269 $mem->profile_id = $this->id;
278 function isAdmin($group)
280 $mem = new Group_member();
282 $mem->group_id = $group->id;
283 $mem->profile_id = $this->id;
293 function avatarUrl($size=AVATAR_PROFILE_SIZE)
295 $avatar = $this->getAvatar($size);
297 return $avatar->displayUrl();
299 return Avatar::defaultImage($size);
303 function getSubscriptions($offset=0, $limit=null)
306 'SELECT profile.* ' .
307 'FROM profile JOIN subscription ' .
308 'ON profile.id = subscription.subscribed ' .
309 'WHERE subscription.subscriber = %d ' .
310 'AND subscription.subscribed != subscription.subscriber ' .
311 'ORDER BY subscription.created DESC ';
313 if ($offset>0 && !is_null($limit)){
314 if (common_config('db','type') == 'pgsql') {
315 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
317 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
321 $profile = new Profile();
323 $profile->query(sprintf($qry, $this->id));
328 function getSubscribers($offset=0, $limit=null)
331 'SELECT profile.* ' .
332 'FROM profile JOIN subscription ' .
333 'ON profile.id = subscription.subscriber ' .
334 'WHERE subscription.subscribed = %d ' .
335 'AND subscription.subscribed != subscription.subscriber ' .
336 'ORDER BY subscription.created DESC ';
338 if ($offset>0 && !is_null($limit)){
340 if (common_config('db','type') == 'pgsql') {
341 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
343 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
348 $profile = new Profile();
350 $cnt = $profile->query(sprintf($qry, $this->id));
355 function getApplications($offset = 0, $limit = null)
359 'FROM oauth_application_user u, oauth_application a ' .
360 'WHERE u.profile_id = %d ' .
361 'AND a.id = u.application_id ' .
362 'AND u.access_type > 0 ' .
363 'ORDER BY u.created DESC ';
366 if (common_config('db','type') == 'pgsql') {
367 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
369 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
373 $application = new Oauth_application();
375 $cnt = $application->query(sprintf($qry, $this->id));
380 function subscriptionCount()
382 $c = common_memcache();
385 $cnt = $c->get(common_cache_key('profile:subscription_count:'.$this->id));
386 if (is_integer($cnt)) {
391 $sub = new Subscription();
392 $sub->subscriber = $this->id;
394 $cnt = (int) $sub->count('distinct subscribed');
396 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
399 $c->set(common_cache_key('profile:subscription_count:'.$this->id), $cnt);
405 function subscriberCount()
407 $c = common_memcache();
409 $cnt = $c->get(common_cache_key('profile:subscriber_count:'.$this->id));
410 if (is_integer($cnt)) {
415 $sub = new Subscription();
416 $sub->subscribed = $this->id;
418 $cnt = (int) $sub->count('distinct subscriber');
420 $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
423 $c->set(common_cache_key('profile:subscriber_count:'.$this->id), $cnt);
431 $c = common_memcache();
433 $cnt = $c->get(common_cache_key('profile:fave_count:'.$this->id));
434 if (is_integer($cnt)) {
440 $faves->user_id = $this->id;
441 $cnt = (int) $faves->count('distinct notice_id');
444 $c->set(common_cache_key('profile:fave_count:'.$this->id), $cnt);
450 function noticeCount()
452 $c = common_memcache();
455 $cnt = $c->get(common_cache_key('profile:notice_count:'.$this->id));
456 if (is_integer($cnt)) {
461 $notices = new Notice();
462 $notices->profile_id = $this->id;
463 $cnt = (int) $notices->count('distinct id');
466 $c->set(common_cache_key('profile:notice_count:'.$this->id), $cnt);
472 function blowSubscriberCount()
474 $c = common_memcache();
476 $c->delete(common_cache_key('profile:subscriber_count:'.$this->id));
480 function blowSubscriptionCount()
482 $c = common_memcache();
484 $c->delete(common_cache_key('profile:subscription_count:'.$this->id));
488 function blowFaveCount()
490 $c = common_memcache();
492 $c->delete(common_cache_key('profile:fave_count:'.$this->id));
496 function blowNoticeCount()
498 $c = common_memcache();
500 $c->delete(common_cache_key('profile:notice_count:'.$this->id));
504 static function maxBio()
506 $biolimit = common_config('profile', 'biolimit');
507 // null => use global limit (distinct from 0!)
508 if (is_null($biolimit)) {
509 $biolimit = common_config('site', 'textlimit');
514 static function bioTooLong($bio)
516 $biolimit = self::maxBio();
517 return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
522 $this->_deleteNotices();
523 $this->_deleteSubscriptions();
524 $this->_deleteMessages();
525 $this->_deleteTags();
526 $this->_deleteBlocks();
528 $related = array('Avatar',
532 Event::handle('ProfileDeleteRelated', array($this, &$related));
534 foreach ($related as $cls) {
536 $inst->profile_id = $this->id;
543 function _deleteNotices()
545 $notice = new Notice();
546 $notice->profile_id = $this->id;
548 if ($notice->find()) {
549 while ($notice->fetch()) {
550 $other = clone($notice);
556 function _deleteSubscriptions()
558 $sub = new Subscription();
559 $sub->subscriber = $this->id;
562 $subd = new Subscription();
563 $subd->subscribed = $this->id;
567 function _deleteMessages()
569 $msg = new Message();
570 $msg->from_profile = $this->id;
573 $msg = new Message();
574 $msg->to_profile = $this->id;
578 function _deleteTags()
580 $tag = new Profile_tag();
581 $tag->tagged = $this->id;
585 function _deleteBlocks()
587 $block = new Profile_block();
588 $block->blocked = $this->id;
591 $block = new Group_block();
592 $block->blocked = $this->id;
596 // XXX: identical to Notice::getLocation.
598 function getLocation()
602 if (!empty($this->location_id) && !empty($this->location_ns)) {
603 $location = Location::fromId($this->location_id, $this->location_ns);
606 if (is_null($location)) { // no ID, or Location::fromId() failed
607 if (!empty($this->lat) && !empty($this->lon)) {
608 $location = Location::fromLatLon($this->lat, $this->lon);
612 if (is_null($location)) { // still haven't found it!
613 if (!empty($this->location)) {
614 $location = Location::fromName($this->location);
621 function hasRole($name)
624 if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
625 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
627 $has_role = !empty($role);
628 Event::handle('EndHasRole', array($this, $name, $has_role));
633 function grantRole($name)
635 $role = new Profile_role();
637 $role->profile_id = $this->id;
639 $role->created = common_sql_now();
641 $result = $role->insert();
644 common_log_db_error($role, 'INSERT', __FILE__);
651 function revokeRole($name)
653 $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
657 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
660 $result = $role->delete();
663 common_log_db_error($role, 'DELETE', __FILE__);
664 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
670 function isSandboxed()
672 return $this->hasRole(Profile_role::SANDBOXED);
675 function isSilenced()
677 return $this->hasRole(Profile_role::SILENCED);
682 $this->grantRole(Profile_role::SANDBOXED);
687 $this->revokeRole(Profile_role::SANDBOXED);
692 $this->grantRole(Profile_role::SILENCED);
697 $this->revokeRole(Profile_role::SILENCED);
701 * Does this user have the right to do X?
703 * With our role-based authorization, this is merely a lookup for whether the user
704 * has a particular role. The implementation currently uses a switch statement
705 * to determine if the user has the pre-defined role to exercise the right. Future
706 * implementations may allow per-site roles, and different mappings of roles to rights.
708 * @param $right string Name of the right, usually a constant in class Right
709 * @return boolean whether the user has the right in question
712 function hasRight($right)
715 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
718 case Right::DELETEOTHERSNOTICE:
719 case Right::MAKEGROUPADMIN:
720 case Right::SANDBOXUSER:
721 case Right::SILENCEUSER:
722 case Right::DELETEUSER:
723 $result = $this->hasRole(Profile_role::MODERATOR);
725 case Right::CONFIGURESITE:
726 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
728 case Right::NEWNOTICE:
729 case Right::NEWMESSAGE:
730 case Right::SUBSCRIBE:
731 $result = !$this->isSilenced();
733 case Right::PUBLICNOTICE:
734 case Right::EMAILONREPLY:
735 case Right::EMAILONSUBSCRIBE:
736 case Right::EMAILONFAVE:
737 $result = !$this->isSandboxed();
747 function hasRepeated($notice_id)
749 // XXX: not really a pkey, but should work
751 $notice = Memcached_DataObject::pkeyGet('Notice',
752 array('profile_id' => $this->id,
753 'repeat_of' => $notice_id));
755 return !empty($notice);
759 * Returns an XML string fragment with limited profile information
760 * as an Atom <author> element.
762 * Assumes that Atom has been previously set up as the base namespace.
766 function asAtomAuthor()
768 $xs = new XMLStringer(true);
770 $xs->elementStart('author');
771 $xs->element('name', null, $this->nickname);
772 $xs->element('uri', null, $this->getUri());
773 $xs->elementEnd('author');
775 return $xs->getString();
779 * Returns an XML string fragment with profile information as an
780 * Activity Streams <activity:actor> element.
782 * Assumes that 'activity' namespace has been previously defined.
786 function asActivityActor()
788 return $this->asActivityNoun('actor');
792 * Returns an XML string fragment with profile information as an
793 * Activity Streams noun object with the given element type.
795 * Assumes that 'activity' namespace has been previously defined.
797 * @param string $element one of 'actor', 'subject', 'object', 'target'
800 function asActivityNoun($element)
802 $xs = new XMLStringer(true);
804 $xs->elementStart('activity:' . $element);
806 'activity:object-type',
808 'http://activitystrea.ms/schema/1.0/person'
815 $xs->element('title', null, $this->getBestName());
817 $avatar = $this->getAvatar(AVATAR_PROFILE_SIZE);
821 'type' => empty($avatar) ? 'image/png' : $avatar->mediatype,
823 'href' => empty($avatar)
824 ? Avatar::defaultImage(AVATAR_PROFILE_SIZE)
825 : $avatar->displayUrl()
830 $xs->elementEnd('activity:' . $element);
832 return $xs->getString();
836 * Returns the best URI for a profile. Plugins may override.
838 * @return string $uri
844 // check for a local user first
845 $user = User::staticGet('id', $this->id);
848 $uri = common_local_url(
850 array('id' => $user->id)
854 // give plugins a chance to set the URI
855 if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
857 // return OMB profile if any
858 $remote = Remote_profile::staticGet('id', $this->id);
860 if (!empty($remote)) {
864 Event::handle('EndGetProfileUri', array($this, &$uri));
871 function hasBlocked($other)
873 $block = Profile_block::get($this->id, $other->id);