From 31aceb7226f34858725916c171eb3b7c85d4ff74 Mon Sep 17 00:00:00 2001 From: Matt Pass Date: Sat, 11 Jan 2014 15:48:23 +0000 Subject: [PATCH] Refactored and improved settings.php file Moved huge chunks of isolated code to their own files Reordered and improved remaining code Lots of die messages added to stop code continuing after a header location !loginRequired now also setting loggedIn = true as demoMode does Boot user to new login page instead of back to this page loginRequired added to final elseif condition Added 2 big notes re probably showing he login screen and continuing with what we're doing --- lib/settings.php | 352 +++++++---------------------------------------- 1 file changed, 48 insertions(+), 304 deletions(-) diff --git a/lib/settings.php b/lib/settings.php index 317ccef..3ecfe29 100644 --- a/lib/settings.php +++ b/lib/settings.php @@ -1,189 +1,58 @@ - array( - 'timeout' => 60 // secs - ) -)); - -// Set our security related headers, none activated -// header("frame-options: SAMEORIGIN"); -// header("XSS-Protection: 1; mode=block"); - -// Start a session if we haven't already -if(!isset($_SESSION)) {@session_start();} - -// Logout if that's the action we're taking -if (isset($_GET['logout'])) { - include(dirname(__FILE__)."/../processes/on-user-logout.php"); - $_SESSION['loggedIn']=false; - $_SESSION['username']=false; - session_destroy(); - header("Location: dirname(__FILE__)./?loggedOut"); -} - -// If magic quotes are still on (attempted to switch off in php.ini) -if (get_magic_quotes_gpc ()) { - function stripslashes_deep($value) { - $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); - return $value; - } - $_POST = (isset($_POST) && !empty($_POST)) ? array_map('stripslashes_deep', $_POST) : array(); - $_GET = (isset($_GET) && !empty($_GET)) ? array_map('stripslashes_deep', $_GET) : array(); - $_COOKIE = (isset($_COOKIE) && !empty($_COOKIE)) ? array_map('stripslashes_deep', $_COOKIE) : array(); - $_REQUEST = (isset($_REQUEST) && !empty($_REQUEST)) ? array_map('stripslashes_deep', $_REQUEST) : array(); -} - -// Function to handle salted hashing -define('SALT_LENGTH',12); -function generateHash($plainText,$salt=null) { - if ($salt === null) { - $salt = substr(md5(uniqid(rand(), true)),0,SALT_LENGTH); - } else { - $salt = substr($salt,0,SALT_LENGTH); - } - return $salt.sha1($salt.$plainText); -} - -// returns converted entities which have HTML entity equivalents -function strClean($var) { - return htmlentities($var, ENT_QUOTES, "UTF-8"); -} - -// returns a number, whole or decimal or null -function numClean($var) { - return is_numeric($var) ? floatval($var) : false; -} - -// returns a UTF8 based string with any UFT8 BOM removed -function toUTF8noBOM($string,$message) { - // Attempt to detect encoding - if (function_exists('mb_detect_encoding')) { - $encType = mb_detect_encoding($string); - // Get rid of any UTF-8 BOM - $string = preg_replace('/\x{EF}\x{BB}\x{BF}/','',$string); - // Test for any bad characters - $teststring = $string; - $teststringBroken = utf8_decode($teststring); - $teststringConverted = iconv("UTF-8", "UTF-8//IGNORE", $teststringBroken); - // If we have a matching length, UTF8 encode it - if ($encType != "ASCII" && $encType != "UTF-8" && strlen($teststringConverted) == strlen($teststringBroken)) { - $string = utf8_encode($string); - if ($message) { - echo "top.ICEcoder.message('Your document doesn\'t appear to be in UTF-8 encoding so has been converted.');"; - } - } - } - return $string; -} - -// Load system settings +// Establish settings and users template filenames $configSettings = 'config___settings.php'; +$configUsersTemplate = 'config___users-template.php'; + +// Load config settings include(dirname(__FILE__)."/".$configSettings); -// Settings are stored in this file -$configUsersTemplate = 'config___users-template.php'; +// Load common functions +include(dirname(__FILE__)."/settings-common.php"); + +// Establish user settings file $username = ""; if (isset($_POST['username']) && $_POST['username'] != "") {$username = strClean($_POST['username']."-");}; if (isset($_SESSION['username']) && $_SESSION['username'] != "") {$username = strClean($_SESSION['username']."-");}; $settingsFile = 'config-'.$username.str_replace(".","_",str_replace("www.","",$_SERVER['SERVER_NAME'])).'.php'; + +// Login is default $setPWorLogin = "login"; + +// Create user settings file if it doesn't exist if (!file_exists(dirname(__FILE__)."/".$settingsFile)) { if (!copy(dirname(__FILE__)."/".$configUsersTemplate, dirname(__FILE__)."/".$settingsFile)) { die("Couldn't create $settingsFile. Maybe you need write permissions on the lib folder?"); } $setPWorLogin = "set password"; } + +// Load user settings include(dirname(__FILE__)."/".$settingsFile); // On mismatch of settings file to system, rename to .old and reload If ($ICEcoderUserSettings["versionNo"] != $ICEcoderSettings["versionNo"]) { rename(dirname(__FILE__)."/".$settingsFile,dirname(__FILE__)."/".str_replace(".php",".old",$settingsFile)); header("Location: settings.php"); + die('Found old settings file, reloading...'); } // Join ICEcoder settings and user settings together to make our final ICEcoder array $ICEcoder = $ICEcoderSettings + $ICEcoderUserSettings; -$onLoadExtras = ""; -$pluginsDisplay = ""; - -if ($ICEcoder['demoMode'] && $ICEcoder['password']!="") {$_SESSION['loggedIn']=true;}; +// Login not required or we're in demo mode and have password set in our settings, log us straight in +if ((!$ICEcoder['loginRequired'] || $ICEcoder['demoMode']) && $ICEcoder['password']!="") {$_SESSION['loggedIn']=true;}; $demoMode = $ICEcoder['demoMode']; // Update this config file? -if (!$demoMode && isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] && isset($_POST["theme"]) && $_POST["theme"]) { - $settingsContents = file_get_contents($settingsFile,false,$context); - // Replace our settings vars - $repPosStart = strpos($settingsContents,'"root"'); - $repPosEnd = strpos($settingsContents,'"previousFiles"'); +include(dirname(__FILE__)."/settings-update.php"); - // Prepare all our vars - $ICEcoder["root"] = strClean($_POST['root']); - $ICEcoder["checkUpdates"] = isset($_POST['checkUpdates']) && $_POST['checkUpdates'] ? "true" : "false"; - $ICEcoder["openLastFiles"] = isset($_POST['openLastFiles']) && $_POST['openLastFiles'] ? "true" : "false"; - $ICEcoder["findFilesExclude"] = 'array("'.str_replace(',','","',str_replace(" ","",strClean($_POST['findFilesExclude']))).'")'; - $ICEcoder["codeAssist"] = isset($_POST['codeAssist']) && $_POST['codeAssist'] ? "true" : "false"; - $ICEcoder["visibleTabs"] = isset($_POST['visibleTabs']) && $_POST['visibleTabs'] ? "true" : "false"; - $ICEcoder["lockedNav"] = isset($_POST['lockedNav']) && $_POST['lockedNav'] ? "true" : "false"; - $ICEcoder["tagWrapperCommand"] = strClean($_POST['tagWrapperCommand']); - $ICEcoder["autoComplete"] = strClean($_POST['autoComplete']); - if ($_POST['password']!="") {$ICEcoder["password"] = generateHash(strClean($_POST['password']));}; - $ICEcoder["bannedFiles"] = 'array("'.str_replace(',','","',str_replace(" ","",strClean($_POST['bannedFiles']))).'")'; - $ICEcoder["bannedPaths"] = 'array("'.str_replace(',','","',str_replace(" ","",strClean($_POST['bannedPaths']))).'")'; - $ICEcoder["allowedIPs"] = 'array("'.str_replace(',','","',str_replace(" ","",strClean($_POST['allowedIPs']))).'")'; - $ICEcoder["plugins"] = 'array('.PHP_EOL.' array('.PHP_EOL.' '.str_replace('====================','),'.PHP_EOL.' array(',str_replace("\\","\\\\",$_POST['plugins'])).'))'; - $ICEcoder["theme"] = strClean($_POST['theme']); - $ICEcoder["fontSize"] = strClean($_POST['fontSize']); - $ICEcoder["lineWrapping"] = strClean($_POST['lineWrapping']); - $ICEcoder["indentWithTabs"] = strClean($_POST['indentWithTabs']); - $ICEcoder["indentSize"] = numClean($_POST['indentSize']); - - $settingsArray = array("root","checkUpdates","openLastFiles","findFilesExclude","codeAssist","visibleTabs","lockedNav","tagWrapperCommand","autoComplete","password","bannedFiles","bannedPaths","allowedIPs","plugins","theme","fontSize","lineWrapping","indentWithTabs","indentSize"); - $settingsNew = ""; - for ($i=0;$i '; - $settingWrap = $settingsArray[$i]=="root"||$settingsArray[$i]=="password"||$settingsArray[$i]=="theme"||$settingsArray[$i]=="fontSize"||$settingsArray[$i]=="tagWrapperCommand"||$settingsArray[$i]=="autoComplete" ? '"' : ''; - $settingsNew .= $settingWrap.$ICEcoder[$settingsArray[$i]].$settingWrap.','.PHP_EOL.PHP_EOL; - } - - // Compile our new settings - $settingsContents = substr($settingsContents,0,$repPosStart).$settingsNew.substr($settingsContents,($repPosEnd),strlen($settingsContents)); - // Now update the config file - if (is_writeable($settingsFile)) { - $fh = fopen($settingsFile, 'w'); - fwrite($fh, $settingsContents); - fclose($fh); - } else { - echo ""; - } - - // OK, now the config file has been updated, update our current session with new arrays - $settingsArray = array("findFilesExclude","bannedFiles","allowedIPs"); - for ($i=0;$itop.ICEcoder.settingsScreen('hide');top.ICEcoder.useNewSettings('".$themeURL."',".$ICEcoder["codeAssist"].",".$ICEcoder["lockedNav"].",'".$ICEcoder["tagWrapperCommand"]."','".$ICEcoder["autoComplete"]."',".$ICEcoder["visibleTabs"].",'".$ICEcoder["fontSize"]."',".$ICEcoder["lineWrapping"].",".$ICEcoder["indentWithTabs"].",".$ICEcoder["indentSize"].",".$refreshFM.");"; -} - -// Establish our user level +// Set loggedIn and username to false if not set as yet if (!isset($_SESSION['loggedIn'])) {$_SESSION['loggedIn'] = false;}; if (!isset($_SESSION['username'])) {$_SESSION['username'] = false;}; + +// Attempt a login with password if(isset($_POST['submit']) && $setPWorLogin=="login") { + // On success, set username if multiUser, loggedIn to true and redirect if (generateHash(strClean($_POST['password']),$ICEcoder["password"])==$ICEcoder["password"]) { if ($ICEcoder["multiUser"]) { $_SESSION['username'] = $_POST['username']; @@ -191,10 +60,13 @@ if(isset($_POST['submit']) && $setPWorLogin=="login") { $_SESSION['loggedIn'] = true; include(dirname(__FILE__)."/../processes/on-user-login.php"); header('Location: ../'); + die('Logging you in...'); } else { include(dirname(__FILE__)."/../processes/on-user-login-fail.php"); } }; + +// Re-establish our loggedIn state and username $_SESSION['loggedIn'] = $_SESSION['loggedIn']; $_SESSION['username'] = $_SESSION['username']; @@ -219,126 +91,30 @@ for($i=0;$itop.window.location="/";'; + die('Sorry, access not permitted'); }; -// Save the currently opened files for next time -if ($_SESSION['loggedIn'] && isset($_GET["saveFiles"]) && $_GET['saveFiles']) { - $settingsContents = file_get_contents($settingsFile,false,$context); +// Save currently opened files in previousFiles and last10Files arrays +include(dirname(__FILE__)."/settings-save-current-files.php"); - // Replace our previousFiles var with the the current - $repPosStart = strpos($settingsContents,'previousFiles" => "')+20; - $repPosEnd = strpos($settingsContents,'",',$repPosStart)-$repPosStart; - if (!$demoMode) { - if ($_GET['saveFiles']!="CLEAR") { - $saveFiles=strClean($_GET['saveFiles']); - $saveFilesArray = explode(",",$saveFiles); - $saveFiles=""; - for ($i=0;$itop.ICEcoder.message('Cannot update config file. Please set public write permissions on lib/".$settingsFile." and try again');"; - } +// Display the plugins +include(dirname(__FILE__)."/plugins-display.php"); - // Update our last10Files var? - $last10FilesArray = explode(",",$ICEcoder["last10Files"]); - for ($i=0;$i "')+18; - $repPosEnd = strpos($settingsContents,'"',$repPosStart)-$repPosStart; - $commaExtra = $ICEcoder["last10Files"]!="" ? "," : ""; - if (count($last10FilesArray)>=10) {$ICEcoder["last10Files"]=substr($ICEcoder["last10Files"],0,strrpos($ICEcoder["last10Files"],','));}; - $settingsContents = substr($settingsContents,0,$repPosStart).$saveFilesArray[$i].$commaExtra.$ICEcoder["last10Files"].substr($settingsContents,($repPosStart+$repPosEnd),strlen($settingsContents)); - // Now update the config file - if (is_writeable($settingsFile)) { - $fh = fopen($settingsFile, 'w'); - fwrite($fh, $settingsContents); - fclose($fh); - } else { - echo ""; - } - } - } - } - echo ''; -} - -// If we're updating, do/redo plugins -if ($_SESSION['loggedIn']) { - // If we're updating, we need to recreate the plugins array - if (isset($_POST["theme"]) && $_POST["theme"]) { - $ICEcoder["plugins"] = array(); - $pluginsArray = explode("====================",str_replace("\"","",str_replace("\r","",str_replace("\n","",$_POST['plugins'])))); - for ($i=0;$i'.$ICEcoder[

