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 $sms; // varchar(64) unique_key
52 public $carrier; // int(4)
53 public $smsnotify; // tinyint(1)
54 public $smsreplies; // tinyint(1)
55 public $smsemail; // varchar(255)
56 public $uri; // varchar(255) unique_key
57 public $autosubscribe; // tinyint(1)
58 public $urlshorteningservice; // varchar(50) default_ur1.ca
59 public $inboxed; // tinyint(1)
60 public $design_id; // int(4)
61 public $viewdesigns; // tinyint(1) default_1
62 public $created; // datetime() not_null
63 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
66 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
68 /* the code above is auto generated do not remove the tag below */
73 return Profile::staticGet('id', $this->id);
76 function isSubscribed($other)
78 assert(!is_null($other));
79 // XXX: cache results of this query
80 $sub = Subscription::pkeyGet(array('subscriber' => $this->id,
81 'subscribed' => $other->id));
82 return (is_null($sub)) ? false : true;
85 // 'update' won't write key columns, so we have to do it ourselves.
87 function updateKeys(&$orig)
90 foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
91 if (strcmp($this->$k, $orig->$k) != 0) {
92 $parts[] = $k . ' = ' . $this->_quote($this->$k);
95 if (count($parts) == 0) {
99 $toupdate = implode(', ', $parts);
101 $table = common_database_tablename($this->tableName());
102 $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
103 ' WHERE id = ' . $this->id;
105 $result = $this->query($qry);
112 static function allowed_nickname($nickname)
114 // XXX: should already be validated for size, content, etc.
115 $blacklist = common_config('nickname', 'blacklist');
117 //all directory and file names should be blacklisted
118 $d = dir(INSTALLDIR);
119 while (false !== ($entry = $d->read())) {
124 //all top level names in the router should be blacklisted
125 $router = Router::get();
126 foreach(array_keys($router->m->getPaths()) as $path){
127 if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
128 $blacklist[]=$matches[1];
131 return !in_array($nickname, $blacklist);
134 function getCurrentNotice($dt=null)
136 $profile = $this->getProfile();
140 return $profile->getCurrentNotice($dt);
143 function getCarrier()
145 return Sms_carrier::staticGet('id', $this->carrier);
148 function subscribeTo($other)
150 $sub = new Subscription();
151 $sub->subscriber = $this->id;
152 $sub->subscribed = $other->id;
154 $sub->created = common_sql_now(); // current time
156 if (!$sub->insert()) {
163 function hasBlocked($other)
166 $block = Profile_block::get($this->id, $other->id);
168 if (is_null($block)) {
179 * Register a new user account and profile and set up default subscriptions.
180 * If a new-user welcome message is configured, this will be sent.
182 * @param array $fields associative array of optional properties
185 * bool 'email_confirmed' pass true to mark email as pre-confirmed
188 * string 'location' informal string description of geolocation
189 * float 'lat' decimal latitude for geolocation
190 * float 'lon' decimal longitude for geolocation
191 * int 'location_id' geoname identifier
192 * int 'location_ns' geoname namespace to interpret location_id
193 * string 'nickname' REQUIRED
194 * string 'password' (may be missing for eg OpenID registrations)
195 * string 'code' invite code
196 * ?string 'uri' permalink to notice; defaults to local notice URL
197 * @return mixed User object or false on failure
199 static function register($fields) {
201 // MAGICALLY put fields into current scope
205 $profile = new Profile();
207 $profile->query('BEGIN');
211 $email = common_canonical_email($email);
214 $nickname = common_canonical_nickname($nickname);
215 $profile->nickname = $nickname;
216 if(! User::allowed_nickname($nickname)){
217 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
220 $profile->profileurl = common_profile_url($nickname);
222 if (!empty($fullname)) {
223 $profile->fullname = $fullname;
225 if (!empty($homepage)) {
226 $profile->homepage = $homepage;
229 $profile->bio = $bio;
231 if (!empty($location)) {
232 $profile->location = $location;
234 $loc = Location::fromName($location);
237 $profile->lat = $loc->lat;
238 $profile->lon = $loc->lon;
239 $profile->location_id = $loc->location_id;
240 $profile->location_ns = $loc->location_ns;
244 $profile->created = common_sql_now();
246 $id = $profile->insert();
249 common_log_db_error($profile, 'INSERT', __FILE__);
256 $user->nickname = $nickname;
258 if (!empty($password)) { // may not have a password for OpenID users
259 $user->password = common_munge_password($password, $id);
262 // Users who respond to invite email have proven their ownership of that address
265 $invite = Invitation::staticGet($code);
266 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
267 $user->email = $invite->address;
271 if(isset($email_confirmed) && $email_confirmed) {
272 $user->email = $email;
275 // This flag is ignored but still set to 1
279 $user->created = common_sql_now();
280 $user->uri = common_user_uri($user);
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();
327 common_log_db_error($confirm, 'INSERT', __FILE__);
332 if (!empty($code) && $user->email) {
333 $user->emailChanged();
336 // Default system subscription
338 $defnick = common_config('newuser', 'default');
340 if (!empty($defnick)) {
341 $defuser = User::staticGet('nickname', $defnick);
342 if (empty($defuser)) {
343 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
346 $defsub = new Subscription();
347 $defsub->subscriber = $user->id;
348 $defsub->subscribed = $defuser->id;
349 $defsub->created = $user->created;
351 $result = $defsub->insert();
354 common_log_db_error($defsub, 'INSERT', __FILE__);
360 $profile->query('COMMIT');
362 if (!empty($email) && !$user->email) {
363 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
368 $welcome = common_config('newuser', 'welcome');
370 if (!empty($welcome)) {
371 $welcomeuser = User::staticGet('nickname', $welcome);
372 if (empty($welcomeuser)) {
373 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
376 $notice = Notice::saveNew($welcomeuser->id,
377 sprintf(_('Welcome to %1$s, @%2$s!'),
378 common_config('site', 'name'),
388 // Things we do when the email changes
390 function emailChanged()
393 $invites = new Invitation();
394 $invites->address = $this->email;
395 $invites->address_type = 'email';
397 if ($invites->find()) {
398 while ($invites->fetch()) {
399 $other = User::staticGet($invites->user_id);
400 subs_subscribe_to($other, $this);
405 function hasFave($notice)
407 $cache = common_memcache();
409 // XXX: Kind of a hack.
412 // This is the stream of favorite notices, in rev chron
413 // order. This forces it into cache.
415 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
417 // If it's in the list, then it's a fave
419 if (in_array($notice->id, $ids)) {
423 // If we're not past the end of the cache window,
424 // then the cache has all available faves, so this one
427 if (count($ids) < NOTICE_CACHE_WINDOW) {
431 // Otherwise, cache doesn't have all faves;
432 // fall through to the default
435 $fave = Fave::pkeyGet(array('user_id' => $this->id,
436 'notice_id' => $notice->id));
437 return ((is_null($fave)) ? false : true);
440 function mutuallySubscribed($other)
442 return $this->isSubscribed($other) &&
443 $other->isSubscribed($this);
446 function mutuallySubscribedUsers()
448 // 3-way join; probably should get cached
449 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
450 $qry = "SELECT $UT.* " .
451 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
452 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
453 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
454 "ORDER BY $UT.nickname";
456 $user->query(sprintf($qry, $this->id, $this->id));
461 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
463 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
464 return Notice::getStreamByIds($ids);
467 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
468 $profile = $this->getProfile();
472 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
476 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
478 $profile = $this->getProfile();
482 return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
486 function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
488 $ids = Fave::stream($this->id, $offset, $limit, $own);
489 return Notice::getStreamByIds($ids);
492 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
494 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
495 return Notice::getStreamByIds($ids);
498 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
500 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
501 return Notice::getStreamByIds($ids);
504 function friendsTimeline($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);
508 return Notice::getStreamByIds($ids);
511 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
513 $ids = Inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
515 return Notice::getStreamByIds($ids);
518 function blowFavesCache()
520 $cache = common_memcache();
522 // Faves don't happen chronologically, so we need to blow
524 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
525 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
526 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
527 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
529 $profile = $this->getProfile();
530 $profile->blowFaveCount();
533 function getSelfTags()
535 return Profile_tag::getTags($this->id, $this->id);
538 function setSelfTags($newtags)
540 return Profile_tag::setTags($this->id, $this->id, $newtags);
543 function block($other)
545 // Add a new block record
547 // no blocking (and thus unsubbing from) yourself
549 if ($this->id == $other->id) {
550 common_log(LOG_WARNING,
552 "Profile ID %d (%s) tried to block his or herself.",
560 $block = new Profile_block();
562 // Begin a transaction
564 $block->query('BEGIN');
566 $block->blocker = $this->id;
567 $block->blocked = $other->id;
569 $result = $block->insert();
572 common_log_db_error($block, 'INSERT', __FILE__);
576 // Cancel their subscription, if it exists
578 $otherUser = User::staticGet('id', $other->id);
580 if (!empty($otherUser)) {
581 subs_unsubscribe_to($otherUser, $this->getProfile());
584 $block->query('COMMIT');
589 function unblock($other)
591 // Get the block record
593 $block = Profile_block::get($this->id, $other->id);
599 $result = $block->delete();
602 common_log_db_error($block, 'DELETE', __FILE__);
609 function isMember($group)
611 $profile = $this->getProfile();
612 return $profile->isMember($group);
615 function isAdmin($group)
617 $profile = $this->getProfile();
618 return $profile->isAdmin($group);
621 function getGroups($offset=0, $limit=null)
624 'SELECT user_group.* ' .
625 'FROM user_group JOIN group_member '.
626 'ON user_group.id = group_member.group_id ' .
627 'WHERE group_member.profile_id = %d ' .
628 'ORDER BY group_member.created DESC ';
630 if ($offset>0 && !is_null($limit)) {
632 if (common_config('db','type') == 'pgsql') {
633 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
635 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
640 $groups = new User_group();
642 $cnt = $groups->query(sprintf($qry, $this->id));
647 function getSubscriptions($offset=0, $limit=null)
649 $profile = $this->getProfile();
650 assert(!empty($profile));
651 return $profile->getSubscriptions($offset, $limit);
654 function getSubscribers($offset=0, $limit=null)
656 $profile = $this->getProfile();
657 assert(!empty($profile));
658 return $profile->getSubscribers($offset, $limit);
661 function getTaggedSubscribers($tag, $offset=0, $limit=null)
664 'SELECT profile.* ' .
665 'FROM profile JOIN subscription ' .
666 'ON profile.id = subscription.subscriber ' .
667 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
668 'AND profile_tag.tagger = subscription.subscribed) ' .
669 'WHERE subscription.subscribed = %d ' .
670 "AND profile_tag.tag = '%s' " .
671 'AND subscription.subscribed != subscription.subscriber ' .
672 'ORDER BY subscription.created DESC ';
675 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
678 $profile = new Profile();
680 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
685 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
688 'SELECT profile.* ' .
689 'FROM profile JOIN subscription ' .
690 'ON profile.id = subscription.subscribed ' .
691 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
692 'AND profile_tag.tagger = subscription.subscriber) ' .
693 'WHERE subscription.subscriber = %d ' .
694 "AND profile_tag.tag = '%s' " .
695 'AND subscription.subscribed != subscription.subscriber ' .
696 'ORDER BY subscription.created DESC ';
698 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
700 $profile = new Profile();
702 $profile->query(sprintf($qry, $this->id, $tag));
709 return Design::staticGet('id', $this->design_id);
712 function hasRight($right)
714 $profile = $this->getProfile();
715 return $profile->hasRight($right);
720 $profile = $this->getProfile();
725 $related = array('Fave',
731 Event::handle('UserDeleteRelated', array($this, &$related));
733 foreach ($related as $cls) {
735 $inst->user_id = $this->id;
739 $this->_deleteTags();
740 $this->_deleteBlocks();
745 function _deleteTags()
747 $tag = new Profile_tag();
748 $tag->tagger = $this->id;
752 function _deleteBlocks()
754 $block = new Profile_block();
755 $block->blocker = $this->id;
757 // XXX delete group block? Reset blocker?
760 function hasRole($name)
762 $profile = $this->getProfile();
763 return $profile->hasRole($name);
766 function grantRole($name)
768 $profile = $this->getProfile();
769 return $profile->grantRole($name);
772 function revokeRole($name)
774 $profile = $this->getProfile();
775 return $profile->revokeRole($name);
778 function isSandboxed()
780 $profile = $this->getProfile();
781 return $profile->isSandboxed();
784 function isSilenced()
786 $profile = $this->getProfile();
787 return $profile->isSilenced();
790 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
792 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
794 'user:repeated_by_me:'.$this->id,
795 $offset, $limit, $since_id, $max_id, null);
797 return Notice::getStreamByIds($ids);
800 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id, $since)
802 $notice = new Notice();
804 $notice->selectAdd(); // clears it
805 $notice->selectAdd('id');
807 $notice->profile_id = $this->id;
808 $notice->whereAdd('repeat_of IS NOT NULL');
810 $notice->orderBy('id DESC');
812 if (!is_null($offset)) {
813 $notice->limit($offset, $limit);
816 if ($since_id != 0) {
817 $notice->whereAdd('id > ' . $since_id);
821 $notice->whereAdd('id <= ' . $max_id);
824 if (!is_null($since)) {
825 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
830 if ($notice->find()) {
831 while ($notice->fetch()) {
832 $ids[] = $notice->id;
842 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
844 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
846 'user:repeats_of_me:'.$this->id,
847 $offset, $limit, $since_id, $max_id, null);
849 return Notice::getStreamByIds($ids);
852 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id, $since)
855 'SELECT DISTINCT original.id AS id ' .
856 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
857 'WHERE original.profile_id = ' . $this->id . ' ';
859 if ($since_id != 0) {
860 $qry .= 'AND original.id > ' . $since_id . ' ';
864 $qry .= 'AND original.id <= ' . $max_id . ' ';
867 if (!is_null($since)) {
868 $qry .= 'AND original.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
871 // NOTE: we sort by fave time, not by notice time!
873 $qry .= 'ORDER BY original.id DESC ';
875 if (!is_null($offset)) {
876 $qry .= "LIMIT $limit OFFSET $offset";
881 $notice = new Notice();
883 $notice->query($qry);
885 while ($notice->fetch()) {
886 $ids[] = $notice->id;
895 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
897 throw new Exception("Not implemented since inbox change.");
900 function shareLocation()
902 $cfg = common_config('location', 'share');
904 if ($cfg == 'always') {
906 } else if ($cfg == 'never') {
911 $prefs = User_location_prefs::staticGet('user_id', $this->id);
914 $share = common_config('location', 'sharedefault');
916 $share = $prefs->share_location;