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);
136 * Get the most recent notice posted by this user, if any.
138 * @return mixed Notice or null
140 function getCurrentNotice()
142 $profile = $this->getProfile();
146 return $profile->getCurrentNotice();
149 function getCarrier()
151 return Sms_carrier::staticGet('id', $this->carrier);
154 function subscribeTo($other)
156 $sub = new Subscription();
157 $sub->subscriber = $this->id;
158 $sub->subscribed = $other->id;
160 $sub->created = common_sql_now(); // current time
162 if (!$sub->insert()) {
169 function hasBlocked($other)
171 $profile = $this->getProfile();
172 return $profile->hasBlocked($other);
176 * Register a new user account and profile and set up default subscriptions.
177 * If a new-user welcome message is configured, this will be sent.
179 * @param array $fields associative array of optional properties
182 * bool 'email_confirmed' pass true to mark email as pre-confirmed
185 * string 'location' informal string description of geolocation
186 * float 'lat' decimal latitude for geolocation
187 * float 'lon' decimal longitude for geolocation
188 * int 'location_id' geoname identifier
189 * int 'location_ns' geoname namespace to interpret location_id
190 * string 'nickname' REQUIRED
191 * string 'password' (may be missing for eg OpenID registrations)
192 * string 'code' invite code
193 * ?string 'uri' permalink to notice; defaults to local notice URL
194 * @return mixed User object or false on failure
196 static function register($fields) {
198 // MAGICALLY put fields into current scope
202 $profile = new Profile();
206 $email = common_canonical_email($email);
209 $nickname = common_canonical_nickname($nickname);
210 $profile->nickname = $nickname;
211 if(! User::allowed_nickname($nickname)){
212 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
216 $profile->profileurl = common_profile_url($nickname);
218 if (!empty($fullname)) {
219 $profile->fullname = $fullname;
221 if (!empty($homepage)) {
222 $profile->homepage = $homepage;
225 $profile->bio = $bio;
227 if (!empty($location)) {
228 $profile->location = $location;
230 $loc = Location::fromName($location);
233 $profile->lat = $loc->lat;
234 $profile->lon = $loc->lon;
235 $profile->location_id = $loc->location_id;
236 $profile->location_ns = $loc->location_ns;
240 $profile->created = common_sql_now();
244 $user->nickname = $nickname;
246 // Users who respond to invite email have proven their ownership of that address
249 $invite = Invitation::staticGet($code);
250 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
251 $user->email = $invite->address;
255 if(isset($email_confirmed) && $email_confirmed) {
256 $user->email = $email;
259 // This flag is ignored but still set to 1
263 $user->created = common_sql_now();
265 if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
267 $profile->query('BEGIN');
269 $id = $profile->insert();
272 common_log_db_error($profile, 'INSERT', __FILE__);
277 $user->uri = common_user_uri($user);
278 if (!empty($password)) { // may not have a password for OpenID users
279 $user->password = common_munge_password($password, $id);
282 $result = $user->insert();
285 common_log_db_error($user, 'INSERT', __FILE__);
289 // Everyone gets an inbox
291 $inbox = new Inbox();
293 $inbox->user_id = $user->id;
294 $inbox->notice_ids = '';
296 $result = $inbox->insert();
299 common_log_db_error($inbox, 'INSERT', __FILE__);
303 // Everyone is subscribed to themself
305 $subscription = new Subscription();
306 $subscription->subscriber = $user->id;
307 $subscription->subscribed = $user->id;
308 $subscription->created = $user->created;
310 $result = $subscription->insert();
313 common_log_db_error($subscription, 'INSERT', __FILE__);
317 if (!empty($email) && !$user->email) {
319 $confirm = new Confirm_address();
320 $confirm->code = common_confirmation_code(128);
321 $confirm->user_id = $user->id;
322 $confirm->address = $email;
323 $confirm->address_type = 'email';
325 $result = $confirm->insert();
328 common_log_db_error($confirm, 'INSERT', __FILE__);
333 if (!empty($code) && $user->email) {
334 $user->emailChanged();
337 // Default system subscription
339 $defnick = common_config('newuser', 'default');
341 if (!empty($defnick)) {
342 $defuser = User::staticGet('nickname', $defnick);
343 if (empty($defuser)) {
344 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
347 $defsub = new Subscription();
348 $defsub->subscriber = $user->id;
349 $defsub->subscribed = $defuser->id;
350 $defsub->created = $user->created;
352 $result = $defsub->insert();
355 common_log_db_error($defsub, 'INSERT', __FILE__);
361 $profile->query('COMMIT');
363 if (!empty($email) && !$user->email) {
364 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
369 $welcome = common_config('newuser', 'welcome');
371 if (!empty($welcome)) {
372 $welcomeuser = User::staticGet('nickname', $welcome);
373 if (empty($welcomeuser)) {
374 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
377 $notice = Notice::saveNew($welcomeuser->id,
378 sprintf(_('Welcome to %1$s, @%2$s!'),
379 common_config('site', 'name'),
386 Event::handle('EndUserRegister', array(&$profile, &$user));
392 // Things we do when the email changes
394 function emailChanged()
397 $invites = new Invitation();
398 $invites->address = $this->email;
399 $invites->address_type = 'email';
401 if ($invites->find()) {
402 while ($invites->fetch()) {
403 $other = User::staticGet($invites->user_id);
404 subs_subscribe_to($other, $this);
409 function hasFave($notice)
411 $cache = common_memcache();
413 // XXX: Kind of a hack.
416 // This is the stream of favorite notices, in rev chron
417 // order. This forces it into cache.
419 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
421 // If it's in the list, then it's a fave
423 if (in_array($notice->id, $ids)) {
427 // If we're not past the end of the cache window,
428 // then the cache has all available faves, so this one
431 if (count($ids) < NOTICE_CACHE_WINDOW) {
435 // Otherwise, cache doesn't have all faves;
436 // fall through to the default
439 $fave = Fave::pkeyGet(array('user_id' => $this->id,
440 'notice_id' => $notice->id));
441 return ((is_null($fave)) ? false : true);
444 function mutuallySubscribed($other)
446 return $this->isSubscribed($other) &&
447 $other->isSubscribed($this);
450 function mutuallySubscribedUsers()
452 // 3-way join; probably should get cached
453 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
454 $qry = "SELECT $UT.* " .
455 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
456 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
457 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
458 "ORDER BY $UT.nickname";
460 $user->query(sprintf($qry, $this->id, $this->id));
465 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
467 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
468 return Notice::getStreamByIds($ids);
471 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
472 $profile = $this->getProfile();
476 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();
486 return $profile->getNotices($offset, $limit, $since_id, $before_id);
490 function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
492 $ids = Fave::stream($this->id, $offset, $limit, $own);
493 return Notice::getStreamByIds($ids);
496 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
498 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
501 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
503 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
506 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
508 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
511 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
513 return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
516 function blowFavesCache()
518 $cache = common_memcache();
520 // Faves don't happen chronologically, so we need to blow
522 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
523 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
524 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
525 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
527 $profile = $this->getProfile();
528 $profile->blowFaveCount();
531 function getSelfTags()
533 return Profile_tag::getTags($this->id, $this->id);
536 function setSelfTags($newtags)
538 return Profile_tag::setTags($this->id, $this->id, $newtags);
541 function block($other)
543 // Add a new block record
545 // no blocking (and thus unsubbing from) yourself
547 if ($this->id == $other->id) {
548 common_log(LOG_WARNING,
550 "Profile ID %d (%s) tried to block his or herself.",
558 $block = new Profile_block();
560 // Begin a transaction
562 $block->query('BEGIN');
564 $block->blocker = $this->id;
565 $block->blocked = $other->id;
567 $result = $block->insert();
570 common_log_db_error($block, 'INSERT', __FILE__);
574 // Cancel their subscription, if it exists
576 $otherUser = User::staticGet('id', $other->id);
578 if (!empty($otherUser)) {
579 subs_unsubscribe_to($otherUser, $this->getProfile());
582 $block->query('COMMIT');
587 function unblock($other)
589 // Get the block record
591 $block = Profile_block::get($this->id, $other->id);
597 $result = $block->delete();
600 common_log_db_error($block, 'DELETE', __FILE__);
607 function isMember($group)
609 $profile = $this->getProfile();
610 return $profile->isMember($group);
613 function isAdmin($group)
615 $profile = $this->getProfile();
616 return $profile->isAdmin($group);
619 function getGroups($offset=0, $limit=null)
621 $profile = $this->getProfile();
622 return $profile->getGroups($offset, $limit);
625 function getSubscriptions($offset=0, $limit=null)
627 $profile = $this->getProfile();
628 assert(!empty($profile));
629 return $profile->getSubscriptions($offset, $limit);
632 function getSubscribers($offset=0, $limit=null)
634 $profile = $this->getProfile();
635 assert(!empty($profile));
636 return $profile->getSubscribers($offset, $limit);
639 function getTaggedSubscribers($tag, $offset=0, $limit=null)
642 'SELECT profile.* ' .
643 'FROM profile JOIN subscription ' .
644 'ON profile.id = subscription.subscriber ' .
645 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
646 'AND profile_tag.tagger = subscription.subscribed) ' .
647 'WHERE subscription.subscribed = %d ' .
648 "AND profile_tag.tag = '%s' " .
649 'AND subscription.subscribed != subscription.subscriber ' .
650 'ORDER BY subscription.created DESC ';
653 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
656 $profile = new Profile();
658 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
663 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
666 'SELECT profile.* ' .
667 'FROM profile JOIN subscription ' .
668 'ON profile.id = subscription.subscribed ' .
669 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
670 'AND profile_tag.tagger = subscription.subscriber) ' .
671 'WHERE subscription.subscriber = %d ' .
672 "AND profile_tag.tag = '%s' " .
673 'AND subscription.subscribed != subscription.subscriber ' .
674 'ORDER BY subscription.created DESC ';
676 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
678 $profile = new Profile();
680 $profile->query(sprintf($qry, $this->id, $tag));
687 return Design::staticGet('id', $this->design_id);
690 function hasRight($right)
692 $profile = $this->getProfile();
693 return $profile->hasRight($right);
698 $profile = $this->getProfile();
703 $related = array('Fave',
709 Event::handle('UserDeleteRelated', array($this, &$related));
711 foreach ($related as $cls) {
713 $inst->user_id = $this->id;
717 $this->_deleteTags();
718 $this->_deleteBlocks();
723 function _deleteTags()
725 $tag = new Profile_tag();
726 $tag->tagger = $this->id;
730 function _deleteBlocks()
732 $block = new Profile_block();
733 $block->blocker = $this->id;
735 // XXX delete group block? Reset blocker?
738 function hasRole($name)
740 $profile = $this->getProfile();
741 return $profile->hasRole($name);
744 function grantRole($name)
746 $profile = $this->getProfile();
747 return $profile->grantRole($name);
750 function revokeRole($name)
752 $profile = $this->getProfile();
753 return $profile->revokeRole($name);
756 function isSandboxed()
758 $profile = $this->getProfile();
759 return $profile->isSandboxed();
762 function isSilenced()
764 $profile = $this->getProfile();
765 return $profile->isSilenced();
768 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
770 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
772 'user:repeated_by_me:'.$this->id,
773 $offset, $limit, $since_id, $max_id, null);
775 return Notice::getStreamByIds($ids);
778 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
780 $notice = new Notice();
782 $notice->selectAdd(); // clears it
783 $notice->selectAdd('id');
785 $notice->profile_id = $this->id;
786 $notice->whereAdd('repeat_of IS NOT NULL');
788 $notice->orderBy('id DESC');
790 if (!is_null($offset)) {
791 $notice->limit($offset, $limit);
794 if ($since_id != 0) {
795 $notice->whereAdd('id > ' . $since_id);
799 $notice->whereAdd('id <= ' . $max_id);
804 if ($notice->find()) {
805 while ($notice->fetch()) {
806 $ids[] = $notice->id;
816 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
818 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
820 'user:repeats_of_me:'.$this->id,
821 $offset, $limit, $since_id, $max_id);
823 return Notice::getStreamByIds($ids);
826 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
829 'SELECT DISTINCT original.id AS id ' .
830 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
831 'WHERE original.profile_id = ' . $this->id . ' ';
833 if ($since_id != 0) {
834 $qry .= 'AND original.id > ' . $since_id . ' ';
838 $qry .= 'AND original.id <= ' . $max_id . ' ';
841 // NOTE: we sort by fave time, not by notice time!
843 $qry .= 'ORDER BY original.id DESC ';
845 if (!is_null($offset)) {
846 $qry .= "LIMIT $limit OFFSET $offset";
851 $notice = new Notice();
853 $notice->query($qry);
855 while ($notice->fetch()) {
856 $ids[] = $notice->id;
865 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
867 throw new Exception("Not implemented since inbox change.");
870 function shareLocation()
872 $cfg = common_config('location', 'share');
874 if ($cfg == 'always') {
876 } else if ($cfg == 'never') {
881 $prefs = User_location_prefs::staticGet('user_id', $this->id);
884 $share = common_config('location', 'sharedefault');
886 $share = $prefs->share_location;
894 static function siteOwner()
896 $owner = self::cacheGet('user:site_owner');
898 if ($owner === false) { // cache miss
900 $pr = new Profile_role();
902 $pr->role = Profile_role::OWNER;
904 $pr->orderBy('created');
908 if ($pr->find(true)) {
909 $owner = User::staticGet('id', $pr->profile_id);
914 self::cacheSet('user:site_owner', $owner);