/** * [Kind of controller's destructor. Called when child's work is done] * @return [type] [description] */ public function displayView() { $output = self::stopCapturing(); if (strlen($output) === 0) { Debug::write("No output from controller was detected. No additionnal action will be done on HTML content", 0); } else { $this->view->setContent("%%@MAIN CONTENT%%", $output); } $this->view->display(); /** * Breaking the DOM for credits or stats */ if ($GLOBALS['config']['website']['display_credits'] === true || $GLOBALS['config']['website']['display_stats'] === true) { echo '<div style="border-top: 1px ridge black;"><p style="text-align:center;font-size:12px;">'; if ($GLOBALS['config']['website']['display_credits'] === true) { echo $GLOBALS['config']['website']['name'] . ' v' . (is_numeric($GLOBALS['config']['website']['version']) ? number_format($GLOBALS['config']['website']['version'], 1) : $GLOBALS['config']['website']['version']) . ' ' . $GLOBALS['config']['website']['branch'] . ', powered by SPF v' . (is_numeric($GLOBALS['config']['framework']['version']) ? number_format($GLOBALS['config']['framework']['version'], 1) : $GLOBALS['config']['framework']['version']) . ' ' . $GLOBALS['config']['framework']['branch'] . '<br />'; } if ($GLOBALS['config']['website']['display_stats'] === true) { $time = round(Timer::getTimeFrom("Start"), 5); if ($time >= 1) { $unit = 's'; $time = round($time, 1); } else { $unit = 'ms'; $time = round($time * 1000, 5); } if ($this->db !== null) { echo 'Number of SQL requests : ' . $this->db->getStats() . ' - Page generated in ' . $time . $unit . '<br />'; } } echo '</p></div>'; } }
public function __construct() { parent::__construct(); Debug::write("Building common WebsiteController ...", 0); /** * Do common stuff concerning your website here */ }
/** * Initialize database */ public function loadDatabase() { Debug::write('Connecting to DB....', 'title'); try { $this->db = new PDO("mysql:host=" . self::$hostname . ";dbname=" . self::$database, self::$username, self::$password); } catch (PDOException $e) { Debug::write('Connection to DB fail.' . $e->getMessage(), 'error'); Debug::output(); exit; } Debug::write('Connection success.', 'success'); }
/** * This method is the primary mechanism for forwarding {@link Request} objects to AT&T APIs using PHP cURL. The response from the API * is automatically received, parsed and returned by this method as a {@link Response} object. * * @method makeRequest * * @param {string} method The http request method [GET|POST|PUT] * @param {string} url Target URL of the request. * @param {Request} request Request object to send to API. * * @return {Response} Returns a Response object * */ public function makeRequest($method, $url, $request = null) { try { $headers = $request->getHeaders(); $postfields = $request->getPostfields(); $curl = curl_init($url); $options = array(CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYHOST => ENABLE_SSL_CHECK, CURLOPT_SSL_VERIFYPEER => ENABLE_SSL_CHECK, CURLOPT_HEADER => true, CURLINFO_HEADER_OUT => true); curl_setopt_array($curl, $options); if ($method === "POST" || $method === "PUT") { curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields); } if ($method === "PUT") { if ($postfields === '[]') { curl_setopt($curl, CURLOPT_PUT, 1); } else { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); } } // // If debugging, set the options before executing the request // if (DEBUG) { $fp = Debug::init(); curl_setopt($curl, CURLOPT_STDERR, $fp); curl_setopt($curl, CURLOPT_VERBOSE, true); } $curl_response = curl_exec($curl); $curl_info = curl_getinfo($curl); // If debugging, capture the response body after the request has been sent, but before the curl instance is closed if (DEBUG) { Debug::write("\n>>>>> [ REQUEST HEADERS AND CONTENT ] >>>>>>>>>>>>\n"); Debug::write("{$curl_info['request_header']}"); if ($method == "POST") { Debug::write("{$postfields}\n"); } Debug::write(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n"); Debug::write("\n<<<<< [ RESPONSE HEADERS AND CONTENT ] <<<<<<<<<<<<\n{$curl_response}\n"); Debug::write("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); Debug::dumpBacktrace(); curl_close($curl); Debug::end(); } else { curl_close($curl); } return new Response(array("curl_info" => $curl_info, "curl_response" => $curl_response)); } catch (Exception $e) { return new Response($e); } }
public function prepare($_qry, $_options = NULL) { Debug::write("SQL prepare : " . $_qry, 2); self::$count = self::$count + 1; try { // Should be caught through Site.class.php, but still... just in case if ($_options === null) { return parent::prepare($_qry); } else { return parent::prepare($_qry, $_options); } } catch (PDOException $e) { Site::error(Site::app_error, "Database error", $GLOBALS['config']['security']['displayExplicitErrors'] === true ? $e->getMessage() : $GLOBALS['config']['errors']['framework']['503']); } }
<?php /** * TODO : clean statics * TODO : give the choice of OOP or not * TODO : update readme * * TODO : set replaceAllContent protected (and clean all others ?) * TODO : add IP who's not online */ require "init.php"; Timer::setMark("Start"); $site = new Site(); Timer::setMark("End"); Debug::write("Page rendered in " . Timer::getTimeBetween("Start", "End") . " secs", 0); Debug::display();
protected function write($verbosity_level, $string, $code_line = '', $params = array()) { if(!$this->mock) { if($verbosity_level != self :: TIMING_POINT) parent :: write($verbosity_level, $string, $code_line, $params); else parent :: write($verbosity_level, $string); return; } if($verbosity_level != self :: TIMING_POINT) { $this->mock->_invoke('write', array($verbosity_level, $string, $params)); $call_parent = true; foreach($this->expected_data as $id => $data) { if( $verbosity_level == $data['level'] && $string == $data['message'] && $params == $data['params']) { $call_parent = false; break; } } if($call_parent) { $this->test->fail('unexpected debug exception: [ ' . $string . ' ]'); parent :: write($verbosity_level, $string, $code_line, $params); } } }
/** * Search a filename * * @param {string} filename * @param {string} content reference */ public function getFile($filename, &$content) { if (!$this->loaded) { return false; } // Case sensitive. faster $position = strpos($this->fileTable, $filename . ""); // Not case sensitive, slower... if ($position === false) { $position = stripos($this->fileTable, $filename . ""); } // File not found if ($position === false) { Debug::write('File not found in ' . $this->filename); return false; } // Extract file info from fileList $position += strlen($filename) + 1; $fileInfo = unpack('Lpack_size/Llength_aligned/Lreal_size/Cflags/Lposition', substr($this->fileTable, $position, 17)); // Just open file. if ($fileInfo['flags'] !== 1) { Debug::write('Can\'t decrypt file in GRF ' . $this->filename); return false; } // Extract file fseek($this->fp, $fileInfo['position'] + self::HEADER_SIZE, SEEK_SET); $content = gzuncompress(fread($this->fp, $fileInfo['pack_size']), $fileInfo['real_size']); Debug::write('File found and extracted from ' . $this->filename, 'success'); return true; }
public function revokeConsentToken($scope) { // Create service for requesting an OAuth token $osrvc = new OAuthTokenService($this->base_url, $this->client_id, $this->client_secret); $refresh_token_string = isset($_SESSION['consent_refresh_tokens'][$scope]) ? $_SESSION['consent_refresh_tokens'][$scope] : ''; if (empty($refresh_token_string)) { return; } if (DEBUG) { Debug::init(); $a = $refresh_token_string; Debug::write("Revoke Consent Refresh token: {$a}.\n"); Debug::end(); } $this->revokeRefreshToken($refresh_token_string); // Parse the consent_tokens array and update each taken that matches old_token $consent_tokens = isset($_SESSION['consent_refresh_tokens']) ? $_SESSION['consent_refresh_tokens'] : ''; foreach ($consent_tokens as $key => $value) { if ($_SESSION['consent_refresh_tokens'][$key] == $refresh_token_string) { unset($_SESSION['consent_tokens'][$key]); unset($_SESSION['consent_refresh_tokens'][$key]); unset($_SESSION['consent_expires_at'][$key]); } } }
} catch (ServiceException $se) { switch ($se->getErrorCode()) { case 400: // invalid_grant. Invalid Refresh token. // invalid_grant. Invalid Refresh token. case 401: // UnAuthorized Access. Invalid access token. unset($_SESSION['client_token']); if (DEBUG) { Debug::init(); Debug::write("Removed cached client token. Errocode=" . $se->getErrorCode() . "\n"); Debug::end(); } break; } return_json_error($se->getErrorCode(), $se->getErrorResponse()); } catch (Exception $e) { $error = $e->getMessage(); // some operations in the codekit do not throw ServiceException if (stripos($error, 'UnAuthorized Request') !== false) { unset($_SESSION['client_token']); if (DEBUG) { Debug::init(); Debug::write("token removed.\n"); Debug::end(); } return_json_error(401, "UnAuthorized Request. Try again to obtain a new access token."); } else { return_json_error(400, $error); } }
/** * Storing file in data folder (convert it if needed) * * @param {string} save to path * @param {string} file content * @return {string} content */ public static function store($path, $content) { $path = utf8_encode($path); $current_path = self::$path; $local_path = $current_path . str_replace('\\', '/', $path); $parent_path = preg_replace("/[^\\/]+\$/", '', $local_path); if (!file_exists($parent_path)) { if (!@mkdir($parent_path, 0777, true)) { Debug::write("Can't build path '{$parent_path}', need write permission ?", 'error'); return $content; } } if (!is_writable($parent_path)) { Debug::write("Can't write file to '{$parent_path}', need write permission.", 'error'); return $content; } // storing bmp images as png if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) === 'bmp') { $img = imagecreatefrombmpstring($content); $path = str_ireplace('.bmp', '.png', $local_path); imagepng($img, $path); return file_get_contents($path); } // Saving file file_put_contents($local_path, $content); return $content; }
public static function log($_msg) { if (!isset($GLOBALS['config']['log']['file']) || !file_exists($GLOBALS['config']['log']['file'])) { return; } $file = fopen($GLOBALS['config']['log']['file'], 'a'); if (!$file) { Debug::write("Couldn't log message : " . $_msg, 0); return; } fwrite($file, $_msg . PHP_EOL); fclose($file); }
if (!empty($refresh_token_string)) { if (DEBUG) { Debug::init(); Debug::write("Revoke Client Refresh token: {$refresh_token_string}.\n"); Debug::end(); } $html5_serviceprovider_base->revokeRefreshToken($refresh_token_string); } } else { if ($revoke == 'consent_ex') { // to test external revoke $refresh_token_string = isset($_SESSION['consent_refresh_tokens']['MIM']) ? $_SESSION['consent_refresh_tokens']['MIM'] : ''; if (!empty($refresh_token_string)) { if (DEBUG) { Debug::init(); Debug::write("Revoke Consent Refresh token: {$refresh_token_string}.\n"); Debug::end(); } $html5_serviceprovider_base->revokeRefreshToken($refresh_token_string); } } } } } } catch (ServiceException $se) { return_json_error($se->getErrorCode(), $se->getErrorResponse()); } catch (Exception $e) { return_json_error(400, $e->getMessage()); } $reduce_token_expiry_by = isset($config['ReduceTokenExpiryInSeconds_Debug']) ? (int) $config['ReduceTokenExpiryInSeconds_Debug'] : 0; echo 'Time Now: ' . date("r") . ' (' . getdate()[0] . ')<br>';
if (Cache::$time && !is_writable(Cache::$path)) { Cache::$time = 0; Debug::write('Disable Cache system, don\'t have write acess to "' . Cache::$path . '".', 'error'); } if (Client::$AutoExtract && !is_writable(Client::$path . 'data/')) { Client::$AutoExtract = false; Debug::write('Disable GRF auto-extract mode, don\'t have write access to "' . Client::$path . 'data/".', 'error'); } // Don't cache images when debug mode is on if (Debug::isEnable()) { Cache::$time = 0; } // Url Rewriting $routes = array(); $routes['/character/(.*)/(\\d+)/([0-7])'] = 'Character'; $routes['/character/(.*)'] = 'Character'; $routes['/characterhead/(.*)'] = 'CharacterHead'; $routes['/avatar/(.*)'] = 'Avatar'; $routes['/signature/(.*)'] = 'Signature'; $routes['/monster/(\\d+)'] = 'Monster'; $routes['/generate/body=(F|M)-(\\d+)-(\\d+)/hair=(\\d+)-(\\d+)-(\\d)/hats=(\\d+)-(\\d+)-(\\d+)/equip=(\\d+)-(\\d+)-(\\d+)/option=(\\d+)/actdir=([0-7])-(\\d+)-(\\d+)'] = 'Generator'; //$routes['/update/(hats|mobs|robes)'] = 'Update'; // Uncomment this line if you want to perform updates by updating lua files. try { // Initialize client and process Client::init(); Controller::run($routes); } catch (Exception $e) { Debug::write($e->getMessage(), 'error'); } // Debug Debug::output();
public function __construct() { parent::__construct(); Debug::write("Executing Index work() method...", 1); $this->work(); }
require_once "service_provider/Html5_ServiceProvider_Base_Att.php"; } $html5_serviceprovider_base = new Html5_ServiceProvider_Base_Att($config); if (isset($_GET['scope'])) { $scope = $_GET['scope']; if (DEBUG) { Debug::init(); $a = $_SESSION['consent_refresh_tokens'][$scope]; Debug::write("Revoke Old Refresh token: {$a}.\n"); Debug::end(); } if (isset($_SESSION['consent_tokens'][$scope])) { $html5_serviceprovider_base->revokeConsentToken($scope); //unset($_SESSION['consent_tokens'][$scope]); } } else { if (DEBUG) { Debug::init(); $a = $_SESSION['consent_refresh_tokens']['MIM']; Debug::write("Revoke Old Refresh token: {$a}.\n"); Debug::end(); } $html5_serviceprovider_base->revokeConsentToken('MIM'); $html5_serviceprovider_base->revokeConsentToken('IMMN'); } echo "{\"authorized\": false }"; } catch (ServiceException $se) { return_json_error($se->getErrorCode(), $se->getErrorResponse()); } catch (Exception $e) { return_json_error(400, $e->getMessage()); }
/** * [A kind of destructor. * loads template, replace patterns and display the content to the web browser] */ public function display() { if (empty($this->template)) { if (!isset($GLOBALS['config']['HTML']['template']) || empty($GLOBALS['config']['HTML']['template'])) { Site::error(Site::app_error, "10", $GLOBALS['config']['errors']['framework']['10']); } elseif (!is_dir(HTML_DIR . $GLOBALS['config']['HTML']['template'])) { Site::error(Site::app_error, "11", $GLOBALS['config']['errors']['framework']['11']); } $this->template = HTML_DIR . $GLOBALS['config']['HTML']['template'] . "/" . $GLOBALS['config']['HTML']['template'] . ".template"; } if (is_readable($this->template)) { ob_start(); include $this->template; $this->content = ob_get_clean(); } else { Site::error(Site::app_error, "12", $GLOBALS['config']['errors']['framework']['12']); } if (empty($this->items)) { Debug::write("No pattern to be replaced were found in this template !", 0); } $this->replaceDefaultUserContent(); $this->setLocaleContent("global"); if ($this->locale) { $this->setLocaleContent($this->locale); } $this->replaceAllContent(); /** * look for unreplaced patterns */ preg_match_all("/%%[^%]*%%/", $this->content, $ressources_config_file); preg_match_all("/##[^#]*##/", $this->content, $ressources_locale); $unreplaced_patterns = array_merge($ressources_locale[0], $ressources_config_file[0]); if (!empty($unreplaced_patterns)) { foreach ($unreplaced_patterns as $pattern) { $current = "'" . $pattern . "' "; $msg = empty($msg) ? $current : $msg . $current; $this->setContent($pattern, ""); } $msg = preg_replace("/%/", "", $msg); Debug::write("One or several HTML field hasn't been replaced : " . htmlentities($msg), 0); if (!isset($GLOBALS['config']['HTML']['view']['suppressUnmatchedPatterns']) || $GLOBALS['config']['HTML']['view']['suppressUnmatchedPatterns'] === true) { $this->replaceAllContent(); } //delete unreplaced patterns from HTML template } echo $this->content; }
// Check Allowed directory if (!preg_match('/\\/(' . $directory . '\\/)?(data|BGM)\\//', $path)) { Debug::write('Forbidden directory, you can just access files located in data and BGM folder.', 'error'); Debug::output(); } // Get file $path = preg_replace('/(.*(' . $directory . '\\/)?)(data|BGM\\/.*)/', '$3', $path); $path = str_replace('/', '\\', $path); $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION)); $file = Client::getFile($path); // File not found, end. if ($file === false) { Debug::write('Failed, file not found...', 'error'); Debug::output(); } else { Debug::write('Success !', 'success'); } header('Status: 200 OK', true, 200); header("Cache-Control: max-age=2592000, public"); header("Expires: Sat, 31 Jan 2015 05:00:00 GMT"); // Display appropriate header switch ($ext) { case 'jpg': case 'jpeg': header('Content-type:image/jpeg'); break; case 'bmp': header('Content-type:image/bmp'); break; case 'gif': header('Content-type:image/gif');
/** * Get a file from client, search it on data dir first, and on grfs. */ public static function getFile($path) { Debug::write('Trying to find file "' . $path . '"...', 'title'); $local_path = self::$path; $local_path .= str_replace('\\', '/', $path); $grf_path = str_replace('/', '\\', $path); // Read data first if (file_exists($local_path) && !is_dir($local_path) && is_readable($local_path)) { Debug::write('Find at "' . $local_path . '"', 'success'); return $local_path; } // Search in GRFS Debug::write('File not found in data folder.'); if (count(self::$grfs)) { Debug::write('Searching in GRFs...'); } foreach (self::$grfs as $grf) { // Load GRF just if needed if (!$grf->loaded) { Debug::write('Loading GRF file "' . $grf->filename . '"...', 'info'); $grf->load(); } // If file is found if ($grf->getFile($grf_path, $content)) { Debug::write('Search in GRF "' . $grf->filename . '", found.', 'success'); // Auto Extract GRF files ? if (self::$AutoExtract) { Debug::write('Saving file to data folder...', 'info'); $current_path = self::$path; $directories = explode('/', $path); array_pop($directories); // Creating directories foreach ($directories as $dir) { $current_path .= $dir . DIRECTORY_SEPARATOR; if (!file_exists($current_path)) { mkdir($current_path); } } // Saving file file_put_contents($local_path, $content); return $local_path; } return "data://application/octet-stream;base64," . base64_encode($content); } Debug::write('Search in GRF "' . $grf->filename . '", fail.'); } Debug::write('File not found...', 'error'); return false; }