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);
156 function subscribeTo($other)
158 $sub = new Subscription();
159 $sub->subscriber = $this->id;
160 $sub->subscribed = $other->id;
162 $sub->created = common_sql_now(); // current time
164 if (!$sub->insert()) {
171 function hasBlocked($other)
173 $profile = $this->getProfile();
174 return $profile->hasBlocked($other);
178 * Register a new user account and profile and set up default subscriptions.
179 * If a new-user welcome message is configured, this will be sent.
181 * @param array $fields associative array of optional properties
184 * bool 'email_confirmed' pass true to mark email as pre-confirmed
187 * string 'location' informal string description of geolocation
188 * float 'lat' decimal latitude for geolocation
189 * float 'lon' decimal longitude for geolocation
190 * int 'location_id' geoname identifier
191 * int 'location_ns' geoname namespace to interpret location_id
192 * string 'nickname' REQUIRED
193 * string 'password' (may be missing for eg OpenID registrations)
194 * string 'code' invite code
195 * ?string 'uri' permalink to notice; defaults to local notice URL
196 * @return mixed User object or false on failure
198 static function register($fields) {
200 // MAGICALLY put fields into current scope
204 $profile = new Profile();
208 $email = common_canonical_email($email);
211 $nickname = common_canonical_nickname($nickname);
212 $profile->nickname = $nickname;
213 if(! User::allowed_nickname($nickname)){
214 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)
469 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
470 return Notice::getStreamByIds($ids);
473 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
474 $profile = $this->getProfile();
475 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
478 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
480 $profile = $this->getProfile();
481 return $profile->getNotices($offset, $limit, $since_id, $before_id);
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)
492 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
495 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
497 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
500 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
502 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
505 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
507 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, 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)
615 $profile = $this->getProfile();
616 return $profile->getGroups($offset, $limit);
619 function getSubscriptions($offset=0, $limit=null)
621 $profile = $this->getProfile();
622 return $profile->getSubscriptions($offset, $limit);
625 function getSubscribers($offset=0, $limit=null)
627 $profile = $this->getProfile();
628 return $profile->getSubscribers($offset, $limit);
631 function getTaggedSubscribers($tag, $offset=0, $limit=null)
634 'SELECT profile.* ' .
635 'FROM profile JOIN subscription ' .
636 'ON profile.id = subscription.subscriber ' .
637 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
638 'AND profile_tag.tagger = subscription.subscribed) ' .
639 'WHERE subscription.subscribed = %d ' .
640 "AND profile_tag.tag = '%s' " .
641 'AND subscription.subscribed != subscription.subscriber ' .
642 'ORDER BY subscription.created DESC ';
645 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
648 $profile = new Profile();
650 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
655 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
658 'SELECT profile.* ' .
659 'FROM profile JOIN subscription ' .
660 'ON profile.id = subscription.subscribed ' .
661 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
662 'AND profile_tag.tagger = subscription.subscriber) ' .
663 'WHERE subscription.subscriber = %d ' .
664 "AND profile_tag.tag = '%s' " .
665 'AND subscription.subscribed != subscription.subscriber ' .
666 'ORDER BY subscription.created DESC ';
668 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
670 $profile = new Profile();
672 $profile->query(sprintf($qry, $this->id, $tag));
679 return Design::staticGet('id', $this->design_id);
682 function hasRight($right)
684 $profile = $this->getProfile();
685 return $profile->hasRight($right);
690 $profile = $this->getProfile();
693 $related = array('Fave',
699 Event::handle('UserDeleteRelated', array($this, &$related));
701 foreach ($related as $cls) {
703 $inst->user_id = $this->id;
707 $this->_deleteTags();
708 $this->_deleteBlocks();
713 function _deleteTags()
715 $tag = new Profile_tag();
716 $tag->tagger = $this->id;
720 function _deleteBlocks()
722 $block = new Profile_block();
723 $block->blocker = $this->id;
725 // XXX delete group block? Reset blocker?
728 function hasRole($name)
730 $profile = $this->getProfile();
731 return $profile->hasRole($name);
734 function grantRole($name)
736 $profile = $this->getProfile();
737 return $profile->grantRole($name);
740 function revokeRole($name)
742 $profile = $this->getProfile();
743 return $profile->revokeRole($name);
746 function isSandboxed()
748 $profile = $this->getProfile();
749 return $profile->isSandboxed();
752 function isSilenced()
754 $profile = $this->getProfile();
755 return $profile->isSilenced();
758 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
760 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
762 'user:repeated_by_me:'.$this->id,
763 $offset, $limit, $since_id, $max_id, null);
765 return Notice::getStreamByIds($ids);
768 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
770 $notice = new Notice();
772 $notice->selectAdd(); // clears it
773 $notice->selectAdd('id');
775 $notice->profile_id = $this->id;
776 $notice->whereAdd('repeat_of IS NOT NULL');
778 $notice->orderBy('id DESC');
780 if (!is_null($offset)) {
781 $notice->limit($offset, $limit);
784 if ($since_id != 0) {
785 $notice->whereAdd('id > ' . $since_id);
789 $notice->whereAdd('id <= ' . $max_id);
794 if ($notice->find()) {
795 while ($notice->fetch()) {
796 $ids[] = $notice->id;
806 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
808 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
810 'user:repeats_of_me:'.$this->id,
811 $offset, $limit, $since_id, $max_id);
813 return Notice::getStreamByIds($ids);
816 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
819 'SELECT DISTINCT original.id AS id ' .
820 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
821 'WHERE original.profile_id = ' . $this->id . ' ';
823 if ($since_id != 0) {
824 $qry .= 'AND original.id > ' . $since_id . ' ';
828 $qry .= 'AND original.id <= ' . $max_id . ' ';
831 // NOTE: we sort by fave time, not by notice time!
833 $qry .= 'ORDER BY original.id DESC ';
835 if (!is_null($offset)) {
836 $qry .= "LIMIT $limit OFFSET $offset";
841 $notice = new Notice();
843 $notice->query($qry);
845 while ($notice->fetch()) {
846 $ids[] = $notice->id;
855 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
857 throw new Exception("Not implemented since inbox change.");
860 function shareLocation()
862 $cfg = common_config('location', 'share');
864 if ($cfg == 'always') {
866 } else if ($cfg == 'never') {
871 $prefs = User_location_prefs::staticGet('user_id', $this->id);
874 $share = common_config('location', 'sharedefault');
876 $share = $prefs->share_location;
884 static function siteOwner()
886 $owner = self::cacheGet('user:site_owner');
888 if ($owner === false) { // cache miss
890 $pr = new Profile_role();
892 $pr->role = Profile_role::OWNER;
894 $pr->orderBy('created');
898 if ($pr->find(true)) {
899 $owner = User::staticGet('id', $pr->profile_id);
904 self::cacheSet('user:site_owner', $owner);