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 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, false);
503 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
505 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, true);
508 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
510 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, false);
513 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
515 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, true);
518 function blowFavesCache()
520 $cache = common_memcache();
522 // Faves don't happen chronologically, so we need to blow
524 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
525 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
526 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
527 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
529 $profile = $this->getProfile();
530 $profile->blowFaveCount();
533 function getSelfTags()
535 return Profile_tag::getTags($this->id, $this->id);
538 function setSelfTags($newtags)
540 return Profile_tag::setTags($this->id, $this->id, $newtags);
543 function block($other)
545 // Add a new block record
547 // no blocking (and thus unsubbing from) yourself
549 if ($this->id == $other->id) {
550 common_log(LOG_WARNING,
552 "Profile ID %d (%s) tried to block his or herself.",
560 $block = new Profile_block();
562 // Begin a transaction
564 $block->query('BEGIN');
566 $block->blocker = $this->id;
567 $block->blocked = $other->id;
569 $result = $block->insert();
572 common_log_db_error($block, 'INSERT', __FILE__);
576 // Cancel their subscription, if it exists
578 $otherUser = User::staticGet('id', $other->id);
580 if (!empty($otherUser)) {
581 subs_unsubscribe_to($otherUser, $this->getProfile());
584 $block->query('COMMIT');
589 function unblock($other)
591 // Get the block record
593 $block = Profile_block::get($this->id, $other->id);
599 $result = $block->delete();
602 common_log_db_error($block, 'DELETE', __FILE__);
609 function isMember($group)
611 $profile = $this->getProfile();
612 return $profile->isMember($group);
615 function isAdmin($group)
617 $profile = $this->getProfile();
618 return $profile->isAdmin($group);
621 function getGroups($offset=0, $limit=null)
624 'SELECT user_group.* ' .
625 'FROM user_group JOIN group_member '.
626 'ON user_group.id = group_member.group_id ' .
627 'WHERE group_member.profile_id = %d ' .
628 'ORDER BY group_member.created DESC ';
630 if ($offset>0 && !is_null($limit)) {
632 if (common_config('db','type') == 'pgsql') {
633 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
635 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
640 $groups = new User_group();
642 $cnt = $groups->query(sprintf($qry, $this->id));
647 function getSubscriptions($offset=0, $limit=null)
649 $profile = $this->getProfile();
650 assert(!empty($profile));
651 return $profile->getSubscriptions($offset, $limit);
654 function getSubscribers($offset=0, $limit=null)
656 $profile = $this->getProfile();
657 assert(!empty($profile));
658 return $profile->getSubscribers($offset, $limit);
661 function getTaggedSubscribers($tag, $offset=0, $limit=null)
664 'SELECT profile.* ' .
665 'FROM profile JOIN subscription ' .
666 'ON profile.id = subscription.subscriber ' .
667 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
668 'AND profile_tag.tagger = subscription.subscribed) ' .
669 'WHERE subscription.subscribed = %d ' .
670 "AND profile_tag.tag = '%s' " .
671 'AND subscription.subscribed != subscription.subscriber ' .
672 'ORDER BY subscription.created DESC ';
675 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
678 $profile = new Profile();
680 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
685 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
688 'SELECT profile.* ' .
689 'FROM profile JOIN subscription ' .
690 'ON profile.id = subscription.subscribed ' .
691 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
692 'AND profile_tag.tagger = subscription.subscriber) ' .
693 'WHERE subscription.subscriber = %d ' .
694 "AND profile_tag.tag = '%s' " .
695 'AND subscription.subscribed != subscription.subscriber ' .
696 'ORDER BY subscription.created DESC ';
698 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
700 $profile = new Profile();
702 $profile->query(sprintf($qry, $this->id, $tag));
709 return Design::staticGet('id', $this->design_id);
712 function hasRight($right)
714 $profile = $this->getProfile();
715 return $profile->hasRight($right);
720 $profile = $this->getProfile();
725 $related = array('Fave',
731 Event::handle('UserDeleteRelated', array($this, &$related));
733 foreach ($related as $cls) {
735 $inst->user_id = $this->id;
739 $this->_deleteTags();
740 $this->_deleteBlocks();
745 function _deleteTags()
747 $tag = new Profile_tag();
748 $tag->tagger = $this->id;
752 function _deleteBlocks()
754 $block = new Profile_block();
755 $block->blocker = $this->id;
757 // XXX delete group block? Reset blocker?
760 function hasRole($name)
762 $profile = $this->getProfile();
763 return $profile->hasRole($name);
766 function grantRole($name)
768 $profile = $this->getProfile();
769 return $profile->grantRole($name);
772 function revokeRole($name)
774 $profile = $this->getProfile();
775 return $profile->revokeRole($name);
778 function isSandboxed()
780 $profile = $this->getProfile();
781 return $profile->isSandboxed();
784 function isSilenced()
786 $profile = $this->getProfile();
787 return $profile->isSilenced();
790 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
792 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
794 'user:repeated_by_me:'.$this->id,
795 $offset, $limit, $since_id, $max_id, null);
797 return Notice::getStreamByIds($ids);
800 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id, $since)
802 $notice = new Notice();
804 $notice->selectAdd(); // clears it
805 $notice->selectAdd('id');
807 $notice->profile_id = $this->id;
808 $notice->whereAdd('repeat_of IS NOT NULL');
810 $notice->orderBy('id DESC');
812 if (!is_null($offset)) {
813 $notice->limit($offset, $limit);
816 if ($since_id != 0) {
817 $notice->whereAdd('id > ' . $since_id);
821 $notice->whereAdd('id <= ' . $max_id);
824 if (!is_null($since)) {
825 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
830 if ($notice->find()) {
831 while ($notice->fetch()) {
832 $ids[] = $notice->id;
842 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
844 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
846 'user:repeats_of_me:'.$this->id,
847 $offset, $limit, $since_id, $max_id, null);
849 return Notice::getStreamByIds($ids);
852 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id, $since)
855 'SELECT DISTINCT original.id AS id ' .
856 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
857 'WHERE original.profile_id = ' . $this->id . ' ';
859 if ($since_id != 0) {
860 $qry .= 'AND original.id > ' . $since_id . ' ';
864 $qry .= 'AND original.id <= ' . $max_id . ' ';
867 if (!is_null($since)) {
868 $qry .= 'AND original.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
871 // NOTE: we sort by fave time, not by notice time!
873 $qry .= 'ORDER BY original.id DESC ';
875 if (!is_null($offset)) {
876 $qry .= "LIMIT $limit OFFSET $offset";
881 $notice = new Notice();
883 $notice->query($qry);
885 while ($notice->fetch()) {
886 $ids[] = $notice->id;
895 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
897 throw new Exception("Not implemented since inbox change.");
900 function shareLocation()
902 $cfg = common_config('location', 'share');
904 if ($cfg == 'always') {
906 } else if ($cfg == 'never') {
911 $prefs = User_location_prefs::staticGet('user_id', $this->id);
914 $share = common_config('location', 'sharedefault');
916 $share = $prefs->share_location;
924 static function siteOwner()
926 $owner = self::cacheGet('user:site_owner');
928 if ($owner === false) { // cache miss
930 $pr = new Profile_role();
932 $pr->role = Profile_role::OWNER;
934 $pr->orderBy('created');
938 if ($pr->find(true)) {
939 $owner = User::staticGet('id', $pr->profile_id);
944 self::cacheSet('user:site_owner', $owner);