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 function allowed_nickname($nickname)
119 // 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);
140 function getCurrentNotice($dt=null)
142 $profile = $this->getProfile();
146 return $profile->getCurrentNotice($dt);
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)
172 $block = Profile_block::get($this->id, $other->id);
174 if (is_null($block)) {
184 static function register($fields) {
186 // MAGICALLY put fields into current scope
190 $profile = new Profile();
192 $profile->query('BEGIN');
194 $profile->nickname = $nickname;
195 $profile->profileurl = common_profile_url($nickname);
197 if (!empty($fullname)) {
198 $profile->fullname = $fullname;
200 if (!empty($homepage)) {
201 $profile->homepage = $homepage;
204 $profile->bio = $bio;
206 if (!empty($location)) {
207 $profile->location = $location;
209 $loc = Location::fromName($location);
212 $profile->lat = $loc->lat;
213 $profile->lon = $loc->lon;
214 $profile->location_id = $loc->location_id;
215 $profile->location_ns = $loc->location_ns;
219 $profile->created = common_sql_now();
221 $id = $profile->insert();
224 common_log_db_error($profile, 'INSERT', __FILE__);
231 $user->nickname = $nickname;
233 if (!empty($password)) { // may not have a password for OpenID users
234 $user->password = common_munge_password($password, $id);
237 // Users who respond to invite email have proven their ownership of that address
240 $invite = Invitation::staticGet($code);
241 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
242 $user->email = $invite->address;
246 // This flag is ignored but still set to 1
250 $user->created = common_sql_now();
251 $user->uri = common_user_uri($user);
253 $result = $user->insert();
256 common_log_db_error($user, 'INSERT', __FILE__);
260 // Everyone is subscribed to themself
262 $subscription = new Subscription();
263 $subscription->subscriber = $user->id;
264 $subscription->subscribed = $user->id;
265 $subscription->created = $user->created;
267 $result = $subscription->insert();
270 common_log_db_error($subscription, 'INSERT', __FILE__);
274 if (!empty($email) && !$user->email) {
276 $confirm = new Confirm_address();
277 $confirm->code = common_confirmation_code(128);
278 $confirm->user_id = $user->id;
279 $confirm->address = $email;
280 $confirm->address_type = 'email';
282 $result = $confirm->insert();
284 common_log_db_error($confirm, 'INSERT', __FILE__);
289 if (!empty($code) && $user->email) {
290 $user->emailChanged();
293 // Default system subscription
295 $defnick = common_config('newuser', 'default');
297 if (!empty($defnick)) {
298 $defuser = User::staticGet('nickname', $defnick);
299 if (empty($defuser)) {
300 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
303 $defsub = new Subscription();
304 $defsub->subscriber = $user->id;
305 $defsub->subscribed = $defuser->id;
306 $defsub->created = $user->created;
308 $result = $defsub->insert();
311 common_log_db_error($defsub, 'INSERT', __FILE__);
317 $profile->query('COMMIT');
319 if ($email && !$user->email) {
320 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
325 $welcome = common_config('newuser', 'welcome');
327 if (!empty($welcome)) {
328 $welcomeuser = User::staticGet('nickname', $welcome);
329 if (empty($welcomeuser)) {
330 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
333 $notice = Notice::saveNew($welcomeuser->id,
334 sprintf(_('Welcome to %1$s, @%2$s!'),
335 common_config('site', 'name'),
338 common_broadcast_notice($notice);
345 // Things we do when the email changes
347 function emailChanged()
350 $invites = new Invitation();
351 $invites->address = $this->email;
352 $invites->address_type = 'email';
354 if ($invites->find()) {
355 while ($invites->fetch()) {
356 $other = User::staticGet($invites->user_id);
357 subs_subscribe_to($other, $this);
362 function hasFave($notice)
364 $cache = common_memcache();
366 // XXX: Kind of a hack.
369 // This is the stream of favorite notices, in rev chron
370 // order. This forces it into cache.
372 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
374 // If it's in the list, then it's a fave
376 if (in_array($notice->id, $ids)) {
380 // If we're not past the end of the cache window,
381 // then the cache has all available faves, so this one
384 if (count($ids) < NOTICE_CACHE_WINDOW) {
388 // Otherwise, cache doesn't have all faves;
389 // fall through to the default
392 $fave = Fave::pkeyGet(array('user_id' => $this->id,
393 'notice_id' => $notice->id));
394 return ((is_null($fave)) ? false : true);
397 function mutuallySubscribed($other)
399 return $this->isSubscribed($other) &&
400 $other->isSubscribed($this);
403 function mutuallySubscribedUsers()
405 // 3-way join; probably should get cached
406 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
407 $qry = "SELECT $UT.* " .
408 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
409 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
410 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
411 "ORDER BY $UT.nickname";
413 $user->query(sprintf($qry, $this->id, $this->id));
418 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
420 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
421 return Notice::getStreamByIds($ids);
424 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
425 $profile = $this->getProfile();
429 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
433 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
435 $profile = $this->getProfile();
439 return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
443 function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
445 $ids = Fave::stream($this->id, $offset, $limit, $own);
446 return Notice::getStreamByIds($ids);
449 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
451 $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
453 return Notice::getStreamByIds($ids);
456 function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
458 $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
460 return Notice::getStreamByIds($ids);
463 function blowFavesCache()
465 $cache = common_memcache();
467 // Faves don't happen chronologically, so we need to blow
469 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
470 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
471 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
472 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
474 $profile = $this->getProfile();
475 $profile->blowFaveCount();
478 function getSelfTags()
480 return Profile_tag::getTags($this->id, $this->id);
483 function setSelfTags($newtags)
485 return Profile_tag::setTags($this->id, $this->id, $newtags);
488 function block($other)
490 // Add a new block record
492 $block = new Profile_block();
494 // Begin a transaction
496 $block->query('BEGIN');
498 $block->blocker = $this->id;
499 $block->blocked = $other->id;
501 $result = $block->insert();
504 common_log_db_error($block, 'INSERT', __FILE__);
508 // Cancel their subscription, if it exists
510 $sub = Subscription::pkeyGet(array('subscriber' => $other->id,
511 'subscribed' => $this->id));
514 $result = $sub->delete();
516 common_log_db_error($sub, 'DELETE', __FILE__);
521 $block->query('COMMIT');
526 function unblock($other)
528 // Get the block record
530 $block = Profile_block::get($this->id, $other->id);
536 $result = $block->delete();
539 common_log_db_error($block, 'DELETE', __FILE__);
546 function isMember($group)
548 $profile = $this->getProfile();
549 return $profile->isMember($group);
552 function isAdmin($group)
554 $profile = $this->getProfile();
555 return $profile->isAdmin($group);
558 function getGroups($offset=0, $limit=null)
561 'SELECT user_group.* ' .
562 'FROM user_group JOIN group_member '.
563 'ON user_group.id = group_member.group_id ' .
564 'WHERE group_member.profile_id = %d ' .
565 'ORDER BY group_member.created DESC ';
568 if (common_config('db','type') == 'pgsql') {
569 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
571 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
575 $groups = new User_group();
577 $cnt = $groups->query(sprintf($qry, $this->id));
582 function getSubscriptions($offset=0, $limit=null)
584 $profile = $this->getProfile();
585 assert(!empty($profile));
586 return $profile->getSubscriptions($offset, $limit);
589 function getSubscribers($offset=0, $limit=null)
591 $profile = $this->getProfile();
592 assert(!empty($profile));
593 return $profile->getSubscribers($offset, $limit);
596 function getTaggedSubscribers($tag, $offset=0, $limit=null)
599 'SELECT profile.* ' .
600 'FROM profile JOIN subscription ' .
601 'ON profile.id = subscription.subscriber ' .
602 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
603 'AND profile_tag.tagger = subscription.subscribed) ' .
604 'WHERE subscription.subscribed = %d ' .
605 "AND profile_tag.tag = '%s' " .
606 'AND subscription.subscribed != subscription.subscriber ' .
607 'ORDER BY subscription.created DESC ';
610 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
613 $profile = new Profile();
615 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
620 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
623 'SELECT profile.* ' .
624 'FROM profile JOIN subscription ' .
625 'ON profile.id = subscription.subscribed ' .
626 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
627 'AND profile_tag.tagger = subscription.subscriber) ' .
628 'WHERE subscription.subscriber = %d ' .
629 "AND profile_tag.tag = '%s' " .
630 'AND subscription.subscribed != subscription.subscriber ' .
631 'ORDER BY subscription.created DESC ';
633 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
635 $profile = new Profile();
637 $profile->query(sprintf($qry, $this->id, $tag));
644 return Design::staticGet('id', $this->design_id);
647 function hasRole($name)
649 $role = User_role::pkeyGet(array('user_id' => $this->id,
651 return (!empty($role));
654 function grantRole($name)
656 $role = new User_role();
658 $role->user_id = $this->id;
660 $role->created = common_sql_now();
662 $result = $role->insert();
665 common_log_db_error($role, 'INSERT', __FILE__);
672 function revokeRole($name)
674 $role = User_role::pkeyGet(array('user_id' => $this->id,
678 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
681 $result = $role->delete();
684 common_log_db_error($role, 'DELETE', __FILE__);
685 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
692 * Does this user have the right to do X?
694 * With our role-based authorization, this is merely a lookup for whether the user
695 * has a particular role. The implementation currently uses a switch statement
696 * to determine if the user has the pre-defined role to exercise the right. Future
697 * implementations may allow per-site roles, and different mappings of roles to rights.
699 * @param $right string Name of the right, usually a constant in class Right
700 * @return boolean whether the user has the right in question
703 function hasRight($right)
706 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
709 case Right::deleteOthersNotice:
710 $result = $this->hasRole('moderator');
722 $profile = $this->getProfile();
725 $related = array('Fave',
734 foreach ($related as $cls) {
736 $inst->user_id = $this->id;
740 $this->_deleteTags();
741 $this->_deleteBlocks();
746 function _deleteTags()
748 $tag = new Profile_tag();
749 $tag->tagger = $this->id;
753 function _deleteBlocks()
755 $block = new Profile_block();
756 $block->blocker = $this->id;
758 // XXX delete group block? Reset blocker?