'; - }; - - // If we're updating, replace the plugin display with our newly established one - echo ""; - - // Work out what plugins we'll need to set on a setInterval - $onLoadExtras = ""; - for ($i=0;$i - - -1)) { $password = generateHash(strClean($_POST['password'])); - $settingsFile = $settingsFile; $settingsContents = file_get_contents($settingsFile,false,$context); // Replace our empty password with the one submitted by user $settingsContents = str_replace('"password" => "",','"password" => "'.$password.'",',$settingsContents); @@ -359,49 +135,17 @@ if ((!$_SESSION['loggedIn'] || $ICEcoder["password"] == "") && !strpos($_SERVER[ include(dirname(__FILE__)."/../processes/on-user-new.php"); // Finally, load again as now this file has changed and auto login header('Location: ../'); + die('Logging you in...'); } -?> - - - - -ICEcoder <?php -echo $ICEcoder["versionNo"]." : "; -echo $ICEcoder["password"] == "" && !$ICEcoder["multiUser"] ? "Setup" : "Login"; -?> - - - - - - -.focus()"> - -
-
-
- -
v
-
-

';};?> -

- " class="button"> - auto-check for updates
'; - } - if (!$ICEcoder["multiUser"]) { echo '';}; - ?> - -
-
- - - - - - \ No newline at end of file