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')) {
25 * Table Definition for user
28 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
29 require_once 'Validate.php';
31 class User extends Memcached_DataObject
34 /* the code below is auto generated do not remove the above tag */
36 public $__table = 'user'; // table name
37 public $id; // int(4) primary_key not_null
38 public $nickname; // varchar(64) unique_key
39 public $password; // varchar(255)
40 public $email; // varchar(255) unique_key
41 public $incomingemail; // varchar(255) unique_key
42 public $emailnotifysub; // tinyint(1) default_1
43 public $emailnotifyfav; // tinyint(1) default_1
44 public $emailnotifynudge; // tinyint(1) default_1
45 public $emailnotifymsg; // tinyint(1) default_1
46 public $emailnotifyattn; // tinyint(1) default_1
47 public $emailmicroid; // tinyint(1) default_1
48 public $language; // varchar(50)
49 public $timezone; // varchar(50)
50 public $emailpost; // tinyint(1) default_1
51 public $sms; // varchar(64) unique_key
52 public $carrier; // int(4)
53 public $smsnotify; // tinyint(1)
54 public $smsreplies; // tinyint(1)
55 public $smsemail; // varchar(255)
56 public $uri; // varchar(255) unique_key
57 public $autosubscribe; // tinyint(1)
58 public $urlshorteningservice; // varchar(50) default_ur1.ca
59 public $inboxed; // tinyint(1)
60 public $design_id; // int(4)
61 public $viewdesigns; // tinyint(1) default_1
62 public $created; // datetime() not_null
63 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
66 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
68 /* the code above is auto generated do not remove the tag below */
73 return Profile::staticGet('id', $this->id);
76 function isSubscribed($other)
78 assert(!is_null($other));
79 // XXX: cache results of this query
80 $sub = Subscription::pkeyGet(array('subscriber' => $this->id,
81 'subscribed' => $other->id));
82 return (is_null($sub)) ? false : true;
85 // 'update' won't write key columns, so we have to do it ourselves.
87 function updateKeys(&$orig)
90 foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
91 if (strcmp($this->$k, $orig->$k) != 0) {
92 $parts[] = $k . ' = ' . $this->_quote($this->$k);
95 if (count($parts) == 0) {
99 $toupdate = implode(', ', $parts);
101 $table = common_database_tablename($this->tableName());
102 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
103 ' WHERE id = ' . $this->id;
105 $result = $this->query($qry);
112 static function allowed_nickname($nickname)
114 // XXX: should already be validated for size, content, etc.
115 $blacklist = common_config('nickname', 'blacklist');
117 //all directory and file names should be blacklisted
118 $d = dir(INSTALLDIR);
119 while (false !== ($entry = $d->read())) {
124 //all top level names in the router should be blacklisted
125 $router = Router::get();
126 foreach(array_keys($router->m->getPaths()) as $path){
127 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
128 $blacklist[]=$matches[1];
131 return !in_array($nickname, $blacklist);
134 function getCurrentNotice($dt=null)
136 $profile = $this->getProfile();
140 return $profile->getCurrentNotice($dt);
143 function getCarrier()
145 return Sms_carrier::staticGet('id', $this->carrier);
148 function subscribeTo($other)
150 $sub = new Subscription();
151 $sub->subscriber = $this->id;
152 $sub->subscribed = $other->id;
154 $sub->created = common_sql_now(); // current time
156 if (!$sub->insert()) {
163 function hasBlocked($other)
166 $block = Profile_block::get($this->id, $other->id);
168 if (is_null($block)) {
179 * Register a new user account and profile and set up default subscriptions.
180 * If a new-user welcome message is configured, this will be sent.
182 * @param array $fields associative array of optional properties
185 * bool 'email_confirmed' pass true to mark email as pre-confirmed
188 * string 'location' informal string description of geolocation
189 * float 'lat' decimal latitude for geolocation
190 * float 'lon' decimal longitude for geolocation
191 * int 'location_id' geoname identifier
192 * int 'location_ns' geoname namespace to interpret location_id
193 * string 'nickname' REQUIRED
194 * string 'password' (may be missing for eg OpenID registrations)
195 * string 'code' invite code
196 * ?string 'uri' permalink to notice; defaults to local notice URL
197 * @return mixed User object or false on failure
199 static function register($fields) {
201 // MAGICALLY put fields into current scope
205 $profile = new Profile();
209 $email = common_canonical_email($email);
212 $nickname = common_canonical_nickname($nickname);
213 $profile->nickname = $nickname;
214 if(! User::allowed_nickname($nickname)){
215 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
218 $profile->profileurl = common_profile_url($nickname);
220 if (!empty($fullname)) {
221 $profile->fullname = $fullname;
223 if (!empty($homepage)) {
224 $profile->homepage = $homepage;
227 $profile->bio = $bio;
229 if (!empty($location)) {
230 $profile->location = $location;
232 $loc = Location::fromName($location);
235 $profile->lat = $loc->lat;
236 $profile->lon = $loc->lon;
237 $profile->location_id = $loc->location_id;
238 $profile->location_ns = $loc->location_ns;
242 $profile->created = common_sql_now();
246 $user->nickname = $nickname;
248 // Users who respond to invite email have proven their ownership of that address
251 $invite = Invitation::staticGet($code);
252 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
253 $user->email = $invite->address;
257 if(isset($email_confirmed) && $email_confirmed) {
258 $user->email = $email;
261 // This flag is ignored but still set to 1
265 $user->created = common_sql_now();
267 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
269 $profile->query('BEGIN');
271 $id = $profile->insert();
274 common_log_db_error($profile, 'INSERT', __FILE__);
279 $user->uri = common_user_uri($user);
280 if (!empty($password)) { // may not have a password for OpenID users
281 $user->password = common_munge_password($password, $id);
284 $result = $user->insert();
287 common_log_db_error($user, 'INSERT', __FILE__);
291 // Everyone gets an inbox
293 $inbox = new Inbox();
295 $inbox->user_id = $user->id;
296 $inbox->notice_ids = '';
298 $result = $inbox->insert();
301 common_log_db_error($inbox, 'INSERT', __FILE__);
305 // Everyone is subscribed to themself
307 $subscription = new Subscription();
308 $subscription->subscriber = $user->id;
309 $subscription->subscribed = $user->id;
310 $subscription->created = $user->created;
312 $result = $subscription->insert();
315 common_log_db_error($subscription, 'INSERT', __FILE__);
319 if (!empty($email) && !$user->email) {
321 $confirm = new Confirm_address();
322 $confirm->code = common_confirmation_code(128);
323 $confirm->user_id = $user->id;
324 $confirm->address = $email;
325 $confirm->address_type = 'email';
327 $result = $confirm->insert();
330 common_log_db_error($confirm, 'INSERT', __FILE__);
335 if (!empty($code) && $user->email) {
336 $user->emailChanged();
339 // Default system subscription
341 $defnick = common_config('newuser', 'default');
343 if (!empty($defnick)) {
344 $defuser = User::staticGet('nickname', $defnick);
345 if (empty($defuser)) {
346 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
349 $defsub = new Subscription();
350 $defsub->subscriber = $user->id;
351 $defsub->subscribed = $defuser->id;
352 $defsub->created = $user->created;
354 $result = $defsub->insert();
357 common_log_db_error($defsub, 'INSERT', __FILE__);
363 $profile->query('COMMIT');
365 if (!empty($email) && !$user->email) {
366 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
371 $welcome = common_config('newuser', 'welcome');
373 if (!empty($welcome)) {
374 $welcomeuser = User::staticGet('nickname', $welcome);
375 if (empty($welcomeuser)) {
376 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
379 $notice = Notice::saveNew($welcomeuser->id,
380 sprintf(_('Welcome to %1$s, @%2$s!'),
381 common_config('site', 'name'),
388 Event::handle('EndUserRegister', array(&$profile, &$user));
394 // Things we do when the email changes
396 function emailChanged()
399 $invites = new Invitation();
400 $invites->address = $this->email;
401 $invites->address_type = 'email';
403 if ($invites->find()) {
404 while ($invites->fetch()) {
405 $other = User::staticGet($invites->user_id);
406 subs_subscribe_to($other, $this);
411 function hasFave($notice)
413 $cache = common_memcache();
415 // XXX: Kind of a hack.
418 // This is the stream of favorite notices, in rev chron
419 // order. This forces it into cache.
421 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
423 // If it's in the list, then it's a fave
425 if (in_array($notice->id, $ids)) {
429 // If we're not past the end of the cache window,
430 // then the cache has all available faves, so this one
433 if (count($ids) < NOTICE_CACHE_WINDOW) {
437 // Otherwise, cache doesn't have all faves;
438 // fall through to the default
441 $fave = Fave::pkeyGet(array('user_id' => $this->id,
442 'notice_id' => $notice->id));
443 return ((is_null($fave)) ? false : true);
446 function mutuallySubscribed($other)
448 return $this->isSubscribed($other) &&
449 $other->isSubscribed($this);
452 function mutuallySubscribedUsers()
454 // 3-way join; probably should get cached
455 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
456 $qry = "SELECT $UT.* " .
457 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
458 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
459 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
460 "ORDER BY $UT.nickname";
462 $user->query(sprintf($qry, $this->id, $this->id));
467 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
469 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
470 return Notice::getStreamByIds($ids);
473 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
474 $profile = $this->getProfile();
478 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
482 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
484 $profile = $this->getProfile();
488 return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
492 function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
494 $ids = Fave::stream($this->id, $offset, $limit, $own);
495 return Notice::getStreamByIds($ids);
498 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
500 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
501 return Notice::getStreamByIds($ids);
504 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
506 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
507 return Notice::getStreamByIds($ids);
510 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
512 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
514 return Notice::getStreamByIds($ids);
517 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
519 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
521 return Notice::getStreamByIds($ids);
524 function blowFavesCache()
526 $cache = common_memcache();
528 // Faves don't happen chronologically, so we need to blow
530 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
531 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
532 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
533 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
535 $profile = $this->getProfile();
536 $profile->blowFaveCount();
539 function getSelfTags()
541 return Profile_tag::getTags($this->id, $this->id);
544 function setSelfTags($newtags)
546 return Profile_tag::setTags($this->id, $this->id, $newtags);
549 function block($other)
551 // Add a new block record
553 // no blocking (and thus unsubbing from) yourself
555 if ($this->id == $other->id) {
556 common_log(LOG_WARNING,
558 "Profile ID %d (%s) tried to block his or herself.",
566 $block = new Profile_block();
568 // Begin a transaction
570 $block->query('BEGIN');
572 $block->blocker = $this->id;
573 $block->blocked = $other->id;
575 $result = $block->insert();
578 common_log_db_error($block, 'INSERT', __FILE__);
582 // Cancel their subscription, if it exists
584 $otherUser = User::staticGet('id', $other->id);
586 if (!empty($otherUser)) {
587 subs_unsubscribe_to($otherUser, $this->getProfile());
590 $block->query('COMMIT');
595 function unblock($other)
597 // Get the block record
599 $block = Profile_block::get($this->id, $other->id);
605 $result = $block->delete();
608 common_log_db_error($block, 'DELETE', __FILE__);
615 function isMember($group)
617 $profile = $this->getProfile();
618 return $profile->isMember($group);
621 function isAdmin($group)
623 $profile = $this->getProfile();
624 return $profile->isAdmin($group);
627 function getGroups($offset=0, $limit=null)
630 'SELECT user_group.* ' .
631 'FROM user_group JOIN group_member '.
632 'ON user_group.id = group_member.group_id ' .
633 'WHERE group_member.profile_id = %d ' .
634 'ORDER BY group_member.created DESC ';
636 if ($offset>0 && !is_null($limit)) {
638 if (common_config('db','type') == 'pgsql') {
639 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
641 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
646 $groups = new User_group();
648 $cnt = $groups->query(sprintf($qry, $this->id));
653 function getSubscriptions($offset=0, $limit=null)
655 $profile = $this->getProfile();
656 assert(!empty($profile));
657 return $profile->getSubscriptions($offset, $limit);
660 function getSubscribers($offset=0, $limit=null)
662 $profile = $this->getProfile();
663 assert(!empty($profile));
664 return $profile->getSubscribers($offset, $limit);
667 function getTaggedSubscribers($tag, $offset=0, $limit=null)
670 'SELECT profile.* ' .
671 'FROM profile JOIN subscription ' .
672 'ON profile.id = subscription.subscriber ' .
673 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
674 'AND profile_tag.tagger = subscription.subscribed) ' .
675 'WHERE subscription.subscribed = %d ' .
676 "AND profile_tag.tag = '%s' " .
677 'AND subscription.subscribed != subscription.subscriber ' .
678 'ORDER BY subscription.created DESC ';
681 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
684 $profile = new Profile();
686 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
691 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
694 'SELECT profile.* ' .
695 'FROM profile JOIN subscription ' .
696 'ON profile.id = subscription.subscribed ' .
697 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
698 'AND profile_tag.tagger = subscription.subscriber) ' .
699 'WHERE subscription.subscriber = %d ' .
700 "AND profile_tag.tag = '%s' " .
701 'AND subscription.subscribed != subscription.subscriber ' .
702 'ORDER BY subscription.created DESC ';
704 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
706 $profile = new Profile();
708 $profile->query(sprintf($qry, $this->id, $tag));
715 return Design::staticGet('id', $this->design_id);
718 function hasRight($right)
720 $profile = $this->getProfile();
721 return $profile->hasRight($right);
726 $profile = $this->getProfile();
731 $related = array('Fave',
737 Event::handle('UserDeleteRelated', array($this, &$related));
739 foreach ($related as $cls) {
741 $inst->user_id = $this->id;
745 $this->_deleteTags();
746 $this->_deleteBlocks();
751 function _deleteTags()
753 $tag = new Profile_tag();
754 $tag->tagger = $this->id;
758 function _deleteBlocks()
760 $block = new Profile_block();
761 $block->blocker = $this->id;
763 // XXX delete group block? Reset blocker?
766 function hasRole($name)
768 $profile = $this->getProfile();
769 return $profile->hasRole($name);
772 function grantRole($name)
774 $profile = $this->getProfile();
775 return $profile->grantRole($name);
778 function revokeRole($name)
780 $profile = $this->getProfile();
781 return $profile->revokeRole($name);
784 function isSandboxed()
786 $profile = $this->getProfile();
787 return $profile->isSandboxed();
790 function isSilenced()
792 $profile = $this->getProfile();
793 return $profile->isSilenced();
796 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
798 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
800 'user:repeated_by_me:'.$this->id,
801 $offset, $limit, $since_id, $max_id, null);
803 return Notice::getStreamByIds($ids);
806 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id, $since)
808 $notice = new Notice();
810 $notice->selectAdd(); // clears it
811 $notice->selectAdd('id');
813 $notice->profile_id = $this->id;
814 $notice->whereAdd('repeat_of IS NOT NULL');
816 $notice->orderBy('id DESC');
818 if (!is_null($offset)) {
819 $notice->limit($offset, $limit);
822 if ($since_id != 0) {
823 $notice->whereAdd('id > ' . $since_id);
827 $notice->whereAdd('id <= ' . $max_id);
830 if (!is_null($since)) {
831 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
836 if ($notice->find()) {
837 while ($notice->fetch()) {
838 $ids[] = $notice->id;
848 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
850 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
852 'user:repeats_of_me:'.$this->id,
853 $offset, $limit, $since_id, $max_id, null);
855 return Notice::getStreamByIds($ids);
858 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id, $since)
861 'SELECT DISTINCT original.id AS id ' .
862 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
863 'WHERE original.profile_id = ' . $this->id . ' ';
865 if ($since_id != 0) {
866 $qry .= 'AND original.id > ' . $since_id . ' ';
870 $qry .= 'AND original.id <= ' . $max_id . ' ';
873 if (!is_null($since)) {
874 $qry .= 'AND original.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
877 // NOTE: we sort by fave time, not by notice time!
879 $qry .= 'ORDER BY original.id DESC ';
881 if (!is_null($offset)) {
882 $qry .= "LIMIT $limit OFFSET $offset";
887 $notice = new Notice();
889 $notice->query($qry);
891 while ($notice->fetch()) {
892 $ids[] = $notice->id;
901 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
903 throw new Exception("Not implemented since inbox change.");
906 function shareLocation()
908 $cfg = common_config('location', 'share');
910 if ($cfg == 'always') {
912 } else if ($cfg == 'never') {
917 $prefs = User_location_prefs::staticGet('user_id', $this->id);
920 $share = common_config('location', 'sharedefault');
922 $share = $prefs->share_location;
930 static function siteOwner()
932 $owner = self::cacheGet('user:site_owner');
934 if ($owner === false) { // cache miss
936 $pr = new Profile_role();
938 $pr->role = Profile_role::OWNER;
940 $pr->orderBy('created');
944 if ($pr->find(true)) {
945 $owner = User::staticGet('id', $pr->profile_id);
950 self::cacheSet('user:site_owner', $owner);