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 = array();
123 //all directory and file names should be blacklisted
124 $d = dir(INSTALLDIR);
125 while (false !== ($entry = $d->read())) {
129 $merged = array_merge($blacklist, common_config('nickname', 'blacklist'));
130 return !in_array($nickname, $merged);
133 function getCurrentNotice($dt=null)
135 $profile = $this->getProfile();
139 return $profile->getCurrentNotice($dt);
142 function getCarrier()
144 return Sms_carrier::staticGet('id', $this->carrier);
147 function subscribeTo($other)
149 $sub = new Subscription();
150 $sub->subscriber = $this->id;
151 $sub->subscribed = $other->id;
153 $sub->created = common_sql_now(); // current time
155 if (!$sub->insert()) {
162 function hasBlocked($other)
165 $block = Profile_block::get($this->id, $other->id);
167 if (is_null($block)) {
177 static function register($fields) {
179 // MAGICALLY put fields into current scope
183 $profile = new Profile();
185 $profile->query('BEGIN');
187 $profile->nickname = $nickname;
188 $profile->profileurl = common_profile_url($nickname);
190 if (!empty($fullname)) {
191 $profile->fullname = $fullname;
193 if (!empty($homepage)) {
194 $profile->homepage = $homepage;
197 $profile->bio = $bio;
199 if (!empty($location)) {
200 $profile->location = $location;
202 $loc = Location::fromName($location);
205 $profile->lat = $loc->lat;
206 $profile->lon = $loc->lon;
207 $profile->location_id = $loc->location_id;
208 $profile->location_ns = $loc->location_ns;
212 $profile->created = common_sql_now();
214 $id = $profile->insert();
217 common_log_db_error($profile, 'INSERT', __FILE__);
224 $user->nickname = $nickname;
226 if (!empty($password)) { // may not have a password for OpenID users
227 $user->password = common_munge_password($password, $id);
230 // Users who respond to invite email have proven their ownership of that address
233 $invite = Invitation::staticGet($code);
234 if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
235 $user->email = $invite->address;
239 // This flag is ignored but still set to 1
243 $user->created = common_sql_now();
244 $user->uri = common_user_uri($user);
246 $result = $user->insert();
249 common_log_db_error($user, 'INSERT', __FILE__);
253 // Everyone is subscribed to themself
255 $subscription = new Subscription();
256 $subscription->subscriber = $user->id;
257 $subscription->subscribed = $user->id;
258 $subscription->created = $user->created;
260 $result = $subscription->insert();
263 common_log_db_error($subscription, 'INSERT', __FILE__);
267 if (!empty($email) && !$user->email) {
269 $confirm = new Confirm_address();
270 $confirm->code = common_confirmation_code(128);
271 $confirm->user_id = $user->id;
272 $confirm->address = $email;
273 $confirm->address_type = 'email';
275 $result = $confirm->insert();
277 common_log_db_error($confirm, 'INSERT', __FILE__);
282 if (!empty($code) && $user->email) {
283 $user->emailChanged();
286 // Default system subscription
288 $defnick = common_config('newuser', 'default');
290 if (!empty($defnick)) {
291 $defuser = User::staticGet('nickname', $defnick);
292 if (empty($defuser)) {
293 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
296 $defsub = new Subscription();
297 $defsub->subscriber = $user->id;
298 $defsub->subscribed = $defuser->id;
299 $defsub->created = $user->created;
301 $result = $defsub->insert();
304 common_log_db_error($defsub, 'INSERT', __FILE__);
310 $profile->query('COMMIT');
312 if ($email && !$user->email) {
313 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
318 $welcome = common_config('newuser', 'welcome');
320 if (!empty($welcome)) {
321 $welcomeuser = User::staticGet('nickname', $welcome);
322 if (empty($welcomeuser)) {
323 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
326 $notice = Notice::saveNew($welcomeuser->id,
327 sprintf(_('Welcome to %1$s, @%2$s!'),
328 common_config('site', 'name'),
331 common_broadcast_notice($notice);
338 // Things we do when the email changes
340 function emailChanged()
343 $invites = new Invitation();
344 $invites->address = $this->email;
345 $invites->address_type = 'email';
347 if ($invites->find()) {
348 while ($invites->fetch()) {
349 $other = User::staticGet($invites->user_id);
350 subs_subscribe_to($other, $this);
355 function hasFave($notice)
357 $cache = common_memcache();
359 // XXX: Kind of a hack.
362 // This is the stream of favorite notices, in rev chron
363 // order. This forces it into cache.
365 $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
367 // If it's in the list, then it's a fave
369 if (in_array($notice->id, $ids)) {
373 // If we're not past the end of the cache window,
374 // then the cache has all available faves, so this one
377 if (count($ids) < NOTICE_CACHE_WINDOW) {
381 // Otherwise, cache doesn't have all faves;
382 // fall through to the default
385 $fave = Fave::pkeyGet(array('user_id' => $this->id,
386 'notice_id' => $notice->id));
387 return ((is_null($fave)) ? false : true);
390 function mutuallySubscribed($other)
392 return $this->isSubscribed($other) &&
393 $other->isSubscribed($this);
396 function mutuallySubscribedUsers()
398 // 3-way join; probably should get cached
399 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
400 $qry = "SELECT $UT.* " .
401 "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
402 "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
403 'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
404 "ORDER BY $UT.nickname";
406 $user->query(sprintf($qry, $this->id, $this->id));
411 function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
413 $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
414 return Notice::getStreamByIds($ids);
417 function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
418 $profile = $this->getProfile();
422 return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
426 function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
428 $profile = $this->getProfile();
432 return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
436 function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
438 $ids = Fave::stream($this->id, $offset, $limit, $own);
439 return Notice::getStreamByIds($ids);
442 function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
444 $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
446 return Notice::getStreamByIds($ids);
449 function noticeInbox($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, true);
453 return Notice::getStreamByIds($ids);
456 function blowFavesCache()
458 $cache = common_memcache();
460 // Faves don't happen chronologically, so we need to blow
462 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
463 $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
464 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
465 $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
467 $profile = $this->getProfile();
468 $profile->blowFaveCount();
471 function getSelfTags()
473 return Profile_tag::getTags($this->id, $this->id);
476 function setSelfTags($newtags)
478 return Profile_tag::setTags($this->id, $this->id, $newtags);
481 function block($other)
483 // Add a new block record
485 $block = new Profile_block();
487 // Begin a transaction
489 $block->query('BEGIN');
491 $block->blocker = $this->id;
492 $block->blocked = $other->id;
494 $result = $block->insert();
497 common_log_db_error($block, 'INSERT', __FILE__);
501 // Cancel their subscription, if it exists
503 $sub = Subscription::pkeyGet(array('subscriber' => $other->id,
504 'subscribed' => $this->id));
507 $result = $sub->delete();
509 common_log_db_error($sub, 'DELETE', __FILE__);
514 $block->query('COMMIT');
519 function unblock($other)
521 // Get the block record
523 $block = Profile_block::get($this->id, $other->id);
529 $result = $block->delete();
532 common_log_db_error($block, 'DELETE', __FILE__);
539 function isMember($group)
541 $profile = $this->getProfile();
542 return $profile->isMember($group);
545 function isAdmin($group)
547 $profile = $this->getProfile();
548 return $profile->isAdmin($group);
551 function getGroups($offset=0, $limit=null)
554 'SELECT user_group.* ' .
555 'FROM user_group JOIN group_member '.
556 'ON user_group.id = group_member.group_id ' .
557 'WHERE group_member.profile_id = %d ' .
558 'ORDER BY group_member.created DESC ';
561 if (common_config('db','type') == 'pgsql') {
562 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
564 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
568 $groups = new User_group();
570 $cnt = $groups->query(sprintf($qry, $this->id));
575 function getSubscriptions($offset=0, $limit=null)
577 $profile = $this->getProfile();
578 assert(!empty($profile));
579 return $profile->getSubscriptions($offset, $limit);
582 function getSubscribers($offset=0, $limit=null)
584 $profile = $this->getProfile();
585 assert(!empty($profile));
586 return $profile->getSubscribers($offset, $limit);
589 function getTaggedSubscribers($tag, $offset=0, $limit=null)
592 'SELECT profile.* ' .
593 'FROM profile JOIN subscription ' .
594 'ON profile.id = subscription.subscriber ' .
595 'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
596 'AND profile_tag.tagger = subscription.subscribed) ' .
597 'WHERE subscription.subscribed = %d ' .
598 "AND profile_tag.tag = '%s' " .
599 'AND subscription.subscribed != subscription.subscriber ' .
600 'ORDER BY subscription.created DESC ';
603 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
606 $profile = new Profile();
608 $cnt = $profile->query(sprintf($qry, $this->id, $tag));
613 function getTaggedSubscriptions($tag, $offset=0, $limit=null)
616 'SELECT profile.* ' .
617 'FROM profile JOIN subscription ' .
618 'ON profile.id = subscription.subscribed ' .
619 'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
620 'AND profile_tag.tagger = subscription.subscriber) ' .
621 'WHERE subscription.subscriber = %d ' .
622 "AND profile_tag.tag = '%s' " .
623 'AND subscription.subscribed != subscription.subscriber ' .
624 'ORDER BY subscription.created DESC ';
626 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
628 $profile = new Profile();
630 $profile->query(sprintf($qry, $this->id, $tag));
637 return Design::staticGet('id', $this->design_id);
640 function hasRole($name)
642 $role = User_role::pkeyGet(array('user_id' => $this->id,
644 return (!empty($role));
647 function grantRole($name)
649 $role = new User_role();
651 $role->user_id = $this->id;
653 $role->created = common_sql_now();
655 $result = $role->insert();
658 common_log_db_error($role, 'INSERT', __FILE__);
665 function revokeRole($name)
667 $role = User_role::pkeyGet(array('user_id' => $this->id,
671 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
674 $result = $role->delete();
677 common_log_db_error($role, 'DELETE', __FILE__);
678 throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
685 * Does this user have the right to do X?
687 * With our role-based authorization, this is merely a lookup for whether the user
688 * has a particular role. The implementation currently uses a switch statement
689 * to determine if the user has the pre-defined role to exercise the right. Future
690 * implementations may allow per-site roles, and different mappings of roles to rights.
692 * @param $right string Name of the right, usually a constant in class Right
693 * @return boolean whether the user has the right in question
696 function hasRight($right)
699 if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
702 case Right::deleteOthersNotice:
703 $result = $this->hasRole('moderator');
715 $profile = $this->getProfile();
718 $related = array('Fave',
727 foreach ($related as $cls) {
729 $inst->user_id = $this->id;
733 $this->_deleteTags();
734 $this->_deleteBlocks();
739 function _deleteTags()
741 $tag = new Profile_tag();
742 $tag->tagger = $this->id;
746 function _deleteBlocks()
748 $block = new Profile_block();
749 $block->blocker = $this->id;
751 // XXX delete group block? Reset blocker?