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 assert(!is_null($other));
84 // XXX: cache results of this query
85 $sub = Subscription::pkeyGet(array('subscriber' => $this->id,
86 'subscribed' => $other->id));
87 return (is_null($sub)) ? false : true;
90 // 'update' won't write key columns, so we have to do it ourselves.
92 function updateKeys(&$orig)
95 foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
96 if (strcmp($this->$k, $orig->$k) != 0) {
97 $parts[] = $k . ' = ' . $this->_quote($this->$k);
100 if (count($parts) == 0) {
104 $toupdate = implode(', ', $parts);
106 $table = common_database_tablename($this->tableName());
107 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
108 ' WHERE id = ' . $this->id;
110 $result = $this->query($qry);
117 static function allowed_nickname($nickname)
119 // XXX: should already be validated for size, content, etc.
120 $blacklist = common_config('nickname', 'blacklist');
122 //all directory and file names should be blacklisted
123 $d = dir(INSTALLDIR);
124 while (false !== ($entry = $d->read())) {
129 //all top level names in the router should be blacklisted
130 $router = Router::get();
131 foreach(array_keys($router->m->getPaths()) as $path){
132 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
133 $blacklist[]=$matches[1];
136 return !in_array($nickname, $blacklist);
139 function getCurrentNotice($dt=null)
141 $profile = $this->getProfile();
145 return $profile->getCurrentNotice($dt);
148 function getCarrier()
150 return Sms_carrier::staticGet('id', $this->carrier);
153 function subscribeTo($other)
155 $sub = new Subscription();
156 $sub->subscriber = $this->id;
157 $sub->subscribed = $other->id;
159 $sub->created = common_sql_now(); // current time
161 if (!$sub->insert()) {
168 function hasBlocked($other)
171 $block = Profile_block::get($this->id, $other->id);
173 if (is_null($block)) {
184 * Register a new user account and profile and set up default subscriptions.
185 * If a new-user welcome message is configured, this will be sent.
187 * @param array $fields associative array of optional properties
190 * bool 'email_confirmed' pass true to mark email as pre-confirmed
193 * string 'location' informal string description of geolocation
194 * float 'lat' decimal latitude for geolocation
195 * float 'lon' decimal longitude for geolocation
196 * int 'location_id' geoname identifier
197 * int 'location_ns' geoname namespace to interpret location_id
198 * string 'nickname' REQUIRED
199 * string 'password' (may be missing for eg OpenID registrations)
200 * string 'code' invite code
201 * ?string 'uri' permalink to notice; defaults to local notice URL
202 * @return mixed User object or false on failure
204 static function register($fields) {
206 // MAGICALLY put fields into current scope
210 $profile = new Profile();
214 $email = common_canonical_email($email);
217 $nickname = common_canonical_nickname($nickname);
218 $profile->nickname = $nickname;
219 if(! User::allowed_nickname($nickname)){
220 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
223 $profile->profileurl = common_profile_url($nickname);
225 if (!empty($fullname)) {
226 $profile->fullname = $fullname;
228 if (!empty($homepage)) {
229 $profile->homepage = $homepage;
232 $profile->bio = $bio;
234 if (!empty($location)) {
235 $profile->location = $location;
237 $loc = Location::fromName($location);
240 $profile->lat = $loc->lat;
241 $profile->lon = $loc->lon;
242 $profile->location_id = $loc->location_id;
243 $profile->location_ns = $loc->location_ns;
247 $profile->created = common_sql_now();
251 $user->nickname = $nickname;
253 if (!empty($password)) { // may not have a password for OpenID users
254 $user->password = common_munge_password($password, $id);
257 // Users who respond to invite email have proven their ownership of that address
260 $invite = Invitation::staticGet($code);
261 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
262 $user->email = $invite->address;
266 if(isset($email_confirmed) && $email_confirmed) {
267 $user->email = $email;
270 // This flag is ignored but still set to 1
274 $user->created = common_sql_now();
276 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
278 $profile->query('BEGIN');
280 $id = $profile->insert();
283 common_log_db_error($profile, 'INSERT', __FILE__);
288 $user->uri = common_user_uri($user);
290 $result = $user->insert();
293 common_log_db_error($user, 'INSERT', __FILE__);
297 // Everyone gets an inbox
299 $inbox = new Inbox();
301 $inbox->user_id = $user->id;
302 $inbox->notice_ids = '';
304 $result = $inbox->insert();
307 common_log_db_error($inbox, 'INSERT', __FILE__);
311 // Everyone is subscribed to themself
313 $subscription = new Subscription();
314 $subscription->subscriber = $user->id;
315 $subscription->subscribed = $user->id;
316 $subscription->created = $user->created;
318 $result = $subscription->insert();
321 common_log_db_error($subscription, 'INSERT', __FILE__);
325 if (!empty($email) && !$user->email) {
327 $confirm = new Confirm_address();
328 $confirm->code = common_confirmation_code(128);
329 $confirm->user_id = $user->id;
330 $confirm->address = $email;
331 $confirm->address_type = 'email';
333 $result = $confirm->insert();
336 common_log_db_error($confirm, 'INSERT', __FILE__);
341 if (!empty($code) && $user->email) {
342 $user->emailChanged();
345 // Default system subscription
347 $defnick = common_config('newuser', 'default');
349 if (!empty($defnick)) {
350 $defuser = User::staticGet('nickname', $defnick);
351 if (empty($defuser)) {
352 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
355 $defsub = new Subscription();
356 $defsub->subscriber = $user->id;
357 $defsub->subscribed = $defuser->id;
358 $defsub->created = $user->created;
360 $result = $defsub->insert();
363 common_log_db_error($defsub, 'INSERT', __FILE__);
369 $profile->query('COMMIT');
371 if (!empty($email) && !$user->email) {
372 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
377 $welcome = common_config('newuser', 'welcome');
379 if (!empty($welcome)) {
380 $welcomeuser = User::staticGet('nickname', $welcome);
381 if (empty($welcomeuser)) {
382 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
385 $notice = Notice::saveNew($welcomeuser->id,
386 sprintf(_('Welcome to %1$s, @%2$s!'),
387 common_config('site', 'name'),
394 Event::handle('EndUserRegister', array(&$profile, &$user));
400 // Things we do when the email changes
402 function emailChanged()
405 $invites = new Invitation();
406 $invites->address = $this->email;
407 $invites->address_type = 'email';
409 if ($invites->find()) {
410 while ($invites->fetch()) {
411 $other = User::staticGet($invites->user_id);
412 subs_subscribe_to($other, $this);
417 function hasFave($notice)
419 $cache = common_memcache();
421 // XXX: Kind of a hack.
424 // This is the stream of favorite notices, in rev chron
425 // order. This forces it into cache.
427 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
429 // If it's in the list, then it's a fave
431 if (in_array($notice->id, $ids)) {
435 // If we're not past the end of the cache window,
436 // then the cache has all available faves, so this one
439 if (count($ids) < NOTICE_CACHE_WINDOW) {
443 // Otherwise, cache doesn't have all faves;
444 // fall through to the default
447 $fave = Fave::pkeyGet(array('user_id' => $this->id,
448 'notice_id' => $notice->id));
449 return ((is_null($fave)) ? false : true);
452 function mutuallySubscribed($other)
454 return $this->isSubscribed($other) &&
455 $other->isSubscribed($this);
458 function mutuallySubscribedUsers()
460 // 3-way join; probably should get cached
461 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
462 $qry = "SELECT $UT.* " .
463 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
464 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
465 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
466 "ORDER BY $UT.nickname";
468 $user->query(sprintf($qry, $this->id, $this->id));
473 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
475 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
476 return Notice::getStreamByIds($ids);
479 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
480 $profile = $this->getProfile();
484 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
488 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
490 $profile = $this->getProfile();
494 return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
498 function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
500 $ids = Fave::stream($this->id, $offset, $limit, $own);
501 return Notice::getStreamByIds($ids);
504 function noticesWithFriends($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, false);
507 return Notice::getStreamByIds($ids);
510 function noticeInbox($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, true);
513 return Notice::getStreamByIds($ids);
516 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
518 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
520 return Notice::getStreamByIds($ids);
523 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
525 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
527 return Notice::getStreamByIds($ids);
530 function blowFavesCache()
532 $cache = common_memcache();
534 // Faves don't happen chronologically, so we need to blow
536 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
537 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
538 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
539 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
541 $profile = $this->getProfile();
542 $profile->blowFaveCount();
545 function getSelfTags()
547 return Profile_tag::getTags($this->id, $this->id);
550 function setSelfTags($newtags)
552 return Profile_tag::setTags($this->id, $this->id, $newtags);
555 function block($other)
557 // Add a new block record
559 // no blocking (and thus unsubbing from) yourself
561 if ($this->id == $other->id) {
562 common_log(LOG_WARNING,
564 "Profile ID %d (%s) tried to block his or herself.",
572 $block = new Profile_block();
574 // Begin a transaction
576 $block->query('BEGIN');
578 $block->blocker = $this->id;
579 $block->blocked = $other->id;
581 $result = $block->insert();
584 common_log_db_error($block, 'INSERT', __FILE__);
588 // Cancel their subscription, if it exists
590 $otherUser = User::staticGet('id', $other->id);
592 if (!empty($otherUser)) {
593 subs_unsubscribe_to($otherUser, $this->getProfile());
596 $block->query('COMMIT');
601 function unblock($other)
603 // Get the block record
605 $block = Profile_block::get($this->id, $other->id);
611 $result = $block->delete();
614 common_log_db_error($block, 'DELETE', __FILE__);
621 function isMember($group)
623 $profile = $this->getProfile();
624 return $profile->isMember($group);
627 function isAdmin($group)
629 $profile = $this->getProfile();
630 return $profile->isAdmin($group);
633 function getGroups($offset=0, $limit=null)
636 'SELECT user_group.* ' .
637 'FROM user_group JOIN group_member '.
638 'ON user_group.id = group_member.group_id ' .
639 'WHERE group_member.profile_id = %d ' .
640 'ORDER BY group_member.created DESC ';
642 if ($offset>0 && !is_null($limit)) {
644 if (common_config('db','type') == 'pgsql') {
645 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
647 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
652 $groups = new User_group();
654 $cnt = $groups->query(sprintf($qry, $this->id));
659 function getSubscriptions($offset=0, $limit=null)
661 $profile = $this->getProfile();
662 assert(!empty($profile));
663 return $profile->getSubscriptions($offset, $limit);
666 function getSubscribers($offset=0, $limit=null)
668 $profile = $this->getProfile();
669 assert(!empty($profile));
670 return $profile->getSubscribers($offset, $limit);
673 function getTaggedSubscribers($tag, $offset=0, $limit=null)
676 'SELECT profile.* ' .
677 'FROM profile JOIN subscription ' .
678 'ON profile.id = subscription.subscriber ' .
679 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
680 'AND profile_tag.tagger = subscription.subscribed) ' .
681 'WHERE subscription.subscribed = %d ' .
682 "AND profile_tag.tag = '%s' " .
683 'AND subscription.subscribed != subscription.subscriber ' .
684 'ORDER BY subscription.created DESC ';
687 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
690 $profile = new Profile();
692 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
697 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
700 'SELECT profile.* ' .
701 'FROM profile JOIN subscription ' .
702 'ON profile.id = subscription.subscribed ' .
703 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
704 'AND profile_tag.tagger = subscription.subscriber) ' .
705 'WHERE subscription.subscriber = %d ' .
706 "AND profile_tag.tag = '%s' " .
707 'AND subscription.subscribed != subscription.subscriber ' .
708 'ORDER BY subscription.created DESC ';
710 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
712 $profile = new Profile();
714 $profile->query(sprintf($qry, $this->id, $tag));
721 return Design::staticGet('id', $this->design_id);
724 function hasRight($right)
726 $profile = $this->getProfile();
727 return $profile->hasRight($right);
732 $profile = $this->getProfile();
737 $related = array('Fave',
743 Event::handle('UserDeleteRelated', array($this, &$related));
745 foreach ($related as $cls) {
747 $inst->user_id = $this->id;
751 $this->_deleteTags();
752 $this->_deleteBlocks();
757 function _deleteTags()
759 $tag = new Profile_tag();
760 $tag->tagger = $this->id;
764 function _deleteBlocks()
766 $block = new Profile_block();
767 $block->blocker = $this->id;
769 // XXX delete group block? Reset blocker?
772 function hasRole($name)
774 $profile = $this->getProfile();
775 return $profile->hasRole($name);
778 function grantRole($name)
780 $profile = $this->getProfile();
781 return $profile->grantRole($name);
784 function revokeRole($name)
786 $profile = $this->getProfile();
787 return $profile->revokeRole($name);
790 function isSandboxed()
792 $profile = $this->getProfile();
793 return $profile->isSandboxed();
796 function isSilenced()
798 $profile = $this->getProfile();
799 return $profile->isSilenced();
802 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
804 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
806 'user:repeated_by_me:'.$this->id,
807 $offset, $limit, $since_id, $max_id, null);
809 return Notice::getStreamByIds($ids);
812 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id, $since)
814 $notice = new Notice();
816 $notice->selectAdd(); // clears it
817 $notice->selectAdd('id');
819 $notice->profile_id = $this->id;
820 $notice->whereAdd('repeat_of IS NOT NULL');
822 $notice->orderBy('id DESC');
824 if (!is_null($offset)) {
825 $notice->limit($offset, $limit);
828 if ($since_id != 0) {
829 $notice->whereAdd('id > ' . $since_id);
833 $notice->whereAdd('id <= ' . $max_id);
836 if (!is_null($since)) {
837 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
842 if ($notice->find()) {
843 while ($notice->fetch()) {
844 $ids[] = $notice->id;
854 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
856 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
858 'user:repeats_of_me:'.$this->id,
859 $offset, $limit, $since_id, $max_id, null);
861 return Notice::getStreamByIds($ids);
864 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id, $since)
867 'SELECT DISTINCT original.id AS id ' .
868 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
869 'WHERE original.profile_id = ' . $this->id . ' ';
871 if ($since_id != 0) {
872 $qry .= 'AND original.id > ' . $since_id . ' ';
876 $qry .= 'AND original.id <= ' . $max_id . ' ';
879 if (!is_null($since)) {
880 $qry .= 'AND original.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
883 // NOTE: we sort by fave time, not by notice time!
885 $qry .= 'ORDER BY original.id DESC ';
887 if (!is_null($offset)) {
888 $qry .= "LIMIT $limit OFFSET $offset";
893 $notice = new Notice();
895 $notice->query($qry);
897 while ($notice->fetch()) {
898 $ids[] = $notice->id;
907 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
909 throw new Exception("Not implemented since inbox change.");
912 function shareLocation()
914 $cfg = common_config('location', 'share');
916 if ($cfg == 'always') {
918 } else if ($cfg == 'never') {
923 $prefs = User_location_prefs::staticGet('user_id', $this->id);
926 $share = common_config('location', 'sharedefault');
928 $share = $prefs->share_location;
936 static function siteOwner()
938 $owner = self::cacheGet('user:site_owner');
940 if ($owner === false) { // cache miss
942 $pr = new Profile_role();
944 $pr->role = Profile_role::OWNER;
946 $pr->orderBy('created');
950 if ($pr->fetch($true)) {
951 $owner = User::staticGet('id', $pr->profile_id);
956 self::cacheSet('user:site_owner', $owner);