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 $profile = Profile::staticGet('id', $this->id);
79 if (empty($profile)) {
80 throw new UserNoProfileException($this);
85 function isSubscribed($other)
87 return Subscription::exists($this->getProfile(), $other);
90 // 'update' won't write key columns, so we have to do it ourselves.
92 function updateKeys(&$orig)
96 foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
97 if (strcmp($this->$k, $orig->$k) != 0) {
98 $parts[] = $k . ' = ' . $this->_quote($this->$k);
101 if (count($parts) == 0) {
105 $toupdate = implode(', ', $parts);
107 $table = common_database_tablename($this->tableName());
108 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
109 ' WHERE id = ' . $this->id;
111 $result = $this->query($qry);
118 static function allowed_nickname($nickname)
120 // XXX: should already be validated for size, content, etc.
121 $blacklist = common_config('nickname', 'blacklist');
123 //all directory and file names should be blacklisted
124 $d = dir(INSTALLDIR);
125 while (false !== ($entry = $d->read())) {
130 //all top level names in the router should be blacklisted
131 $router = Router::get();
132 foreach(array_keys($router->m->getPaths()) as $path){
133 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
134 $blacklist[]=$matches[1];
137 return !in_array($nickname, $blacklist);
141 * Get the most recent notice posted by this user, if any.
143 * @return mixed Notice or null
145 function getCurrentNotice()
147 $profile = $this->getProfile();
148 return $profile->getCurrentNotice();
151 function getCarrier()
153 return Sms_carrier::staticGet('id', $this->carrier);
157 * @deprecated use Subscription::start($sub, $other);
159 function subscribeTo($other)
161 return Subscription::start($this->getProfile(), $other);
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),
211 $profile->profileurl = common_profile_url($nickname);
213 if (!empty($fullname)) {
214 $profile->fullname = $fullname;
216 if (!empty($homepage)) {
217 $profile->homepage = $homepage;
220 $profile->bio = $bio;
222 if (!empty($location)) {
223 $profile->location = $location;
225 $loc = Location::fromName($location);
228 $profile->lat = $loc->lat;
229 $profile->lon = $loc->lon;
230 $profile->location_id = $loc->location_id;
231 $profile->location_ns = $loc->location_ns;
235 $profile->created = common_sql_now();
239 $user->nickname = $nickname;
241 // Users who respond to invite email have proven their ownership of that address
244 $invite = Invitation::staticGet($code);
245 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
246 $user->email = $invite->address;
250 if(isset($email_confirmed) && $email_confirmed) {
251 $user->email = $email;
254 // This flag is ignored but still set to 1
258 // Set default-on options here, otherwise they'll be disabled
259 // initially for sites using caching, since the initial encache
260 // doesn't know about the defaults in the database.
261 $user->emailnotifysub = 1;
262 $user->emailnotifyfav = 1;
263 $user->emailnotifynudge = 1;
264 $user->emailnotifymsg = 1;
265 $user->emailnotifyattn = 1;
266 $user->emailmicroid = 1;
267 $user->emailpost = 1;
268 $user->jabbermicroid = 1;
269 $user->viewdesigns = 1;
271 $user->created = common_sql_now();
273 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
275 $profile->query('BEGIN');
277 $id = $profile->insert();
280 common_log_db_error($profile, 'INSERT', __FILE__);
289 $user->uri = common_user_uri($user);
292 if (!empty($password)) { // may not have a password for OpenID users
293 $user->password = common_munge_password($password, $id);
296 $result = $user->insert();
299 common_log_db_error($user, 'INSERT', __FILE__);
303 // Everyone gets an inbox
305 $inbox = new Inbox();
307 $inbox->user_id = $user->id;
308 $inbox->notice_ids = '';
310 $result = $inbox->insert();
313 common_log_db_error($inbox, 'INSERT', __FILE__);
317 // Everyone is subscribed to themself
319 $subscription = new Subscription();
320 $subscription->subscriber = $user->id;
321 $subscription->subscribed = $user->id;
322 $subscription->created = $user->created;
324 $result = $subscription->insert();
327 common_log_db_error($subscription, 'INSERT', __FILE__);
331 if (!empty($email) && !$user->email) {
333 $confirm = new Confirm_address();
334 $confirm->code = common_confirmation_code(128);
335 $confirm->user_id = $user->id;
336 $confirm->address = $email;
337 $confirm->address_type = 'email';
339 $result = $confirm->insert();
342 common_log_db_error($confirm, 'INSERT', __FILE__);
347 if (!empty($code) && $user->email) {
348 $user->emailChanged();
351 // Default system subscription
353 $defnick = common_config('newuser', 'default');
355 if (!empty($defnick)) {
356 $defuser = User::staticGet('nickname', $defnick);
357 if (empty($defuser)) {
358 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
361 Subscription::start($user, $defuser);
365 $profile->query('COMMIT');
367 if (!empty($email) && !$user->email) {
368 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
373 $welcome = common_config('newuser', 'welcome');
375 if (!empty($welcome)) {
376 $welcomeuser = User::staticGet('nickname', $welcome);
377 if (empty($welcomeuser)) {
378 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
381 $notice = Notice::saveNew($welcomeuser->id,
382 // TRANS: Notice given on user registration.
383 // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
384 sprintf(_('Welcome to %1$s, @%2$s!'),
385 common_config('site', 'name'),
391 Event::handle('EndUserRegister', array(&$profile, &$user));
397 // Things we do when the email changes
398 function emailChanged()
401 $invites = new Invitation();
402 $invites->address = $this->email;
403 $invites->address_type = 'email';
405 if ($invites->find()) {
406 while ($invites->fetch()) {
407 $other = User::staticGet($invites->user_id);
408 subs_subscribe_to($other, $this);
413 function hasFave($notice)
415 $cache = common_memcache();
417 // XXX: Kind of a hack.
420 // This is the stream of favorite notices, in rev chron
421 // order. This forces it into cache.
423 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
425 // If it's in the list, then it's a fave
427 if (in_array($notice->id, $ids)) {
431 // If we're not past the end of the cache window,
432 // then the cache has all available faves, so this one
435 if (count($ids) < NOTICE_CACHE_WINDOW) {
439 // Otherwise, cache doesn't have all faves;
440 // fall through to the default
443 $fave = Fave::pkeyGet(array('user_id' => $this->id,
444 'notice_id' => $notice->id));
445 return ((is_null($fave)) ? false : true);
448 function mutuallySubscribed($other)
450 return $this->isSubscribed($other) &&
451 $other->isSubscribed($this);
454 function mutuallySubscribedUsers()
456 // 3-way join; probably should get cached
457 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
458 $qry = "SELECT $UT.* " .
459 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
460 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
461 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
462 "ORDER BY $UT.nickname";
464 $user->query(sprintf($qry, $this->id, $this->id));
469 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
471 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
472 return Notice::getStreamByIds($ids);
475 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
476 $profile = $this->getProfile();
477 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
480 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
482 $profile = $this->getProfile();
483 return $profile->getNotices($offset, $limit, $since_id, $before_id);
486 function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
488 $ids = Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
489 return Notice::getStreamByIds($ids);
492 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
494 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
497 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
499 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
502 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
504 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
507 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
509 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
512 function blowFavesCache()
514 $cache = common_memcache();
516 // Faves don't happen chronologically, so we need to blow
518 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
519 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
520 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
521 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
523 $profile = $this->getProfile();
524 $profile->blowFaveCount();
527 function getSelfTags()
529 return Profile_tag::getTags($this->id, $this->id);
532 function setSelfTags($newtags)
534 return Profile_tag::setTags($this->id, $this->id, $newtags);
537 function block($other)
539 // Add a new block record
541 // no blocking (and thus unsubbing from) yourself
543 if ($this->id == $other->id) {
544 common_log(LOG_WARNING,
546 "Profile ID %d (%s) tried to block themself.",
554 $block = new Profile_block();
556 // Begin a transaction
558 $block->query('BEGIN');
560 $block->blocker = $this->id;
561 $block->blocked = $other->id;
563 $result = $block->insert();
566 common_log_db_error($block, 'INSERT', __FILE__);
570 $self = $this->getProfile();
571 if (Subscription::exists($other, $self)) {
572 Subscription::cancel($other, $self);
574 if (Subscription::exists($self, $other)) {
575 Subscription::cancel($self, $other);
578 $block->query('COMMIT');
583 function unblock($other)
585 // Get the block record
587 $block = Profile_block::get($this->id, $other->id);
593 $result = $block->delete();
596 common_log_db_error($block, 'DELETE', __FILE__);
603 function isMember($group)
605 $profile = $this->getProfile();
606 return $profile->isMember($group);
609 function isAdmin($group)
611 $profile = $this->getProfile();
612 return $profile->isAdmin($group);
615 function getGroups($offset=0, $limit=null)
617 $profile = $this->getProfile();
618 return $profile->getGroups($offset, $limit);
621 function getSubscriptions($offset=0, $limit=null)
623 $profile = $this->getProfile();
624 return $profile->getSubscriptions($offset, $limit);
627 function getSubscribers($offset=0, $limit=null)
629 $profile = $this->getProfile();
630 return $profile->getSubscribers($offset, $limit);
633 function getTaggedSubscribers($tag, $offset=0, $limit=null)
636 'SELECT profile.* ' .
637 'FROM profile JOIN subscription ' .
638 'ON profile.id = subscription.subscriber ' .
639 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
640 'AND profile_tag.tagger = subscription.subscribed) ' .
641 'WHERE subscription.subscribed = %d ' .
642 "AND profile_tag.tag = '%s' " .
643 'AND subscription.subscribed != subscription.subscriber ' .
644 'ORDER BY subscription.created DESC ';
647 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
650 $profile = new Profile();
652 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
657 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
660 'SELECT profile.* ' .
661 'FROM profile JOIN subscription ' .
662 'ON profile.id = subscription.subscribed ' .
663 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
664 'AND profile_tag.tagger = subscription.subscriber) ' .
665 'WHERE subscription.subscriber = %d ' .
666 "AND profile_tag.tag = '%s' " .
667 'AND subscription.subscribed != subscription.subscriber ' .
668 'ORDER BY subscription.created DESC ';
670 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
672 $profile = new Profile();
674 $profile->query(sprintf($qry, $this->id, $tag));
681 return Design::staticGet('id', $this->design_id);
684 function hasRight($right)
686 $profile = $this->getProfile();
687 return $profile->hasRight($right);
693 $profile = $this->getProfile();
695 } catch (UserNoProfileException $unp) {
696 common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
699 $related = array('Fave',
706 Event::handle('UserDeleteRelated', array($this, &$related));
708 foreach ($related as $cls) {
710 $inst->user_id = $this->id;
714 $this->_deleteTags();
715 $this->_deleteBlocks();
720 function _deleteTags()
722 $tag = new Profile_tag();
723 $tag->tagger = $this->id;
727 function _deleteBlocks()
729 $block = new Profile_block();
730 $block->blocker = $this->id;
732 // XXX delete group block? Reset blocker?
735 function hasRole($name)
737 $profile = $this->getProfile();
738 return $profile->hasRole($name);
741 function grantRole($name)
743 $profile = $this->getProfile();
744 return $profile->grantRole($name);
747 function revokeRole($name)
749 $profile = $this->getProfile();
750 return $profile->revokeRole($name);
753 function isSandboxed()
755 $profile = $this->getProfile();
756 return $profile->isSandboxed();
759 function isSilenced()
761 $profile = $this->getProfile();
762 return $profile->isSilenced();
765 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
767 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
769 'user:repeated_by_me:'.$this->id,
770 $offset, $limit, $since_id, $max_id, null);
772 return Notice::getStreamByIds($ids);
775 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
777 $notice = new Notice();
779 $notice->selectAdd(); // clears it
780 $notice->selectAdd('id');
782 $notice->profile_id = $this->id;
783 $notice->whereAdd('repeat_of IS NOT NULL');
785 $notice->orderBy('id DESC');
787 if (!is_null($offset)) {
788 $notice->limit($offset, $limit);
791 if ($since_id != 0) {
792 $notice->whereAdd('id > ' . $since_id);
796 $notice->whereAdd('id <= ' . $max_id);
801 if ($notice->find()) {
802 while ($notice->fetch()) {
803 $ids[] = $notice->id;
813 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
815 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
817 'user:repeats_of_me:'.$this->id,
818 $offset, $limit, $since_id, $max_id);
820 return Notice::getStreamByIds($ids);
823 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
826 'SELECT DISTINCT original.id AS id ' .
827 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
828 'WHERE original.profile_id = ' . $this->id . ' ';
830 if ($since_id != 0) {
831 $qry .= 'AND original.id > ' . $since_id . ' ';
835 $qry .= 'AND original.id <= ' . $max_id . ' ';
838 // NOTE: we sort by fave time, not by notice time!
840 $qry .= 'ORDER BY original.id DESC ';
842 if (!is_null($offset)) {
843 $qry .= "LIMIT $limit OFFSET $offset";
848 $notice = new Notice();
850 $notice->query($qry);
852 while ($notice->fetch()) {
853 $ids[] = $notice->id;
862 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
864 throw new Exception("Not implemented since inbox change.");
867 function shareLocation()
869 $cfg = common_config('location', 'share');
871 if ($cfg == 'always') {
873 } else if ($cfg == 'never') {
878 $prefs = User_location_prefs::staticGet('user_id', $this->id);
881 $share = common_config('location', 'sharedefault');
883 $share = $prefs->share_location;
891 static function siteOwner()
893 $owner = self::cacheGet('user:site_owner');
895 if ($owner === false) { // cache miss
897 $pr = new Profile_role();
899 $pr->role = Profile_role::OWNER;
901 $pr->orderBy('created');
905 if ($pr->find(true)) {
906 $owner = User::staticGet('id', $pr->profile_id);
911 self::cacheSet('user:site_owner', $owner);