Beispiel #1
0
 public static function resourceLimiter($name, $seconds)
 {
     global $User;
     /* 
     				Disabled while fixing https://github.com/kestasjk/webDiplomacy/issues/159
     				At the time of writing (5 Aug 2015), no code that calls this function
     				needs users to be logged in, so disabling this seems safe.
     
     		if( !$User->type['User'] )
     			libHTML::notice(
     				l_t('Denied'),
     				l_t("Please <a href='register.php' class='light'>register</a> or ".
     					"<a href='logon.php' class='light'>log in</a> to %s.",l_t($name))
     			);
     */
     if (!isset($_SESSION['resources'])) {
         $_SESSION['resources'] = array();
     }
     if (isset($_SESSION['resources'][$name]) && time() - $_SESSION['resources'][$name] < $seconds) {
         libHTML::notice(l_t('Denied'), l_t("One %s per %s seconds, please wait and try again.", $name, $seconds));
     }
     $_SESSION['resources'][$name] = time();
 }
Beispiel #2
0
 /**
  * Log-on, create/update a session record, and take information for user access logging for meta-gamers
  */
 function logon()
 {
     global $DB;
     session_name('wD_Sess_User-' . $this->id);
     /*if( $this->type['User'] )
     			session_cache_limiter('private_no_expire');
     		else
     			session_cache_limiter('public');*/
     session_start();
     // Non-users can't get banned
     if ($this->type['Guest']) {
         return;
     }
     if (isset($_SERVER['HTTP_USER_AGENT'])) {
         $userAgentHash = substr(md5($_SERVER['HTTP_USER_AGENT']), 0, 4);
     } else {
         $userAgentHash = '0000';
     }
     if (!isset($_COOKIE['wD_Code']) or intval($_COOKIE['wD_Code']) == 0 or intval($_COOKIE['wD_Code']) == 1) {
         // Making this larger than 2^31 makes it negative..
         $cookieCode = rand(2, 2000000000);
         setcookie('wD_Code', $cookieCode, time() + 365 * 7 * 24 * 60 * 60);
     } else {
         $cookieCode = (int) $_COOKIE['wD_Code'];
     }
     if ($this->type['Banned']) {
         libHTML::notice(l_t('Banned'), l_t('You have been banned from this server. If you think there has been a mistake contact the moderator team at %s , and if you still aren\'t satisfied contact the admin at %s (with details of what happened).', Config::$modEMail, Config::$adminEMail));
     }
     /*
     		$bans=array();
     		$tabl = $DB->sql_tabl("SELECT numberType, number, userID FROM wD_BannedNumbers
     			WHERE ( number = INET_ATON('".$_SERVER['REMOTE_ADDR']."') AND numberType='IP')
     				OR ( number = ".$cookieCode." AND numberType='CookieCode')
     				OR ( userID=".$this->id.")");
     		while(list($banType,$banNum)=$DB->tabl_row($tabl))
     			$bans[$banType]=$banNum;
     
     		if($this->type['Banned'])
     		{
     			//if( isset($bans['IP']) and $cookieCode!=$bans['CookieCode'] )
     				//setcookie('wD_Code', $bans['CookieCode'],time()+365*7*24*60*60);
     
     			if(!isset($bans['IP']) || ip2long($_SERVER['REMOTE_ADDR'])!=$bans['IP'])
     				self::banIP(ip2long($_SERVER['REMOTE_ADDR']), $this->id);
     
     			libHTML::notice('Banned', 'You have been banned from this server. If you think there has been
     					a mistake contact '.Config::$adminEMail.' .');
     		}
     		elseif( isset($bans['IP']) )
     		{
     			self::banUser($this->id,"You share an IP with a banned user account.", $_SERVER['REMOTE_ADDR']);
     			libHTML::notice('Banned', 'You have been banned from this server. If you think there has been
     				a mistake contact '.Config::$adminEMail.' .');
     		}*/
     $DB->sql_put("INSERT INTO wD_Sessions (userID, lastRequest, hits, ip, userAgent, cookieCode)\r\n\t\t\t\t\tVALUES (" . $this->id . ",CURRENT_TIMESTAMP,1, INET_ATON('" . $_SERVER['REMOTE_ADDR'] . "'),\r\n\t\t\t\t\t\t\tUNHEX('" . $userAgentHash . "'), " . $cookieCode . " )\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE hits=hits+1");
     $this->online = true;
 }
