Exemplo n.º 1
0
 function LoadConfig()
 {
     global $config;
     $configTxt = file_get_contents("config/config.txt");
     $lines = explode("\n", $configTxt);
     $linesUpdated = array();
     foreach ($lines as $i => $line) {
         $line = trim($line);
         if (StartsWith($line, "#")) {
             //Comment
             continue;
         }
         $linePair = explode("|", $line);
         if (count($linePair) == 2) {
             //key-value pair
             $key = trim($linePair[0]);
             $value = trim($linePair[1]);
             $config[$key] = $value;
             //Validate line
             switch ($key) {
                 case "PEPPER":
                     if (strlen($value) < 1) {
                         //Generate pepper if none exists (first time site launch).
                         $config[$key] = GenerateSalt();
                         $lines[$i] = "{$key} | " . $config[$key];
                         file_put_contents("config/config.txt", implode("\n", $lines));
                     }
                     break;
                 case "SESSION_PASSWORD_ITERATIONS":
                     if (strlen($value) < 1) {
                         //Generate pepper if none exists (first time site launch).
                         $config[$key] = rand(10000, 20000);
                         $lines[$i] = "{$key} | " . $config[$key];
                         file_put_contents("config/config.txt", implode("\n", $lines));
                     } else {
                         $config[$key] = intval($value);
                     }
                     break;
                 default:
                     $linesUpdated[] = $line;
                     break;
             }
         }
     }
 }
Exemplo n.º 2
0
/**
* Create an attribute of a product 
*
* @return int, parameter erp5_variation like size/L, size/XL, color/blue, 
*/
function deleteProductAttribute($product_id, $product_base_categ, $product_variation)
{
    if (!($result = mysql_query("SELECT attribute FROM " . constant('_VM_TABLE_PREFIX_') . "_product \n                            WHERE product_id='{$product_id}'"))) {
        return false;
    }
    $row = mysql_fetch_array($result);
    $vm_category_list = "";
    //Get the attributes
    $attribute_list = explode(';', $row['attribute']);
    // test if the attribute already exists
    $pos = strpos(strtolower($row['attribute']), "," . strtolower($product_variation));
    if ($pos > 0) {
        //attribute already exists
        foreach ($attribute_list as $attribute) {
            $attribute_value_list = explode(',', $attribute);
            $attribute_name = $attribute_value_list[0];
            $updated_attibute = "";
            if (strtolower($attribute_name) === strtolower($product_base_categ)) {
                $updated_attibute = $attribute_name;
                for ($i = 1; $i < count($attribute_value_list); $i++) {
                    $vm_variation = $attribute_value_list[$i];
                    if (!StartsWith($vm_variation, $product_variation)) {
                        $updated_attibute .= "," . $vm_variation;
                        //echo $updated_attibute."<br>";
                    }
                }
                $vm_category_list .= $updated_attibute . ";";
            } else {
                $vm_category_list .= $attribute . ";";
            }
        }
    }
    if ($vm_category_list != "") {
        $vm_category_list = substr($vm_category_list, 0, strlen($vm_category_list) - 1);
        $attributeUpdateQuery = sprintf("UPDATE " . constant('_VM_TABLE_PREFIX_') . "_product \n                                      SET attribute=%s\n                                      WHERE product_id=%s", GetSQLValueString($vm_category_list, "text"), GetSQLValueString($product_id, "int"));
        //echo $attributeUpdateQuery;
        $msg = executeSQL($attributeUpdateQuery);
        return $msg;
    } else {
        return "<xml><error>Query not executed</error></xml>";
    }
}
Exemplo n.º 3
0
function ParseLine($nLineType) {
	global $TempString,$LineCount;
	global $bWaiting;
	global $TempPoint, $TempArea,$NumberOfAirspaceAreas;
	global $Rotation ,$CenterX, $CenterY;
	// DEBUG("checkAirspace",128,"ParseLine: [$nLineType] $TempString");

	$k_strAreaStart = array("R",  "Q", "P", "A", "B", "C", "CTR","D", "GP", "W", "E", "F");
	$k_nAreaType = array( "RESTRICT", "DANGER", "PROHIBITED", "CLASSA", "CLASSB", "CLASSC", 
					"CTR","CLASSD", "NOGLIDER", "WAVE", "CLASSE", "CLASSF");


	switch ($nLineType)
	{
	case k_nLtAC:
		if (!$bWaiting)	AddArea();
		//unset($GLOBALS['TempArea']);
		//unset($TempArea);
		$TempArea->NumPoints = 0;
		$TempArea->Points = array();
		$TempArea->Type = OTHER;
		//echo "Set type: $TempString <BR>";
		for ($nIndex = 0; $nIndex < count($k_strAreaStart); $nIndex++) {
			if (StartsWith(substr($TempString,3), $k_strAreaStart[$nIndex]))	{
				$TempArea->Type = $k_nAreaType[$nIndex];
				break;
			}
		}
		// echo "type= ".$TempArea->Type."<BR>";
	  	$Rotation = +1;
		$bWaiting = false;
		break;

	case k_nLtAN:		
		$TempArea->Name=substr($TempString,3);
		// echo "[Name] type= ".$TempArea->Type."<BR>";
		break;

	case k_nLtAL:
		//$m1=memory_get_usage();
		ReadAltitude( substr($TempString,3) ,'Base');
		//$m2=memory_get_usage();
		//echo "ReadAltitude: mem usage: ".($m2-$m1)." AFTER: ".$m2."<BR>"; 
		//echo "[Alt base] type= ".$TempArea->Type."<BR>";
		break;

	case k_nLtAH:
		/// $TempArea->Top=ReadAltitude( substr($TempString,3) ,'Top' );
		ReadAltitude( substr($TempString,3) ,'Top' );
		break;

	case k_nLtV:
		// Need to set these while in count mode, or DB/DA will crash
		// DEBUG("checkAirspace",128,"found V");
		if( StartsWith(substr($TempString,2), "X=" ) || StartsWith(substr($TempString,2), "x=") ) {
			// DEBUG("checkAirspace",128,"will read coords");
			list ($res, $CenterX , $CenterY ) = ReadCoords( substr($TempString,4) );
			if ($res) break;
		} else if( StartsWith(substr($TempString,2),"D=-") || StartsWith(substr($TempString,2),"d=-") )	{
			$Rotation = -1;
	      break;
		} else if ( StartsWith(substr($TempString,2),"D=+") || StartsWith(substr($TempString,2),"d=+") ) {
			$Rotation = +1;
		    break;
		} else if(StartsWith(substr($TempString,2),"Z") || StartsWith(substr($TempString,2),"z") ) {
	      // ToDo Display Zool Level
	      break;
		} else if(StartsWith(substr($TempString,2),"W") || StartsWith(substr($TempString,2),"w")) {
     	  // ToDo width of an airway
		  break;
		} else if(StartsWith(substr($TempString,2),"T") || StartsWith(substr($TempString,2),"t") ) {
	      // ----- JMW THIS IS REQUIRED FOR LEGACY FILES
	      break;
		}

		DEBUG("checkAirspace",128, sprintf("Parse Error1 at Line: %d\r\n\"%s\"\r\nLine skiped.", $LineCount, $TempString) );
		return 0;

	case k_nLtDP:
		// DEBUG("checkAirspace",128,"will read coods");
		list ($res, $TempPoint->Longitude , $TempPoint->Latitude ) = ReadCoords( substr($TempString,3) );
    	if (!$res)  {
			DEBUG("checkAirspace",128, sprintf("Parse Error2 at Line: %d\r\n\"%s\"\r\nLine skiped.", $LineCount, $TempString) );
			return 0;
		}
  		AddPoint($TempPoint);
		break;

	case k_nLtDB:
		//$m1=memory_get_usage();
		CalculateArc($TempString);
		//$m2=memory_get_usage();
		//echo "CalculateArc: mem usage: ".($m2-$m1)." AFTER: ".$m2."<BR>"; 
		break;

	case k_nLtDA:
		CalculateSector($TempString);
		break;

	case k_nLtDC:
		$Radius = substr($TempString,2)+0;
		$Radius = $Radius * NAUTICALMILESTOMETRES;
		AddAirspaceCircle($CenterX, $CenterY, $Radius);
		$bWaiting = true;
		break;

	default:
		break;
	}

  return 1;
}
 function parseResults($s)
 {
     $arraylist = array();
     if (StartsWith($s, "!ERROR!")) {
         $this->error = $s;
         return null;
     }
     $tokens = strtok($s, ":\r\n");
     $s1;
     $flag = false;
     foreach ($tokens as $token) {
         $s2 = $token;
         if (!s2 . startsWith(":")) {
             $arraylist[] = $s2;
             $flag = false;
         } else {
             if (flag) {
                 $arraylist[] = "";
             }
             $flag = true;
         }
     }
     return $arraylist;
     $this->error = "Internal Error!";
     return null;
 }
