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();
212 $profile->query('BEGIN');
216 $email = common_canonical_email($email);
219 $nickname = common_canonical_nickname($nickname);
220 $profile->nickname = $nickname;
221 if(! User::allowed_nickname($nickname)){
222 common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
225 $profile->profileurl = common_profile_url($nickname);
227 if (!empty($fullname)) {
228 $profile->fullname = $fullname;
230 if (!empty($homepage)) {
231 $profile->homepage = $homepage;
234 $profile->bio = $bio;
236 if (!empty($location)) {
237 $profile->location = $location;
239 $loc = Location::fromName($location);
242 $profile->lat = $loc->lat;
243 $profile->lon = $loc->lon;
244 $profile->location_id = $loc->location_id;
245 $profile->location_ns = $loc->location_ns;
249 $profile->created = common_sql_now();
251 $id = $profile->insert();
254 common_log_db_error($profile, 'INSERT', __FILE__);
261 $user->nickname = $nickname;
263 if (!empty($password)) { // may not have a password for OpenID users
264 $user->password = common_munge_password($password, $id);
267 // Users who respond to invite email have proven their ownership of that address
270 $invite = Invitation::staticGet($code);
271 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
272 $user->email = $invite->address;
276 if(isset($email_confirmed) && $email_confirmed) {
277 $user->email = $email;
280 // This flag is ignored but still set to 1
284 $user->created = common_sql_now();
285 $user->uri = common_user_uri($user);
287 $result = $user->insert();
290 common_log_db_error($user, 'INSERT', __FILE__);
294 // Everyone is subscribed to themself
296 $subscription = new Subscription();
297 $subscription->subscriber = $user->id;
298 $subscription->subscribed = $user->id;
299 $subscription->created = $user->created;
301 $result = $subscription->insert();
304 common_log_db_error($subscription, 'INSERT', __FILE__);
308 if (!empty($email) && !$user->email) {
310 $confirm = new Confirm_address();
311 $confirm->code = common_confirmation_code(128);
312 $confirm->user_id = $user->id;
313 $confirm->address = $email;
314 $confirm->address_type = 'email';
316 $result = $confirm->insert();
318 common_log_db_error($confirm, 'INSERT', __FILE__);
323 if (!empty($code) && $user->email) {
324 $user->emailChanged();
327 // Default system subscription
329 $defnick = common_config('newuser', 'default');
331 if (!empty($defnick)) {
332 $defuser = User::staticGet('nickname', $defnick);
333 if (empty($defuser)) {
334 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
337 $defsub = new Subscription();
338 $defsub->subscriber = $user->id;
339 $defsub->subscribed = $defuser->id;
340 $defsub->created = $user->created;
342 $result = $defsub->insert();
345 common_log_db_error($defsub, 'INSERT', __FILE__);
351 $profile->query('COMMIT');
353 if (!empty($email) && !$user->email) {
354 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
359 $welcome = common_config('newuser', 'welcome');
361 if (!empty($welcome)) {
362 $welcomeuser = User::staticGet('nickname', $welcome);
363 if (empty($welcomeuser)) {
364 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
367 $notice = Notice::saveNew($welcomeuser->id,
368 sprintf(_('Welcome to %1$s, @%2$s!'),
369 common_config('site', 'name'),
372 common_broadcast_notice($notice);
379 // Things we do when the email changes
381 function emailChanged()
384 $invites = new Invitation();
385 $invites->address = $this->email;
386 $invites->address_type = 'email';
388 if ($invites->find()) {
389 while ($invites->fetch()) {
390 $other = User::staticGet($invites->user_id);
391 subs_subscribe_to($other, $this);
396 function hasFave($notice)
398 $cache = common_memcache();
400 // XXX: Kind of a hack.
403 // This is the stream of favorite notices, in rev chron
404 // order. This forces it into cache.
406 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
408 // If it's in the list, then it's a fave
410 if (in_array($notice->id, $ids)) {
414 // If we're not past the end of the cache window,
415 // then the cache has all available faves, so this one
418 if (count($ids) < NOTICE_CACHE_WINDOW) {
422 // Otherwise, cache doesn't have all faves;
423 // fall through to the default
426 $fave = Fave::pkeyGet(array('user_id' => $this->id,
427 'notice_id' => $notice->id));
428 return ((is_null($fave)) ? false : true);
431 function mutuallySubscribed($other)
433 return $this->isSubscribed($other) &&
434 $other->isSubscribed($this);
437 function mutuallySubscribedUsers()
439 // 3-way join; probably should get cached
440 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
441 $qry = "SELECT $UT.* " .
442 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
443 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
444 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
445 "ORDER BY $UT.nickname";
447 $user->query(sprintf($qry, $this->id, $this->id));
452 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
454 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
455 return Notice::getStreamByIds($ids);
458 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
459 $profile = $this->getProfile();
463 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
467 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
469 $profile = $this->getProfile();
473 return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
477 function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
479 $ids = Fave::stream($this->id, $offset, $limit, $own);
480 return Notice::getStreamByIds($ids);
483 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
485 $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
487 return Notice::getStreamByIds($ids);
490 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
492 $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
494 return Notice::getStreamByIds($ids);
497 function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
499 $ids = Notice::stream(array($this, '_friendsTimelineDirect'),
501 'user:friends_timeline:'.$this->id,
502 $offset, $limit, $since_id, $before_id, $since);
504 return Notice::getStreamByIds($ids);
507 function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
509 $ids = Notice::stream(array($this, '_friendsTimelineDirect'),
511 'user:friends_timeline_own:'.$this->id,
512 $offset, $limit, $since_id, $before_id, $since);
514 return Notice::getStreamByIds($ids);
517 function _friendsTimelineDirect($own, $offset, $limit, $since_id, $max_id, $since)
520 'SELECT notice.id AS id ' .
521 'FROM notice JOIN notice_inbox ON notice.id = notice_inbox.notice_id ' .
522 'WHERE notice_inbox.user_id = ' . $this->id . ' ' .
523 'AND notice.repeat_of IS NULL ';
526 // XXX: autoload notice inbox for constant
527 $inbox = new Notice_inbox();
529 $qry .= 'AND notice_inbox.source != ' . NOTICE_INBOX_SOURCE_GATEWAY . ' ';
532 if ($since_id != 0) {
533 $qry .= 'AND notice.id > ' . $since_id . ' ';
537 $qry .= 'AND notice.id <= ' . $max_id . ' ';
540 if (!is_null($since)) {
541 $qry .= 'AND notice.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
544 // NOTE: we sort by fave time, not by notice time!
546 $qry .= 'ORDER BY notice_id DESC ';
548 if (!is_null($offset)) {
549 $qry .= "LIMIT $limit OFFSET $offset";
554 $notice = new Notice();
556 $notice->query($qry);
558 while ($notice->fetch()) {
559 $ids[] = $notice->id;
568 function blowFavesCache()
570 $cache = common_memcache();
572 // Faves don't happen chronologically, so we need to blow
574 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
575 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
576 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
577 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
579 $profile = $this->getProfile();
580 $profile->blowFaveCount();
583 function getSelfTags()
585 return Profile_tag::getTags($this->id, $this->id);
588 function setSelfTags($newtags)
590 return Profile_tag::setTags($this->id, $this->id, $newtags);
593 function block($other)
595 // Add a new block record
597 // no blocking (and thus unsubbing from) yourself
599 if ($this->id == $other->id) {
600 common_log(LOG_WARNING,
602 "Profile ID %d (%s) tried to block his or herself.",
610 $block = new Profile_block();
612 // Begin a transaction
614 $block->query('BEGIN');
616 $block->blocker = $this->id;
617 $block->blocked = $other->id;
619 $result = $block->insert();
622 common_log_db_error($block, 'INSERT', __FILE__);
626 // Cancel their subscription, if it exists
628 $otherUser = User::staticGet('id', $other->id);
630 if (!empty($otherUser)) {
631 subs_unsubscribe_to($otherUser, $this->getProfile());
634 $block->query('COMMIT');
639 function unblock($other)
641 // Get the block record
643 $block = Profile_block::get($this->id, $other->id);
649 $result = $block->delete();
652 common_log_db_error($block, 'DELETE', __FILE__);
659 function isMember($group)
661 $profile = $this->getProfile();
662 return $profile->isMember($group);
665 function isAdmin($group)
667 $profile = $this->getProfile();
668 return $profile->isAdmin($group);
671 function getGroups($offset=0, $limit=null)
674 'SELECT user_group.* ' .
675 'FROM user_group JOIN group_member '.
676 'ON user_group.id = group_member.group_id ' .
677 'WHERE group_member.profile_id = %d ' .
678 'ORDER BY group_member.created DESC ';
680 if ($offset>0 && !is_null($limit)) {
682 if (common_config('db','type') == 'pgsql') {
683 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
685 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
690 $groups = new User_group();
692 $cnt = $groups->query(sprintf($qry, $this->id));
697 function getSubscriptions($offset=0, $limit=null)
699 $profile = $this->getProfile();
700 assert(!empty($profile));
701 return $profile->getSubscriptions($offset, $limit);
704 function getSubscribers($offset=0, $limit=null)
706 $profile = $this->getProfile();
707 assert(!empty($profile));
708 return $profile->getSubscribers($offset, $limit);
711 function getTaggedSubscribers($tag, $offset=0, $limit=null)
714 'SELECT profile.* ' .
715 'FROM profile JOIN subscription ' .
716 'ON profile.id = subscription.subscriber ' .
717 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
718 'AND profile_tag.tagger = subscription.subscribed) ' .
719 'WHERE subscription.subscribed = %d ' .
720 "AND profile_tag.tag = '%s' " .
721 'AND subscription.subscribed != subscription.subscriber ' .
722 'ORDER BY subscription.created DESC ';
725 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
728 $profile = new Profile();
730 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
735 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
738 'SELECT profile.* ' .
739 'FROM profile JOIN subscription ' .
740 'ON profile.id = subscription.subscribed ' .
741 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
742 'AND profile_tag.tagger = subscription.subscriber) ' .
743 'WHERE subscription.subscriber = %d ' .
744 "AND profile_tag.tag = '%s' " .
745 'AND subscription.subscribed != subscription.subscriber ' .
746 'ORDER BY subscription.created DESC ';
748 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
750 $profile = new Profile();
752 $profile->query(sprintf($qry, $this->id, $tag));
759 return Design::staticGet('id', $this->design_id);
762 function hasRight($right)
764 $profile = $this->getProfile();
765 return $profile->hasRight($right);
770 $profile = $this->getProfile();
775 $related = array('Fave',
782 Event::handle('UserDeleteRelated', array($this, &$related));
784 foreach ($related as $cls) {
786 $inst->user_id = $this->id;
790 $this->_deleteTags();
791 $this->_deleteBlocks();
796 function _deleteTags()
798 $tag = new Profile_tag();
799 $tag->tagger = $this->id;
803 function _deleteBlocks()
805 $block = new Profile_block();
806 $block->blocker = $this->id;
808 // XXX delete group block? Reset blocker?
811 function hasRole($name)
813 $profile = $this->getProfile();
814 return $profile->hasRole($name);
817 function grantRole($name)
819 $profile = $this->getProfile();
820 return $profile->grantRole($name);
823 function revokeRole($name)
825 $profile = $this->getProfile();
826 return $profile->revokeRole($name);
829 function isSandboxed()
831 $profile = $this->getProfile();
832 return $profile->isSandboxed();
835 function isSilenced()
837 $profile = $this->getProfile();
838 return $profile->isSilenced();
841 function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
843 $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
845 'user:repeated_by_me:'.$this->id,
846 $offset, $limit, $since_id, $max_id, null);
848 return Notice::getStreamByIds($ids);
851 function _repeatedByMeDirect($offset, $limit, $since_id, $max_id, $since)
853 $notice = new Notice();
855 $notice->selectAdd(); // clears it
856 $notice->selectAdd('id');
858 $notice->profile_id = $this->id;
859 $notice->whereAdd('repeat_of IS NOT NULL');
861 $notice->orderBy('id DESC');
863 if (!is_null($offset)) {
864 $notice->limit($offset, $limit);
867 if ($since_id != 0) {
868 $notice->whereAdd('id > ' . $since_id);
872 $notice->whereAdd('id <= ' . $max_id);
875 if (!is_null($since)) {
876 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
881 if ($notice->find()) {
882 while ($notice->fetch()) {
883 $ids[] = $notice->id;
893 function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
895 $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
897 'user:repeats_of_me:'.$this->id,
898 $offset, $limit, $since_id, $max_id, null);
900 return Notice::getStreamByIds($ids);
903 function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id, $since)
906 'SELECT DISTINCT original.id AS id ' .
907 'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
908 'WHERE original.profile_id = ' . $this->id . ' ';
910 if ($since_id != 0) {
911 $qry .= 'AND original.id > ' . $since_id . ' ';
915 $qry .= 'AND original.id <= ' . $max_id . ' ';
918 if (!is_null($since)) {
919 $qry .= 'AND original.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
922 // NOTE: we sort by fave time, not by notice time!
924 $qry .= 'ORDER BY original.id DESC ';
926 if (!is_null($offset)) {
927 $qry .= "LIMIT $limit OFFSET $offset";
932 $notice = new Notice();
934 $notice->query($qry);
936 while ($notice->fetch()) {
937 $ids[] = $notice->id;
946 function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
948 $ids = Notice::stream(array($this, '_repeatedToMeDirect'),
950 'user:repeated_to_me:'.$this->id,
951 $offset, $limit, $since_id, $max_id, null);
953 return Notice::getStreamByIds($ids);
956 function _repeatedToMeDirect($offset, $limit, $since_id, $max_id, $since)
959 'SELECT notice.id AS id ' .
960 'FROM notice JOIN notice_inbox ON notice.id = notice_inbox.notice_id ' .
961 'WHERE notice_inbox.user_id = ' . $this->id . ' ' .
962 'AND notice.repeat_of IS NOT NULL ';
964 if ($since_id != 0) {
965 $qry .= 'AND notice.id > ' . $since_id . ' ';
969 $qry .= 'AND notice.id <= ' . $max_id . ' ';
972 if (!is_null($since)) {
973 $qry .= 'AND notice.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
976 // NOTE: we sort by fave time, not by notice time!
978 $qry .= 'ORDER BY notice.id DESC ';
980 if (!is_null($offset)) {
981 $qry .= "LIMIT $limit OFFSET $offset";
986 $notice = new Notice();
988 $notice->query($qry);
990 while ($notice->fetch()) {
991 $ids[] = $notice->id;
1000 function shareLocation()
1004 $prefs = User_location_prefs::staticGet('user_id', $this->id);
1006 if (empty($prefs)) {
1007 $share = common_config('location', 'share');
1009 $share = $prefs->share_location;