Beispiel #3
0
$onlineUsers = array();
while (list($userID) = $DB->tabl_row($tabl)) {
    $onlineUsers[] = $userID;
}
file_put_contents($onlineFile, 'onlineUsers=$A([' . implode(',', $onlineUsers) . ']);');
//- Update misc values (if running as admin/mod)
if (!$User->type['System'] || time() % (15 * 60) <= 5 * 60) {
    print l_t('Updating Misc values') . '<br />';
    miscUpdate::errorLog();
    miscUpdate::forum();
    miscUpdate::game();
    miscUpdate::user();
}
//- Check last process time, pause processing/save current process time
if (time() - $Misc->LastProcessTime > Config::$downtimeTriggerMinutes * 60) {
    libHTML::notice(l_t('Games not processing'), libHTML::admincp('resetLastProcessTime', null, l_t('Continue processing now')));
}
$Misc->LastProcessTime = time();
$Misc->write();
$startTime = time();
// Only do ~30 sec of processing per cycle
$tabl = $DB->sql_tabl("SELECT * FROM wD_Games\r\n\tWHERE processStatus='Not-processing' AND processTime <= " . time() . " AND NOT phase='Finished'");
while (time() - $startTime < 30 && ($gameRow = $DB->tabl_hash($tabl))) {
    $Variant = libVariant::loadFromVariantID($gameRow['variantID']);
    $Game = $Variant->Game($gameRow);
    print '<a href="board.php?gameID=' . $Game->id . '">gameID=' . $Game->id . ': ' . $Game->name . '</a>: ';
    try {
        if ($Game->processStatus != 'Crashed' && $Game->attempts > count($Game->Members->ByID) * 2) {
            $Game = $Variant->processGame($Game->id);
            $Game->crashed();
            $DB->sql_put("COMMIT");
Beispiel #4
0
} elseif (isset($_SESSION['viewthread'])) {
    $viewthread = $_SESSION['viewthread'];
}
if (!$viewthread) {
    $viewthread = false;
}
$forumPager = new PagerForum($Misc->ForumThreads);
//$pageCount = $currentPage = ceil(($Misc->ForumThreads+1)/$forumPager->pageCount);
if (!isset($_SESSION['lastSeenForum']) || $_SESSION['lastSeenForum'] < $User->timeLastSessionEnded) {
    $_SESSION['lastSeenForum'] = $User->timeLastSessionEnded;
}
if (!isset($_REQUEST['page']) && isset($_REQUEST['viewthread']) && $viewthread) {
    unset($orderIndex);
    list($orderIndex) = $DB->sql_row("SELECT b.latestReplySent FROM wD_ForumMessages b WHERE b.id = " . $viewthread);
    if (!isset($orderIndex) || !$orderIndex) {
        libHTML::notice(l_t('Thread not found'), l_t("The thread you requested wasn't found."));
    }
    list($position) = $DB->sql_row("SELECT COUNT(*)-1 FROM wD_ForumMessages a WHERE a.latestReplySent >= " . $orderIndex . " AND a.type='ThreadStart'");
    $forumPager->currentPage = $forumPager->pageCount - floor($position / PagerForum::$defaultPostsPerPage);
}
if (!isset($_REQUEST['newmessage'])) {
    $_REQUEST['newmessage'] = '';
}
if (!isset($_REQUEST['newsubject'])) {
    $_REQUEST['newsubject'] = '';
}
$new = array('message' => "", 'subject' => "", 'id' => -1);
if (isset($_REQUEST['newmessage']) and $User->type['User'] and $_REQUEST['newmessage'] != "") {
    // We're being asked to send a message.
    $new['message'] = $DB->msg_escape($_REQUEST['newmessage']);
    if (isset($_REQUEST['newsubject'])) {
Beispiel #5
0
                $types[] = $type;
            }
        }
        $types = implode(',', $types);
        $DB->sql_put("UPDATE wD_Users SET type = '" . $types . "' WHERE id = " . $User->id);
        $User->type['Donator'] = false;
        libHTML::notice(l_t("Opt-out"), l_t("You've decided to re-add the Plura applet, thanks! By running the Plura applet you " . "help keep this server running."));
    }
}
if (isset($_REQUEST['emailToken'])) {
    if (!($email = libAuth::emailToken_email($_REQUEST['emailToken']))) {
        libHTML::notice(l_t("E-mail change validation"), l_t("A bad e-mail token was given, please check the validation link try again"));
    }
    $email = $DB->escape($email);
    if (User::findEmail($email)) {
        libHTML::notice(l_t("E-mail change validation"), l_t("The given e-mail address is already in use, please use a unique e-mail address"));
    }
    $DB->sql_put("UPDATE wD_Users SET email='" . $email . "' WHERE id = " . $User->id);
    $User->email = $email;
    print '<div class="content"><p class="notice">' . l_t('Your e-mail address has been succesfully changed') . '</p></div>';
}
if (isset($_REQUEST['userForm'])) {
    $formOutput = '';
    try {
        $errors = array();
        $SQLVars = User::processForm($_REQUEST['userForm'], $errors);
        if (count($errors)) {
            throw new Exception(implode('. ', $errors));
        }
        unset($errors);
        $allowed = array('E-mail' => 'email', 'E-mail hiding' => 'hideEmail', 'Homepage' => 'homepage', 'Comment' => 'comment');
Beispiel #6
0
    if (!$fb_user) {
        if (!isset($_REQUEST['wD_FB_AuthNow'])) {
            libHTML::notice(l_t('Not authorized'), l_t('To play in webDiplomacy games you need to authorize this application, so that ' . 'it can send you notifications informing you when a game you\'re playing in needs your attention. ' . 'Please <a href="index.php?wD_FB_AuthNow=on">authorize this application</a> to continue.'));
        } else {
            $fb_user = $facebook->require_login();
        }
    }
}
require_once l_r('lib/auth.php');
if (!defined('AJAX')) {
    if (isset($_REQUEST['logoff'])) {
        $success = libAuth::keyWipe();
        $User = new User(GUESTID);
        // Give him a guest $User
        header('refresh: 4; url=logon.php?noRefresh=on');
        libHTML::notice(l_t("Logged out"), l_t("You have been logged out, and are being redirected to the logon page."));
    }
    global $User;
    $User = libAuth::auth();
    if ($User->type['Admin']) {
        Config::$debug = true;
        if (isset($_REQUEST['auid']) || isset($_SESSION['auid'])) {
            $User = libAuth::adminUserSwitch($User);
        } else {
            define('AdminUserSwitch', $User->id);
        }
    } elseif ($Misc->Maintenance) {
        unset($DB);
        // This lets libHTML know there's a problem
        libHTML::error(Config::$serverMessages['Maintenance']);
    }
Beispiel #7
0
    die;
}
if ($User->type['Admin'] && isset($_REQUEST['viewErrorLog'])) {
    $log = (int) $_REQUEST['viewErrorLog'];
    if (!($data = file_get_contents(Config::errorlogDirectory() . '/' . $log . '.txt'))) {
        trigger_error(l_t("Couldn't open file %s.txt", $log));
    }
    header('Content-type:text/plain');
    print $data;
    die;
}
if ($User->type['Admin'] && isset($_REQUEST['systemTask'])) {
    if ($Misc->Maintenance == 0) {
        $Misc->Maintenance = 1;
        $Misc->write();
        libHTML::notice(l_t('Wait'), l_t("Make sure you're in maintenance-mode and no-one " . "else is using the system before running a system-task!") . "<br /> " . l_t("Maintenance mode has been set, please wait 3 mins to make sure all " . "other users are done, then click " . "<a href='admincp.php?systemTask=%s'>here</a> to " . "run the system-task safely.", $_REQUEST['systemTask']) . "<br /><br /> " . l_t("Once it has run successfully, maintenance-mode can be disabled."));
    } else {
        ini_set('memory_limit', "32M");
        // 8M is the default
        ini_set('max_execution_time', '120');
        switch ($_REQUEST['systemTask']) {
            case 'defragTables':
                require_once l_r('admin/systemTasks/defragTables.php');
                die;
            case 'resetCountryIDBalancer':
                require_once l_r('admin/systemTasks/resetCountryIDBalancer.php');
                die;
        }
    }
}
libHTML::starthtml();
Beispiel #8
0
 static function checkDeleteNote()
 {
     global $User, $DB;
     if (!$User->type['Moderator'] || !isset($_REQUEST['modNoteDelete'])) {
         return;
     }
     $params = explode('_', $_REQUEST['modNoteDelete']);
     if (count($params) != 3 || $params[0] != 'User' && $params[0] != 'Game') {
         throw new Exception("Invalid mod-note deletion command given");
     }
     list($linkIDType, $linkID, $timeSent) = $params;
     $linkID = (int) $linkID;
     $timeSent = (int) $timeSent;
     $DB->sql_put("DELETE FROM wD_ModeratorNotes WHERE linkIDType='" . $linkIDType . "' AND linkID=" . $linkID . " AND timeSent=" . $timeSent);
     libHTML::notice('Deleted', 'Moderator note successfully deleted.');
 }
Beispiel #9
0
 /**
  * Redirect to a game after joining it. Script ends here.
  */
 function joinedRedirect()
 {
     // We have successfully joined, now give a message to tell the user so
     header('refresh: 4; url=board.php?gameID=' . $this->Game->id);
     $message = '<p class="notice">' . l_t('You are being redirected to %s. Good luck!', '<a href="board.php?gameID=' . $this->Game->id . '">' . $this->Game->name . '</a>') . '</p>';
     libHTML::notice(l_t("Joined %s", $this->Game->name), $message);
 }
Beispiel #10
0
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with webDiplomacy.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @package Base
 * @subpackage Forms
 */
require_once 'header.php';
if ($Misc->Panic) {
    libHTML::notice(l_t('Game creation disabled'), l_t("Game creation has been temporarily disabled while we take care of an " . "unexpected problem. Please try again later, sorry for the inconvenience."));
}
if (!$User->type['User']) {
    libHTML::notice(l_t('Not logged on'), l_t("Only a logged on user can create games, guests can't. " . "Please <a href='logon.php' class='light'>log on</a> to create your own games."));
}
libHTML::starthtml();
//print '<div class="content">';
if (isset($_REQUEST['newGame']) and is_array($_REQUEST['newGame'])) {
    try {
        $form = $_REQUEST['newGame'];
        // This makes $form look harmless when it is unsanitized; the parameters must all be sanitized
        $input = array();
        $required = array('variantID', 'name', 'password', 'passwordcheck', 'bet', 'potType', 'phaseMinutes', 'joinPeriod', 'anon', 'pressType', 'missingPlayerPolicy', 'drawType', 'minimumReliabilityRating');
        if (!isset($form['missingPlayerPolicy'])) {
            $form['missingPlayerPolicy'] = 'Normal';
        }
        foreach ($required as $requiredName) {
            if (isset($form[$requiredName])) {
                $input[$requiredName] = $form[$requiredName];
Beispiel #11
0
     } else {
         if ($Game->needsProcess()) {
             $DB->sql_put("UPDATE wD_Games SET attempts=attempts+1 WHERE id=" . $Game->id);
             $DB->sql_put("COMMIT");
             require_once l_r('gamemaster/game.php');
             $Game = $Game->Variant->processGame($Game->id);
             if ($Game->needsProcess()) {
                 try {
                     $Game->process();
                     $DB->sql_put("UPDATE wD_Games SET attempts=0 WHERE id=" . $Game->id);
                     $DB->sql_put("COMMIT");
                 } catch (Exception $e) {
                     if ($e->getMessage() == "Abandoned" || $e->getMessage() == "Cancelled") {
                         assert('$Game->phase=="Pre-game" || $e->getMessage() == "Cancelled"');
                         $DB->sql_put("COMMIT");
                         libHTML::notice(l_t('Cancelled'), l_t("Game was cancelled or didn't have enough players to start."));
                     } else {
                         $DB->sql_put("ROLLBACK");
                     }
                     throw $e;
                 }
             }
         }
     }
 }
 if ($Game instanceof processGame) {
     $Game = $Game->Variant->panelGameBoard($Game->id);
     $Game->Members->makeUserMember($User->id);
     $Member = $Game->Members->ByUserID[$User->id];
 }
 if ('Pre-game' != $Game->phase && $Game->phase != 'Finished') {
Beispiel #12
0
	$Misc->Maintenance = 1;
	$Misc->write();
	libHTML::error('Cannot update unless in maintenance mode; maintenance mode set, wait a minute for clients to
		finish and run again.');
}

ini_set('memory_limit',"20M"); // 8M is the default
ini_set('max_execution_time','120');

$DB->get_lock('install',0); // Make sure only one person performs the update

$Misc->read(); // Check we haven't updated while waiting for the lock

if( $Misc->Version == VERSION )
	libHTML::notice('Complete','Update complete');
*/
if ($Misc->Version == 98 || $Misc->Version == 99) {
    $Misc->Version = 100;
    $Misc->write();
    libHTML::notice('Updated', 'Updated version number, please refresh.');
} elseif ($Misc->Version == 104 || $Misc->Version == 130) {
    $Misc->Version = 131;
    $Misc->write();
    libHTML::notice('Updated', 'Updated version number, please refresh.');
} else {
    unset($DB);
    // Prevent libHTML from trying to do anything fancy if the database is out of sync with the code
    libHTML::error("Database version " . $Misc->Version / 100 . " and code\r\n\t\t\tversion " . VERSION / 100 . " don't match, and no\r\n\t\t\tauto-update script is available for this version.\r\n\t\t\tPlease wait while the admin runs update.sql");
}
print '</div>';
libHTML::footer();
Beispiel #13
0
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with webDiplomacy.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @package Base
 * @subpackage Forms
 */
require_once 'header.php';
require_once l_r('objects/mailer.php');
global $Mailer;
$Mailer = new Mailer();
if ($Misc->Panic) {
    libHTML::notice(l_t('Registration disabled'), l_t("Registration has been temporarily disabled while we take care of an " . "unexpected problem. Please try again later, sorry for the inconvenience."));
}
// The user must be guest to register a new account
if ($User->type['User']) {
    libHTML::error(l_t("You're attempting to create a " . "new user account when you already have one. Please use " . "your existing user account."));
}
libHTML::starthtml();
$page = 'firstValidationForm';
if (isset($_COOKIE['imageToken']) && isset($_REQUEST['imageText']) && isset($_REQUEST['emailValidate'])) {
    try {
        // Validate and send e-mail
        $imageToken = explode('|', $_COOKIE['imageToken'], 2);
        if (count($imageToken) != 2) {
            throw new Exception(l_t("A bad anti-script code was given, please try again"));
        }
        list($Hash, $Time) = $imageToken;
Beispiel #14
0
 /**
  * Return a Variant object given its short name (the preferred/quickest way)
  * @param string $variantName
  * @return Variant
  */
 public static function loadFromVariantName($variantName)
 {
     global $DB, $Misc;
     if (!isset(self::$Variants[$variantName])) {
         $variantCache = self::cacheDir($variantName) . '/data.php';
         if (!file_exists($variantCache)) {
             self::installLock();
             if (file_exists($variantCache)) {
                 libHTML::notice(l_t("Installed variant"), l_t("Variant '%s' installed, please refresh.", $variantName));
             }
             $classname = $variantName . 'Variant';
             $Variant = new $classname();
             // variants/variant.php __autoload() will find the class for this
             // The object will have loaded all the cacheable data and be ready to be saved for next time
             file_put_contents($variantCache, serialize($Variant));
         } else {
             // This variant is saved, and doesn't need to waste database queries retreiving this data again
             $variantData = file_get_contents($variantCache);
             $Variant = unserialize($variantData);
             if (isset($Variant->codeVersion) && $Variant->codeVersion != null && $Variant->codeVersion != 0) {
                 // Cache version checking is enabled
                 if (!isset($Variant->cacheVersion) || $Variant->cacheVersion == null || $Variant->cacheVersion < $Variant->codeVersion || !$Variant->cacheVersion) {
                     // An old cache version has been loaded; wipe this variant's cache and try again.
                     self::wipe($variantName);
                     $Variant = self::loadFromVariantName($variantName);
                 }
             }
         }
         self::$Variants[$variantName] = $Variant;
     }
     return self::$Variants[$variantName];
 }