Exemplo n.º 5
0
function SaveConfig($key, $newValue)
{
    global $config, $configSettings;
    if (!IsAdmin()) {
        return;
        //Lacks permissions to make edits
    }
    if ($configSettings[$key]["EDITABLE"] == FALSE) {
        //Some configuration settings cannot be set via this interface for security reasons.
        return;
    }
    $newValue = str_replace("\n", "", $newValue);
    $newValue = str_replace("\r", "", $newValue);
    $newValue = trim($newValue);
    $configTxt = file_get_contents("config/config.txt");
    $lines = explode("\n", $configTxt);
    $linesUpdated = array();
    foreach ($lines as $i => $line) {
        $line = trim($line);
        if (StartsWith($line, "#")) {
            //Comment
            continue;
        }
        $linePair = explode("|", $line);
        if (count($linePair) >= 2) {
            //key-value pair
            $currentKey = trim($linePair[0]);
            $value = trim($linePair[1]);
            if ($key == $currentKey) {
                if ($value != $newValue) {
                    $lines[$i] = $key . " | " . $newValue;
                    file_put_contents("config/config.txt", implode("\n", $lines));
                }
                return;
            }
        }
    }
}
Exemplo n.º 6
0
 /**
  * Destiny API Class constructor
  *
  * @version 1
  * @author Rick de Man <*****@*****.**>
  *        
  */
 public function __Construct()
 {
     // Check all Server keys for the API
     foreach (array("DESTINY_API_KEY", "DESTINY_DNS_HOST", "DESTINY_DNS_CHAR", "DESTINY_DNS_USER", "DESTINY_DNS_PASS", "DESTINY_DNS_DB") as $V) {
         if (!isset($_SERVER[$V])) {
             $this->_Result(array('message' => "ApiError: " . $V . " not defined"), false);
         }
     }
     // Check if Debug is requested
     $this->Debug = isset($_GET['Debug']) && $_GET['Debug'] == true;
     $this->LocalDebug = isset($_GET['localdebug']) && strtolower($_GET['localdebug']) == 'true';
     // Define Destiny API Key
     $this->ApiKey = $_SERVER["DESTINY_API_KEY"];
     // Define MySQL Connection
     $DnsHost = $_SERVER["DESTINY_DNS_HOST"];
     $DnsChar = $_SERVER["DESTINY_DNS_CHAR"];
     $DnsUser = $_SERVER["DESTINY_DNS_USER"];
     $DnsPass = $_SERVER["DESTINY_DNS_PASS"];
     $DnsDaBa = $_SERVER["DESTINY_DNS_DB"];
     // Create Server Connection
     try {
         $this->DBH = new PDO("mysql:host={$DnsHost};charset={$DnsChar}", $DnsUser, $DnsPass);
         $this->DBH->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
         $this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $this->DBH->Query('USE ' . $DnsDaBa);
     } catch (PDOException $e) {
         // Oops, Something went wrong...
         $this->_Result(array('message' => $e->getMessage(), 'line' => __LINE__), false);
     }
     // Create a cookie for each users ( Session defined )
     $this->ApiCookieFile = __DIR__ . "/cookies/" . md5($_SERVER["REMOTE_ADDR"] . "-" . session_id()) . '.txt';
     // Create Cookie folder if not exists
     if (!file_exists(substr($this->ApiCookieFile, 0, -strlen(basename($this->ApiCookieFile))))) {
         mkdir(substr($this->ApiCookieFile, 0, -strlen(basename($this->ApiCookieFile))));
     }
     // Chck is file exists
     if (!file_exists($this->ApiCookieFile)) {
         // Create Cookie file with no content
         file_put_contents($this->ApiCookieFile, '');
     }
     // Remove old files ( 1 day )
     foreach (glob(substr($this->ApiCookieFile, 0, -strlen(basename($this->ApiCookieFile))) . "*") as $File) {
         // Check for file
         if (is_file($File)) {
             // File must be older than x
             if (time() - filemtime($File) >= 86400) {
                 // And its gone...
                 unlink($File);
             }
         }
     }
     try {
         // Load Manifest Version
         $STH = $this->DBH->Query('SELECT * FROM `settings` WHERE name = "DestinyManifestVersion"');
     } catch (PDOException $e) {
         // Oops, Something went wrong...
         $this->_Result(array('message' => $e->getMessage(), 'line' => __LINE__), false);
     }
     // If a record has been found
     if ($STH !== false && $STH->RowCount() > 0) {
         $this->DestinyManifestVersion = $STH->fetch()['Value'];
     } else {
         // Execute the Current Query with Parameters
         $STH = $this->DBH->Query('INSERT INTO `settings` VALUES ( "DestinyManifestVersion", "-1" )');
     }
     // Json file which contains the endpoints
     $File = __DIR__ . "/data.json";
     if (!file_exists($File)) {
         $this->_Result(array('message' => "ApiError: Data file not found"), false);
     }
     // Parse JSON data
     $Data = json_decode(file_get_contents($File));
     // Check for Json Errors
     if (json_last_error() != 0) {
         $this->_Result(array('message' => "ApiError: Invalid Data file"), false);
     }
     // Load Endpoints
     $this->Endpoints = $Data->Endpoints;
     // Load API Host
     $this->ApiHost = $Data->Host;
     // Load API version
     $this->GitDataVersion = $Data->Version;
     // Load API version
     $this->ApiVars = json_decode(json_encode($Data->Variables), true);
     // Load 'Last updated' time from the Database
     try {
         // Load Manifest Version
         $STH = $this->DBH->Query('SELECT * FROM `settings` WHERE name = "DestinyApiUpdateTime"');
     } catch (PDOException $e) {
         // Oops, Something went wrong...
         $this->_Result(array('message' => $e->getMessage(), 'line' => __LINE__), false);
     }
     // Load all Available tables
     try {
         $STH = $this->DBH->Query('SELECT * FROM `information_schema`.`tables` WHERE TABLE_SCHEMA="ricdem1_platform"');
     } catch (PDOException $e) {
         // Oops, Something went wrong...
         $this->_Result(array('message' => $e->getMessage(), 'line' => __LINE__), false);
     }
     // loop through each table
     foreach ($STH as $V) {
         // Save table name
         $this->Tables[] = $V['TABLE_NAME'];
     }
     $H = getallheaders();
     if (isset($H['X-Apitest'])) {
         $this->CurlApiTest($H);
     }
     if (isset($H['X-Api-Key']) && $H['X-Api-Key'] === $this->ApiKey) {
         // Filename for Current line
         $FilenameLine = 'DestinyManifest.txt';
         // Check for Header call: Get Destiny Manifest Version
         if (isset($H['X-Api-Func'])) {
             // Show Manifest Version
             if ($H['X-Api-Func'] === 'GetDestinyManiFestVersion') {
                 die($this->DestinyManifestVersion);
             }
             // Accept the Upload File
             if ($H['X-Api-Func'] === 'UploadZipFile') {
                 if ($_FILES[0]["name"] == "DestinyManifest.zip") {
                     if (move_uploaded_file($_FILES[0]["tmp_name"], $_FILES[0]["name"])) {
                         $zip = new ZipArchive();
                         $zip->open($_FILES[0]["name"]);
                         $zip->extractTo(__DIR__);
                         $zip->close();
                         unlink($_FILES[0]["name"]);
                         file_put_contents($FilenameLine, '-1');
                         die('OK');
                     } else {
                         die('MoveFailed');
                     }
                 }
             }
             if ($H['X-Api-Func'] == 'ProcessZipFile') {
                 // Filename for Current line
                 $FilenameLine = 'DestinyManifest.txt';
                 // string to integer
                 $CurrentLine = intval(file_get_contents($FilenameLine));
                 // if -1, truncate tables
                 if ($CurrentLine == -1) {
                     foreach ($this->Tables as $Table) {
                         if (StartsWith("destiny", strtolower($Table), true)) {
                             $this->DBH->Query("TRUNCATE TABLE `" . $_SERVER["DESTINY_DNS_DB"] . '`.`' . $Table . "`");
                         }
                     }
                     file_put_contents($FilenameLine, '0');
                     $CurrentLine = 0;
                 }
                 $MaxExecutionTime = ini_get('max_execution_time');
                 if ($MaxExecutionTime > 30.0) {
                     $MaxExecutionTime = 30.0;
                 }
                 $file = fopen("DestinyManifest.json", "r");
                 $FileLine = 0;
                 while (!feof($file) && $MaxExecutionTime - (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) > 5.0) {
                     $Line = fgets($file);
                     if ($FileLine >= $CurrentLine) {
                         if (preg_match('/^\\[([\\w\\W].+?)\\]/i', $Line, $M)) {
                             $Table = $M[1];
                             $Json = str_replace($M[0], '', $Line);
                             $Json = json_decode($Json, true);
                             // Create table if not exists
                             if (!in_array(strtolower($Table), array_map('strtolower', $this->Tables))) {
                                 // Query Setup
                                 $Query = '';
                                 $Query .= 'CREATE TABLE `' . $Table . '` (' . EOL;
                                 foreach (array_keys($Json) as $Index => $Key) {
                                     if ($Index == 0) {
                                         $Query .= '	`' . $Key . '` VARCHAR(255),' . EOL;
                                     } else {
                                         $Query .= '	`' . $Key . '` ' . ($Table !== 'DestinyGrimoireDefinition' ? 'TEXT,' : 'MEDIUMTEXT,') . EOL;
                                     }
                                 }
                                 $Query .= '	primary KEY (`' . array_keys($Json)[0] . '`)' . EOL;
                                 $Query .= ');';
                                 // Execute the Current Query with Parameters
                                 $STH = $this->DBH->Query($Query);
                                 if ($STH != true) {
                                     die('TableCreate Error');
                                 }
                                 $this->Tables[] = $Table;
                             }
                             // Query Setup
                             if (strtolower($Table) != 'settings') {
                                 $Query = 'INSERT INTO `' . $Table . '` VALUES( \'' . implode("', '", array_map("addSlashes", $Json)) . '\')';
                             } else {
                                 $Query = 'UPDATE `' . $Table . '` SET `Value`= "' . $Json['Value'] . '" WHERE `Name`= "' . $Json['Name'] . '"  ';
                             }
                             // Execute the Current Query with Parameters
                             $STH = $this->DBH->Query($Query);
                             if ($STH == false) {
                                 echo "Error Insert" . EOL;
                                 echo "Table: {$Table}" . EOL;
                                 echo "data: " . json_encode($Data) . EOL;
                                 die('');
                             }
                         }
                         $CurrentLine++;
                     }
                     $FileLine++;
                 }
                 fclose($file);
                 file_put_contents($FilenameLine, $CurrentLine);
                 if (!($MaxExecutionTime - (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'])) > 5.0) {
                     unlink($FilenameLine);
                     unlink(str_replace('.txt', '.json', $FilenameLine));
                 }
                 echo $CurrentLine;
                 die;
             }
         }
     }
     // last Updated, default
     $last = 0;
     // check for rows
     if ($STH !== false && $STH->RowCount() > 0) {
         // get the latest time
         $last = $STH->fetch()['Value'];
     } else {
         // Insert into the database
         $STH = $this->DBH->Query('INSERT INTO `settings` VALUES ( "DestinyApiUpdateTime", "0" )');
     }
     // Check if time passed 1 hour after last time
     if (time() >= $last + 3600) {
         // Curl - Create
         $Curl = curl_init();
         // Curl - Setup
         curl_setopt($Curl, CURLOPT_CONNECTTIMEOUT, 10);
         curl_setopt($Curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($Curl, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($Curl, CURLOPT_TIMEOUT, 10);
         curl_setopt($Curl, CURLOPT_URL, $Data->GitVersionUrl . "?" . time());
         curl_setopt($Curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
         curl_setopt($Curl, CURLOPT_HEADER, true);
         curl_setopt($Curl, CURLOPT_FRESH_CONNECT, true);
         curl_setopt($Curl, CURLOPT_HTTPHEADER, array("Cache-Control: no-cache"));
         // Curl - Execute
         $CurlData = $this->CurlExecute($Curl, true, false);
         $GitVersion = json_decode($CurlData->body);
         // Check if Local and Git are not equal
         if ($GitVersion->data !== $this->GitDataVersion || $GitVersion->php !== $this->GitPhpVersion) {
             $this->_Result(array('message' => "Destiny API is outdated", 'Local' => $this->GitDataVersion, 'Git' => $CurlData->body), false);
         }
         // update database 'Last updated'
         try {
             // Update last update check'
             $this->DBH->Query("UPDATE `settings` SET `Value` = '" . time() . "' WHERE `settings`.`Name` = 'DestinyApiUpdateTime';");
         } catch (PDOException $e) {
             // Oops, Something went wrong...
             $this->_Result(array('message' => $e->getMessage(), 'line' => __LINE__), false);
         }
     }
     // Load URL
     $URL = substr($_SERVER["REDIRECT_URL"], strlen($_SERVER["CWD"]));
     // URL may not be false, no URL provided
     if ($URL == false) {
         $this->_Result(array('message' => "No Endpoint provided"), false);
     }
     // Endpoint variables
     $Endpoint = NULL;
     $EndpointsNames = array();
     // Loop through Endpoints
     foreach ($this->Endpoints as $Name => $Data) {
         $EndpointsNames[] = $Name;
         if (strpos(strtoupper($URL), strtoupper($Name . '/')) === 0) {
             $Endpoint = $Data;
             break;
         }
     }
     // Check if Endpoint is found
     if ($Endpoint === NULL) {
         // Return the Error
         $this->_Result(array('message' => 'Endpoint "' . $URL . '" not found', 'endpoints' => $EndpointsNames), false);
     }
     $this->ExecuteEndpoint($Endpoint, $URL, $Name);
     // Do not further execute this script
     die;
 }
Exemplo n.º 7
0
Arquivo: html.php Projeto: RickdeM/wms
 /**
  * The HTML Current Page/Component loader
  *
  * @version 1
  * @author Rick de Man <*****@*****.**>
  *        
  * @param string $WmsElement
  *        	The complete wms:include element
  * @param array $Attributes
  *        	The element tag attributes
  * @return string The HTML Output
  */
 protected function HTML_Page($WmsElement, $Attributes)
 {
     // Create the Result variable
     $Result = '';
     // Load the Mode Page folder
     $Folder = WMS_LIB . 'pages/' . $this->WMS_Mode . '/' . $this->Template . '/';
     // make sure no '\' is used
     $Folder = str_replace('\\', '/', $Folder);
     // Default page
     $Home = $Folder . 'home.php';
     // HTTP/1.1 401
     $Error401 = $Folder . '401.php';
     // HTTP/1.1 401
     $Error403 = $Folder . '403.php';
     // HTTP/1.1 404
     $Error404 = $Folder . '404.php';
     // Page is already determined
     $Page = $Folder . strtolower($this->Page) . '.php';
     // For debug purpose
     echo "<wms:PageDebug>";
     // Check if URL does not start with 'component'
     if (!StartsWith('component/', strtolower($this->Page))) {
         // FIXME : Check if user has acces to the requested page
         // Check if file exists
         if (file_exists($Page)) {
             $Code = $this->User_HasAcces_Page();
             switch ($Code) {
                 case 401:
                     include $Error401;
                     break;
                 case 403:
                     include $Error403;
                     break;
                 case 404:
                     include $Error404;
                     break;
                 default:
                     // include the page
                     include $Page;
             }
         } else {
             // check if 404 error is allowd
             if ($this->WMS['Error404'] !== false) {
                 // Genereate fake 404
                 include $Error404;
             } else {
                 // check if Homepage exists
                 if (file_exists($Home)) {
                     // include Homepage
                     include $Home;
                 } else {
                     // Genera error
                     echo $this->Bootstrap_HtmlAlert('HTML_Page error: Homepage does not exist', 'danger');
                 }
             }
         }
     } else {
         // Get en exploded URL
         $UrlExploded = explode('/', strtolower($this->Page));
         // Generate the Component Class
         $Class = "Component_" . $UrlExploded[1];
         $ComponentName = $UrlExploded[1];
         $ComponentName[0] = strtoupper($ComponentName[0]);
         // Check if the Class exists
         if (class_exists($Class)) {
             // Remove 'component'
             array_shift($UrlExploded);
             // Remove ComponentName
             array_shift($UrlExploded);
             // Load the class
             if (!isset($this->Components[$ComponentName])) {
                 $this->HTML_JsComponentsLoad($ComponentName);
                 $this->Components[$ComponentName] = new $Class($this->SQL, $this->Template, $this->User);
             }
             $_Class = $this->Components[$ComponentName];
             // Check if the Method Page does exists
             if (method_exists($_Class, 'Page')) {
                 // Get the Page result of the class
                 $ClassResult = $_Class->Page(implode('/', $UrlExploded));
                 // Check if the result is an integer
                 if (is_int($ClassResult)) {
                     // The error page
                     $ErrorPage = $Folder . $ClassResult . '.php';
                     // Check fi the ErrorPage does exist
                     if (file_exists($ErrorPage)) {
                         // Include ErrorPage
                         include $ErrorPage;
                     } else {
                         // Error: ErrorPage does not exist
                         $this->BuildErrors[] = $this->Bootstrap_HtmlAlert('HTML_page error page not found : (' . $ClassResult . ')', 'danger');
                     }
                 } else {
                     echo $ClassResult;
                 }
             } else {
                 // Error: Class Method does not exists (Page)
                 $this->BuildErrors[] = $this->Bootstrap_HtmlAlert('Component error: Method does not exists: ( Page )', 'danger');
             }
         } else {
             // Error: Class does not exists
             $this->BuildErrors[] = $this->Bootstrap_HtmlAlert('HTML_page error: Component doest not exist (' . $Class . ')', 'danger');
         }
     }
     // Get content
     $Content = ob_get_contents();
     // clear the page result
     ob_clean();
     // for each line add starting tabs
     $Result .= $Content;
     // Return processed HTML string
     return array('Result' => $Result, 'Paramaters' => array('ClearPage' => isset($ClearPage)));
 }
Exemplo n.º 8
0
function run_test($file, $www)
{
    // parse the test '$file'
    $section_text = parse_file($file);
    // setup environment
    if (EndsWith($www, '.php')) {
        $www = dirname($www);
    }
    if (!EndsWith($www, '/')) {
        $www .= '/';
    }
    $phpfile = replace_extension($file, 'php');
    $tested = trim($section_text['TEST']);
    $env = array('HTTP_CONTENT_ENCODING' => '');
    $opts = array('http' => array('method' => "GET", 'header' => ''));
    if (!empty($section_text['ENV'])) {
        foreach (explode("\n", trim($section_text['ENV'])) as $e) {
            $e = explode('=', trim($e), 2);
            if (!empty($e[0]) && isset($e[1])) {
                $env[$e[0]] = $e[1];
            }
        }
    }
    // Default ini settings
    $ini_settings = array();
    // put additional INI settings here
    // Any special ini settings, these may overwrite the test defaults...
    if (array_key_exists('INI', $section_text)) {
        if (strpos($section_text['INI'], '{PWD}') !== false) {
            $section_text['INI'] = str_replace('{PWD}', dirname(realpath($file)), $section_text['INI']);
        }
        settings2array(preg_split("/[\n\r]+/", $section_text['INI']), $ini_settings);
    }
    // prepend custom ini settings
    if (count($ini_settings) > 0) {
        $section_text['FILE'] = get_ini_code($ini_settings) . $section_text['FILE'];
    }
    // skip this test ?
    try_skip($file, $www, $section_text);
    // redirect test ?
    try_redirect($file, $www, $section_text);
    // request .php script
    save_text($phpfile, $section_text['FILE']);
    if (array_key_exists('GET', $section_text)) {
        $query_string = trim($section_text['GET']);
    } else {
        $query_string = '';
    }
    $env['QUERY_STRING'] = $query_string;
    if (array_key_exists('COOKIE', $section_text)) {
        $env['HTTP_COOKIE'] = trim($section_text['COOKIE']);
        $opts["http"]["header"] .= "Cookie: " . $env['HTTP_COOKIE'] . "\r\n";
    } else {
        $env['HTTP_COOKIE'] = '';
    }
    $args = isset($section_text['ARGS']) ? ' -- ' . $section_text['ARGS'] : '';
    if (array_key_exists('POST_RAW', $section_text) && !empty($section_text['POST_RAW'])) {
        $post = trim($section_text['POST_RAW']);
        $raw_lines = explode("\n", $post);
        $request = '';
        $started = false;
        foreach ($raw_lines as $line) {
            if (empty($env['CONTENT_TYPE']) && preg_match('/^Content-Type:(.*)/i', $line, $res)) {
                $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1]));
                continue;
            }
            if ($started) {
                $request .= "\n";
            }
            $started = true;
            $request .= $line;
        }
        $env['CONTENT_LENGTH'] = strlen($request);
        $env['REQUEST_METHOD'] = 'POST';
        $opts["http"]["method"] = "POST";
        $opts["http"]["header"] .= "Content-type: " . $env['CONTENT_TYPE'] . "\r\n";
        $opts["http"]["content"] = $request;
        if (empty($request)) {
            error("POST empty in '{$file}'");
        }
    } else {
        if (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
            $post = trim($section_text['POST']);
            if (array_key_exists('GZIP_POST', $section_text) && function_exists('gzencode')) {
                $post = gzencode($post, 9, FORCE_GZIP);
                $env['HTTP_CONTENT_ENCODING'] = 'gzip';
            } else {
                if (array_key_exists('DEFLATE_POST', $section_text) && function_exists('gzcompress')) {
                    $post = gzcompress($post, 9);
                    $env['HTTP_CONTENT_ENCODING'] = 'deflate';
                }
            }
            //save_text($tmp_post, $post);
            $content_length = strlen($post);
            $env['REQUEST_METHOD'] = 'POST';
            $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
            $env['CONTENT_LENGTH'] = $content_length;
            $opts["http"]["method"] = "POST";
            $opts["http"]["header"] .= "Content-type: " . $env['CONTENT_TYPE'] . "\r\n";
            $opts["http"]["header"] .= "Content-encoding: " . $env['HTTP_CONTENT_ENCODING'] . "\r\n";
            $opts["http"]["header"] .= "Content-length: " . $content_length . "\r\n";
            $opts["http"]["content"] = $post;
        } else {
            $env['REQUEST_METHOD'] = 'GET';
            $env['CONTENT_TYPE'] = '';
            $env['CONTENT_LENGTH'] = '';
        }
    }
    $context = stream_context_create($opts);
    $out = _file_get_contents($www . $phpfile, false, $context, &$headers);
    if ($out === FALSE) {
        echo '<br/>';
        error("See <a target='_blank' href='{$phpfile}'>{$phpfile}</a>, exception ");
    }
    if (StartsWith($out, "\r\nCompileError") || StartsWith($out, "\r\nCompileWarning")) {
        show_result("<span class='skip'>SKIP</span>", $file, ", Script generates <b>CompileError</b> or <b>CompileWarning</b>, so it cannot be compared with PHP. <a href='{$phpfile}' target='_blank'>Try the script</a><pre>{$out}</pre>");
    }
    // perform clean
    try_clean($file, $www, $section_text);
    // compare .php response with expected output
    // Does the output match what is expected?
    $output = preg_replace("/\r\n/", "\n", trim($out));
    $output = str_replace("string[binary](", "string(", $output);
    $failed_headers = false;
    if (isset($section_text['EXPECTHEADERS'])) {
        $want = array();
        $wanted_headers = array();
        $lines = preg_split("/[\n\r]+/", (string) $section_text['EXPECTHEADERS']);
        foreach ($lines as $line) {
            if (strpos($line, ':') !== false) {
                $line = explode(':', $line, 2);
                $want[trim($line[0])] = trim($line[1]);
                $wanted_headers[] = trim($line[0]) . ': ' . trim($line[1]);
            }
        }
        $org_headers = $headers;
        $headers = array();
        $output_headers = array();
        foreach ($want as $k => $v) {
            if (isset($org_headers[$k])) {
                $headers = $org_headers[$k];
                $output_headers[] = $k . ': ' . $org_headers[$k];
            }
            if (!isset($org_headers[$k]) || $org_headers[$k] != $v) {
                $failed_headers = true;
            }
        }
        ksort($wanted_headers);
        $wanted_headers = join("\n", $wanted_headers);
        ksort($output_headers);
        $output_headers = join("\n", $output_headers);
    }
    if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) {
        if (isset($section_text['EXPECTF'])) {
            $wanted = trim($section_text['EXPECTF']);
        } else {
            $wanted = trim($section_text['EXPECTREGEX']);
        }
        $wanted_re = preg_replace('/\\r\\n/', "\n", $wanted);
        if (isset($section_text['EXPECTF'])) {
            // do preg_quote, but miss out any %r delimited sections
            $temp = "";
            $r = "%r";
            $startOffset = 0;
            $length = strlen($wanted_re);
            while ($startOffset < $length) {
                $start = strpos($wanted_re, $r, $startOffset);
                if ($start !== false) {
                    // we have found a start tag
                    $end = strpos($wanted_re, $r, $start + 2);
                    if ($end === false) {
                        // unbalanced tag, ignore it.
                        $end = $start = $length;
                    }
                } else {
                    // no more %r sections
                    $start = $end = $length;
                }
                // quote a non re portion of the string
                $temp = $temp . preg_quote(substr($wanted_re, $startOffset, $start - $startOffset), '/');
                // add the re unquoted.
                if ($end > $start) {
                    $temp = $temp . '(' . substr($wanted_re, $start + 2, $end - $start - 2) . ')';
                }
                $startOffset = $end + 2;
            }
            $wanted_re = $temp;
            $wanted_re = str_replace(array('%binary_string_optional%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? 'string' : 'binary string', $wanted_re);
            $wanted_re = str_replace(array('%unicode_string_optional%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? 'string' : 'Unicode string', $wanted_re);
            $wanted_re = str_replace(array('%unicode\\|string%', '%string\\|unicode%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? 'string' : 'unicode', $wanted_re);
            $wanted_re = str_replace(array('%u\\|b%', '%b\\|u%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? '' : 'u', $wanted_re);
            // Stick to basics
            $wanted_re = str_replace('%e', '\\' . '\\', $wanted_re);
            $wanted_re = str_replace('%s', '[^\\r\\n]+', $wanted_re);
            $wanted_re = str_replace('%S', '[^\\r\\n]*', $wanted_re);
            $wanted_re = str_replace('%a', '.+', $wanted_re);
            $wanted_re = str_replace('%A', '.*', $wanted_re);
            $wanted_re = str_replace('%w', '\\s*', $wanted_re);
            $wanted_re = str_replace('%i', '[+-]?\\d+', $wanted_re);
            $wanted_re = str_replace('%d', '\\d+', $wanted_re);
            $wanted_re = str_replace('%x', '[0-9a-fA-F]+', $wanted_re);
            $wanted_re = str_replace('%f', '[+-]?\\.?\\d+\\.?\\d*(?:[Ee][+-]?\\d+)?', $wanted_re);
            $wanted_re = str_replace('%c', '.', $wanted_re);
            // %f allows two points "-.0.0" but that is the best *simple* expression
        }
        /* DEBUG YOUR REGEX HERE
        		var_dump($wanted_re);
        		print(str_repeat('=', 80) . "\n");
        		var_dump($output);
        */
        if (preg_match("/^{$wanted_re}\$/s", $output)) {
            @unlink($phpfile);
            show_result("<span class='pass'>PASS</span>", "{$file}", '');
        }
    } else {
        $wanted = (string) trim($section_text['EXPECT']);
        $wanted = preg_replace('/\\r\\n/', "\n", $wanted);
        // compare and leave on success
        if (!strcmp($output, $wanted)) {
            @unlink($phpfile);
            show_result("<span class='pass'>PASS</span>", $file, '');
        }
        $wanted_re = null;
    }
    // Test failed so we need to report details.
    if ($failed_headers) {
        $passed = false;
        $wanted = (string) $wanted_headers . "\n--HEADERS--\n" . (string) $wanted;
        $output = (string) $output_headers . "\n--HEADERS--\n" . (string) $output;
        if (isset($wanted_re)) {
            $wanted_re = preg_quote($wanted_headers . "\n--HEADERS--\n", '/') . $wanted_re;
        }
    }
    // write .exp
    if (file_put_contents($file . '.exp', (string) $wanted, FILE_BINARY) === false) {
        error("Cannot create expected test output '{$file}.exp'");
    }
    // write .out
    if (file_put_contents($file . '.out', (string) $output, FILE_BINARY) === false) {
        error("Cannot create test output - '{$file}.out'");
    }
    // write .diff
    $diff = generate_diff($wanted, $wanted_re, $output);
    if (file_put_contents($file . '.diff', (string) $diff, FILE_BINARY) === false) {
        error("Cannot create test diff - '{$file}.diff'");
    }
    $resultid = "result_" . strlen($phpfile) . '_' . crc32($phpfile);
    $sourceid = "source_" . strlen($phpfile) . '_' . crc32($phpfile);
    show_result("<span class='fail'>FAIL</span>", $file, ", <a href='{$phpfile}' target='_blank'>Try the script</a>" . ", <a href='#' onclick='\$(\"#{$sourceid}\").slideToggle();return false;'>source</a>" . ", <a href='#' onclick='\$(\"#{$resultid}\").slideToggle();return false;'>details</a>" . "<div id='{$sourceid}' style='display:none;background:#eee;border:1px dashed #888;'><pre>" . htmlspecialchars(trim(_file_get_contents($file, false, null, &$dummyheaders))) . "</pre></div>" . "<div id='{$resultid}' style='display:none;'><table border='1'><tr><td><b>Output</b><br/><pre style='background:#fee;font-size:8px;'>" . htmlspecialchars($output) . "</pre></td><td><b>Expected</b><br/><pre  style='background:#efe;font-size:8px;'>" . htmlspecialchars($wanted) . "</pre></td></tr></table></div>");
    // write .sh
    //if (strpos($log_format, 'S') !== false && file_put_contents($sh_filename, b"#!/bin/sh{$cmd}", FILE_BINARY) === false) {
    //error("Cannot create test shell script - $sh_filename");
    //}
    //chmod($sh_filename, 0755);
    /*foreach ($restype as $type) {
    		$PHP_FAILED_TESTS[$type.'ED'][] = array (
    			'name'      => $file,
    			'test_name' => (is_array($IN_REDIRECT) ? $IN_REDIRECT['via'] : '') . $tested . " [$tested_file]",
    			'output'    => $output_filename,
    			'diff'      => $diff_filename,
    			'info'      => $info,
    		);
    	}*/
}
Exemplo n.º 9
0
Arquivo: wms.php Projeto: RickdeM/wms
 /**
  * The Starting Method
  *
  * @version 1
  * @author Rick de Man <*****@*****.**>
  *        
  */
 function __Construct()
 {
     // Store starting Time
     $this->TimeStarted = microtime(true);
     // Setup Load WMS Setup
     $File_wms = WMS_LIB . 'settings/wms.php';
     $File_reg = WMS_LIB . 'settings/regex.php';
     // File exist check
     if (!file_exists($File_wms)) {
         die('Missing settings file: Wms Setup');
     }
     // File exist check
     if (!file_exists($File_reg)) {
         die('Missing settings file: Regex Setup');
     }
     // Load WMS setting file
     include $File_wms;
     // Load Regex setting file
     include $File_reg;
     // Store Settings
     $this->WMS = $_WMS;
     $this->Regex = $_Regex;
     // Reset WMS 'After Loading elements'
     foreach ($_SESSION as $K => $V) {
         // If SESSION key starts with 'WMS-': Delelte
         if (StartsWith('WMS-', $K)) {
             unset($_SESSION[$K]);
         }
     }
 }
Exemplo n.º 10
0
    function MenuIzquierdo()
    {
        if ($_SESSION['session'][0]) {
            /* SECCIONES */
            $array = Acceso::AccesoSecciones($_SESSION['session'][0]);
            if (is_array($array)) {
                ?>
			<table cellpadding="0" cellspacing="0"  width="100%" id="menu_izquierdo" >
    		<tr>
				<td class="date"><a href="javascript:history.go(-1)"><img src="public_root/imgs/back.png" alt="Retroceder" width="16" height="16" border="0" align="absmiddle" style="margin-bottom:4px"/></a> <strong>MODULOS DEL SISTEMA</strong> <a href="javascript:history.go(1)"><img src="public_root/imgs/forward.png" alt="Retroceder" width="16" height="16" border="0" align="absmiddle" style="margin-bottom:4px"/></a></td>
			</tr>
			<tr>
				<td>
            		<?php 
                for ($c = 0; $c < sizeof($array); $c++) {
                    /*   PAGINAS  */
                    $paginas = Acceso::AccesoPaginasSecciones($array[$c]['id_modulo'], $_SESSION['session'][0]);
                    if (is_array($paginas)) {
                        $submenu = array();
                        ?>
					<div style="float: left" id="my_menu" class="sdmenu">
					<?php 
                        for ($z = 0; $z < sizeof($paginas); $z++) {
                            ?>
                        
						<?php 
                            if (!StartsWith(strtolower($paginas[$z]['pagina']), 'administracion')) {
                                ?>
							<div>
								<div class="item" id="menu<?php 
                                echo $paginas[$z]['id'];
                                ?>
">
									  <a href="<?php 
                                echo $paginas[$z]['url'];
                                ?>
"> <?php 
                                echo $paginas[$z]['pagina'];
                                ?>
</a>								</div>
							</div>
							<?php 
                            } else {
                                $submenu[] = $z;
                                //guardamos los indices
                            }
                            ?>
								                      
                        <?php 
                        }
                        if (count($submenu) > 0) {
                            ?>
						<div>
							<div class="item cerrado" id="admin"><a href="javascript:VerSubMenu()">Administraci&oacute;n</a></div>
							<div style="display:none" id="submenu">
							<?php 
                            for ($z = 0; $z < sizeof($submenu); $z++) {
                                $index = $submenu[$z];
                                ?>
								<div class="item subitem">
									<a href="<?php 
                                echo $paginas[$index]['url'];
                                ?>
"> <?php 
                                echo $paginas[$index]['pagina'];
                                ?>
</a>								</div>	
							<?php 
                            }
                            ?>
							</div>
						</div>
					    <?php 
                        }
                    }
                    ?>
				</div>
            <?php 
                }
                ?>
				</td>
			</tr>
        </table>
        <?php 
            }
        }
    }