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 $jabber; // varchar(255) unique_key
52 public $jabbernotify; // tinyint(1)
53 public $jabberreplies; // tinyint(1)
54 public $jabbermicroid; // tinyint(1) default_1
55 public $updatefrompresence; // tinyint(1)
56 public $sms; // varchar(64) unique_key
57 public $carrier; // int(4)
58 public $smsnotify; // tinyint(1)
59 public $smsreplies; // tinyint(1)
60 public $smsemail; // varchar(255)
61 public $uri; // varchar(255) unique_key
62 public $autosubscribe; // tinyint(1)
63 public $urlshorteningservice; // varchar(50) default_ur1.ca
64 public $inboxed; // tinyint(1)
65 public $design_id; // int(4)
66 public $viewdesigns; // tinyint(1) default_1
67 public $created; // datetime() not_null
68 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
71 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
73 /* the code above is auto generated do not remove the tag below */
78 return Profile::staticGet('id', $this->id);
81 function isSubscribed($other)
83 return Subscription::exists($this->getProfile(), $other);
86 // 'update' won't write key columns, so we have to do it ourselves.
88 function updateKeys(&$orig)
91 foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
92 if (strcmp($this->$k, $orig->$k) != 0) {
93 $parts[] = $k . ' = ' . $this->_quote($this->$k);
96 if (count($parts) == 0) {
100 $toupdate = implode(', ', $parts);
102 $table = common_database_tablename($this->tableName());
103 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
104 ' WHERE id = ' . $this->id;
106 $result = $this->query($qry);
113 static function allowed_nickname($nickname)
115 // XXX: should already be validated for size, content, etc.
116 $blacklist = common_config('nickname', 'blacklist');
118 //all directory and file names should be blacklisted
119 $d = dir(INSTALLDIR);
120 while (false !== ($entry = $d->read())) {
125 //all top level names in the router should be blacklisted
126 $router = Router::get();
127 foreach(array_keys($router->m->getPaths()) as $path){
128 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
129 $blacklist[]=$matches[1];
132 return !in_array($nickname, $blacklist);
135 function getCurrentNotice($dt=null)
137 $profile = $this->getProfile();
141 return $profile->getCurrentNotice($dt);
144 function getCarrier()
146 return Sms_carrier::staticGet('id', $this->carrier);
149 function subscribeTo($other)
151 $sub = new Subscription();
152 $sub->subscriber = $this->id;
153 $sub->subscribed = $other->id;
155 $sub->created = common_sql_now(); // current time
157 if (!$sub->insert()) {
164 function hasBlocked($other)
166 $profile = $this->getProfile();
167 return $profile->hasBlocked($other);
171 * Register a new user account and profile and set up default subscriptions.
172 * If a new-user welcome message is configured, this will be sent.
174 * @param array $fields associative array of optional properties
177 * bool 'email_confirmed' pass true to mark email as pre-confirmed
180 * string 'location' informal string description of geolocation
181 * float 'lat' decimal latitude for geolocation
182 * float 'lon' decimal longitude for geolocation
183 * int 'location_id' geoname identifier
184 * int 'location_ns' geoname namespace to interpret location_id
185 * string 'nickname' REQUIRED
186 * string 'password' (may be missing for eg OpenID registrations)
187 * string 'code' invite code
188 * ?string 'uri' permalink to notice; defaults to local notice URL
189 * @return mixed User object or false on failure
191 static function register($fields) {
193 // MAGICALLY put fields into current scope
197 $profile = new Profile();
201 $email = common_canonical_email($email);
204 $nickname = common_canonical_nickname($nickname);
205 $profile->nickname = $nickname;
206 if(! User::allowed_nickname($nickname)){
207 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
210 $profile->profileurl = common_profile_url($nickname);
212 if (!empty($fullname)) {
213 $profile->fullname = $fullname;
215 if (!empty($homepage)) {
216 $profile->homepage = $homepage;
219 $profile->bio = $bio;
221 if (!empty($location)) {
222 $profile->location = $location;
224 $loc = Location::fromName($location);
227 $profile->lat = $loc->lat;
228 $profile->lon = $loc->lon;
229 $profile->location_id = $loc->location_id;
230 $profile->location_ns = $loc->location_ns;
234 $profile->created = common_sql_now();
238 $user->nickname = $nickname;
240 // Users who respond to invite email have proven their ownership of that address
243 $invite = Invitation::staticGet($code);
244 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
245 $user->email = $invite->address;
249 if(isset($email_confirmed) && $email_confirmed) {
250 $user->email = $email;
253 // This flag is ignored but still set to 1
257 $user->created = common_sql_now();
259 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
261 $profile->query('BEGIN');
263 $id = $profile->insert();
266 common_log_db_error($profile, 'INSERT', __FILE__);
271 $user->uri = common_user_uri($user);
272 if (!empty($password)) { // may not have a password for OpenID users
273 $user->password = common_munge_password($password, $id);
276 $result = $user->insert();
279 common_log_db_error($user, 'INSERT', __FILE__);
283 // Everyone gets an inbox
285 $inbox = new Inbox();
287 $inbox->user_id = $user->id;
288 $inbox->notice_ids = '';
290 $result = $inbox->insert();
293 common_log_db_error($inbox, 'INSERT', __FILE__);
297 // Everyone is subscribed to themself
299 $subscription = new Subscription();
300 $subscription->subscriber = $user->id;
301 $subscription->subscribed = $user->id;
302 $subscription->created = $user->created;
304 $result = $subscription->insert();
307 common_log_db_error($subscription, 'INSERT', __FILE__);
311 if (!empty($email) && !$user->email) {
313 $confirm = new Confirm_address();
314 $confirm->code = common_confirmation_code(128);
315 $confirm->user_id = $user->id;
316 $confirm->address = $email;
317 $confirm->address_type = 'email';
319 $result = $confirm->insert();
322 common_log_db_error($confirm, 'INSERT', __FILE__);
327 if (!empty($code) && $user->email) {
328 $user->emailChanged();
331 // Default system subscription
333 $defnick = common_config('newuser', 'default');
335 if (!empty($defnick)) {
336 $defuser = User::staticGet('nickname', $defnick);
337 if (empty($defuser)) {
338 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
341 $defsub = new Subscription();
342 $defsub->subscriber = $user->id;
343 $defsub->subscribed = $defuser->id;
344 $defsub->created = $user->created;
346 $result = $defsub->insert();
349 common_log_db_error($defsub, 'INSERT', __FILE__);
355 $profile->query('COMMIT');
357 if (!empty($email) && !$user->email) {
358 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
363 $welcome = common_config('newuser', 'welcome');
365 if (!empty($welcome)) {
366 $welcomeuser = User::staticGet('nickname', $welcome);
367 if (empty($welcomeuser)) {
368 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
371 $notice = Notice::saveNew($welcomeuser->id,
372 sprintf(_('Welcome to %1$s, @%2$s!'),
373 common_config('site', 'name'),
380 Event::handle('EndUserRegister', array(&$profile, &$user));
386 // Things we do when the email changes
388 function emailChanged()
391 $invites = new Invitation();
392 $invites->address = $this->email;
393 $invites->address_type = 'email';
395 if ($invites->find()) {
396 while ($invites->fetch()) {
397 $other = User::staticGet($invites->user_id);
398 subs_subscribe_to($other, $this);
403 function hasFave($notice)
405 $cache = common_memcache();
407 // XXX: Kind of a hack.
410 // This is the stream of favorite notices, in rev chron
411 // order. This forces it into cache.
413 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
415 // If it's in the list, then it's a fave
417 if (in_array($notice->id, $ids)) {
421 // If we're not past the end of the cache window,
422 // then the cache has all available faves, so this one
425 if (count($ids) < NOTICE_CACHE_WINDOW) {
429 // Otherwise, cache doesn't have all faves;
430 // fall through to the default
433 $fave = Fave::pkeyGet(array('user_id' => $this->id,
434 'notice_id' => $notice->id));
435 return ((is_null($fave)) ? false : true);
438 function mutuallySubscribed($other)
440 return $this->isSubscribed($other) &&
441 $other->isSubscribed($this);
444 function mutuallySubscribedUsers()
446 // 3-way join; probably should get cached
447 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
448 $qry = "SELECT $UT.* " .
449 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
450 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
451 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
452 "ORDER BY $UT.nickname";
454 $user->query(sprintf($qry, $this->id, $this->id));
459 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
461 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
462 return Notice::getStreamByIds($ids);
465 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
466 $profile = $this->getProfile();
470 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
474 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
476 $profile = $this->getProfile();
480 return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
484 function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
486 $ids = Fave::stream($this->id, $offset, $limit, $own);
487 return Notice::getStreamByIds($ids);
490 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
492 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, false);
495 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
497 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, true);
500 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
502 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, false);
505 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
507 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, true);
510 function blowFavesCache()
512 $cache = common_memcache();
514 // Faves don't happen chronologically, so we need to blow
516 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
517 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
518 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
519 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
521 $profile = $this->getProfile();
522 $profile->blowFaveCount();
525 function getSelfTags()
527 return Profile_tag::getTags($this->id, $this->id);
530 function setSelfTags($newtags)
532 return Profile_tag::setTags($this->id, $this->id, $newtags);
535 function block($other)
537 // Add a new block record
539 // no blocking (and thus unsubbing from) yourself
541 if ($this->id == $other->id) {
542 common_log(LOG_WARNING,
544 "Profile ID %d (%s) tried to block his or herself.",
552 $block = new Profile_block();
554 // Begin a transaction
556 $block->query('BEGIN');
558 $block->blocker = $this->id;
559 $block->blocked = $other->id;
561 $result = $block->insert();
564 common_log_db_error($block, 'INSERT', __FILE__);
568 // Cancel their subscription, if it exists
570 $otherUser = User::staticGet('id', $other->id);
572 if (!empty($otherUser)) {
573 subs_unsubscribe_to($otherUser, $this->getProfile());
576 $block->query('COMMIT');
581 function unblock($other)
583 // Get the block record
585 $block = Profile_block::get($this->id, $other->id);
591 $result = $block->delete();
594 common_log_db_error($block, 'DELETE', __FILE__);
601 function isMember($group)
603 $profile = $this->getProfile();
604 return $profile->isMember($group);
607 function isAdmin($group)
609 $profile = $this->getProfile();
610 return $profile->isAdmin($group);
613 function getGroups($offset=0, $limit=null)
616 'SELECT user_group.* ' .
617 'FROM user_group JOIN group_member '.
618 'ON user_group.id = group_member.group_id ' .
619 'WHERE group_member.profile_id = %d ' .
620 'ORDER BY group_member.created DESC ';
622 if ($offset>0 && !is_null($limit)) {
624 if (common_config('db','type') == 'pgsql') {
625 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
627 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
632 $groups = new User_group();
634 $cnt = $groups->query(sprintf($qry, $this->id));
639 function getSubscriptions($offset=0, $limit=null)
641 $profile = $this->getProfile();
642 assert(!empty($profile));
643 return $profile->getSubscriptions($offset, $limit);
646 function getSubscribers($offset=0, $limit=null)
648 $profile = $this->getProfile();
649 assert(!empty($profile));
650 return $profile->getSubscribers($offset, $limit);
653 function getTaggedSubscribers($tag, $offset=0, $limit=null)
656 'SELECT profile.* ' .
657 'FROM profile JOIN subscription ' .
658 'ON profile.id = subscription.subscriber ' .
659 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
660 'AND profile_tag.tagger = subscription.subscribed) ' .
661 'WHERE subscription.subscribed = %d ' .
662 "AND profile_tag.tag = '%s' " .
663 'AND subscription.subscribed != subscription.subscriber ' .
664 'ORDER BY subscription.created DESC ';
667 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
670 $profile = new Profile();
672 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
677 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
680 'SELECT profile.* ' .
681 'FROM profile JOIN subscription ' .
682 'ON profile.id = subscription.subscribed ' .
683 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
684 'AND profile_tag.tagger = subscription.subscriber) ' .
685 'WHERE subscription.subscriber = %d ' .
686 "AND profile_tag.tag = '%s' " .
687 'AND subscription.subscribed != subscription.subscriber ' .
688 'ORDER BY subscription.created DESC ';
690 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
692 $profile = new Profile();
694 $profile->query(sprintf($qry, $this->id, $tag));
701 return Design::staticGet('id', $this->design_id);
704 function hasRight($right)
706 $profile = $this->getProfile();
707 return $profile->hasRight($right);
712 $profile = $this->getProfile();
717 $related = array('Fave',
723 Event::handle('UserDeleteRelated', array($this, &$related));
725 foreach ($related as $cls) {
727 $inst->user_id = $this->id;
731 $this->_deleteTags();
732 $this->_deleteBlocks();
737 function _deleteTags()
739 $tag = new Profile_tag();
740 $tag->tagger = $this->id;
744 function _deleteBlocks()
746 $block = new Profile_block();
747 $block->blocker = $this->id;
749 // XXX delete group block? Reset blocker?
752 function hasRole($name)
754 $profile = $this->getProfile();
755 return $profile->hasRole($name);
758 function grantRole($name)
760 $profile = $this->getProfile();
761 return $profile->grantRole($name);
764 function revokeRole($name)
766 $profile = $this->getProfile();
767 return $profile->revokeRole($name);
770 function isSandboxed()
772 $profile = $this->getProfile();
773 return $profile->isSandboxed();
776 function isSilenced()
778 $profile = $this->getProfile();
779 return $profile->isSilenced();
782 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
784 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
786 'user:repeated_by_me:'.$this->id,
787 $offset, $limit, $since_id, $max_id, null);
789 return Notice::getStreamByIds($ids);
792 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id, $since)
794 $notice = new Notice();
796 $notice->selectAdd(); // clears it
797 $notice->selectAdd('id');
799 $notice->profile_id = $this->id;
800 $notice->whereAdd('repeat_of IS NOT NULL');
802 $notice->orderBy('id DESC');
804 if (!is_null($offset)) {
805 $notice->limit($offset, $limit);
808 if ($since_id != 0) {
809 $notice->whereAdd('id > ' . $since_id);
813 $notice->whereAdd('id <= ' . $max_id);
816 if (!is_null($since)) {
817 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
822 if ($notice->find()) {
823 while ($notice->fetch()) {
824 $ids[] = $notice->id;
834 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
836 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
838 'user:repeats_of_me:'.$this->id,
839 $offset, $limit, $since_id, $max_id, null);
841 return Notice::getStreamByIds($ids);
844 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id, $since)
847 'SELECT DISTINCT original.id AS id ' .
848 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
849 'WHERE original.profile_id = ' . $this->id . ' ';
851 if ($since_id != 0) {
852 $qry .= 'AND original.id > ' . $since_id . ' ';
856 $qry .= 'AND original.id <= ' . $max_id . ' ';
859 if (!is_null($since)) {
860 $qry .= 'AND original.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
863 // NOTE: we sort by fave time, not by notice time!
865 $qry .= 'ORDER BY original.id DESC ';
867 if (!is_null($offset)) {
868 $qry .= "LIMIT $limit OFFSET $offset";
873 $notice = new Notice();
875 $notice->query($qry);
877 while ($notice->fetch()) {
878 $ids[] = $notice->id;
887 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
889 throw new Exception("Not implemented since inbox change.");
892 function shareLocation()
894 $cfg = common_config('location', 'share');
896 if ($cfg == 'always') {
898 } else if ($cfg == 'never') {
903 $prefs = User_location_prefs::staticGet('user_id', $this->id);
906 $share = common_config('location', 'sharedefault');
908 $share = $prefs->share_location;
916 static function siteOwner()
918 $owner = self::cacheGet('user:site_owner');
920 if ($owner === false) { // cache miss
922 $pr = new Profile_role();
924 $pr->role = Profile_role::OWNER;
926 $pr->orderBy('created');
930 if ($pr->find(true)) {
931 $owner = User::staticGet('id', $pr->profile_id);
936 self::cacheSet('user:site_owner', $owner);