private static function lock_file_name($file_name) { //-- $file_name = (string) $file_name; //-- if (!SmartFileSysUtils::check_file_or_dir_name($file_name)) { //-- this is for absolute paths for example, to avoid create lock outside ... if (!is_dir('tmp/locks')) { self::dir_recursive_create('tmp/locks'); } //end if $lock_file = 'tmp/locks/' . SmartHashCrypto::sha256(SMART_FRAMEWORK_SECURITY_KEY . '!' . $file_name) . '__' . substr(Smart::safe_filename($file_name, '-'), 0, 99) . '.__LOCK__'; // this is a max of 165 chars (file name is no more than 255 bytes on many systems) //-- } else { //-- $lock_file = $file_name . '.__LOCK__'; //-- } //end if else //-- return (string) $lock_file; //-- }
/** * Decompress RAW LZS * * @access private * @internal * */ public static function decompressRawLZS($compressed) { //-- $unarch = trim(self::RawInflate((string) $compressed)); //-- checksum verification $arr = explode('#CHECKSUM-SHA1#', $unarch); $unarch = trim($arr[0]); $checksum = trim($arr[1]); //-- if ((string) SmartHashCrypto::sha1($unarch) != (string) $checksum) { Smart::log_warning('SmartArchiverLZS/decompressRawLZS: Checksum Failed'); return ''; // string is corrupted, avoid to return } //end if //-- return @hex2bin(strtolower($unarch)); //-- }
public static function save_debug_info($y_area, $y_debug_token, $is_main) { //-- {{{SYNC-DEBUG-DATA}}} if ((string) SMART_FRAMEWORK_DEBUG_MODE != 'yes') { return false; } //end if //-- if ((string) $y_area != 'idx' and (string) $y_area != 'adm') { return false; } //end if //-- $y_debug_token = trim((string) $y_debug_token); if ((string) $y_debug_token == '') { return false; } //end if //-- $the_dir = 'tmp/logs/' . Smart::safe_filename($y_area) . '/' . date('Y-m-d@H') . '-debug-data/' . Smart::safe_filename($y_debug_token) . '/'; //-- #END# SYNC //-- if ($is_main) { $the_file = $the_dir . 'debug-main.log'; } else { $the_file = $the_dir . 'debug-sub-req-' . time() . '-' . SmartHashCrypto::sha1($_SERVER['REQUEST_URI']) . '.log'; } //end if else //-- //-- if (!is_dir($the_dir)) { SmartFileSystem::dir_recursive_create($the_dir); } //end if //-- if (is_dir($the_dir)) { if (is_writable($the_dir)) { //-- $arr = array(); //-- generate debug info if set to show optimizations SmartMarkersTemplating::registerOptimizationHintsToDebugLog(); //-- generate debug info if set to show internals if (defined('SMART_FRAMEWORK_INTERNAL_DEBUG')) { Smart::registerInternalCacheToDebugLog(); SmartFrameworkRegistry::registerInternalCacheToDebugLog(); SmartAuth::registerInternalCacheToDebugLog(); SmartHashCrypto::registerInternalCacheToDebugLog(); SmartUtils::registerInternalCacheToDebugLog(); SmartMarkersTemplating::registerInternalCacheToDebugLog(); } //end if //-- $dbg_stats = (array) SmartFrameworkRegistry::getDebugMsgs('stats'); //-- $arr['date-time'] = date('Y-m-d H:i:s O'); $arr['debug-token'] = (string) $y_debug_token; $arr['is-request-main'] = $is_main; $arr['request-hash'] = SmartHashCrypto::sha1($_SERVER['REQUEST_URI']); $arr['request-uri'] = (string) $_SERVER['REQUEST_URI']; $arr['resources-time'] = $dbg_stats['time']; $arr['resources-memory'] = $dbg_stats['memory']; $arr['response-code'] = (int) http_response_code(); $arr['response-headers'] = base64_encode(Smart::seryalize((array) headers_list())); if (function_exists('getallheaders')) { $arr['request-headers'] = base64_encode(Smart::seryalize((array) getallheaders())); } else { $arr['request-headers'] = base64_encode(Smart::seryalize('')); } //end if else $arr['env-req-filtered'] = base64_encode(Smart::seryalize((array) SmartFrameworkRegistry::getRequestVars())); $arr['env-get'] = base64_encode(Smart::seryalize((array) $_GET)); $arr['env-post'] = base64_encode(Smart::seryalize((array) $_POST)); $arr['env-cookies'] = base64_encode(Smart::seryalize((array) $_COOKIE)); $arr['env-server'] = base64_encode(Smart::seryalize((array) $_SERVER)); if (@session_status() === PHP_SESSION_ACTIVE) { $arr['php-session'] = base64_encode(Smart::seryalize((array) $_SESSION)); } else { $arr['php-session'] = base64_encode(Smart::seryalize('')); } //end if else if (SmartAuth::check_login() === true) { $arr['auth-data'] = array('is_auth' => true, 'login_data' => (array) SmartAuth::get_login_data(), '#login-pass#', SmartAuth::get_login_password()); } else { $arr['auth-data'] = array('is_auth' => false, 'login_data' => array()); } //end if else foreach ((array) SmartFrameworkRegistry::getDebugMsgs('optimizations') as $key => $val) { $arr['log-optimizations'][(string) $key] = base64_encode(Smart::seryalize((array) $val)); } //end foreach foreach ((array) SmartFrameworkRegistry::getDebugMsgs('extra') as $key => $val) { $arr['log-extra'][(string) $key] = base64_encode(Smart::seryalize((array) $val)); } //end foreach foreach ((array) SmartFrameworkRegistry::getDebugMsgs('db') as $key => $val) { $arr['log-db'][(string) $key] = base64_encode(Smart::seryalize((array) $val)); } //end foreach $arr['log-mail'] = base64_encode(Smart::seryalize((array) SmartFrameworkRegistry::getDebugMsgs('mail'))); foreach ((array) SmartFrameworkRegistry::getDebugMsgs('modules') as $key => $val) { $arr['log-modules'][(string) $key] = base64_encode(Smart::seryalize((array) $val)); } //end foreach //-- SmartFileSystem::write($the_file, Smart::seryalize($arr)); //-- } //end if } //end if //-- //-- return true; //-- }
public static function test_fs() { //-- if (SMART_FRAMEWORK_TESTUNIT_ALLOW_FS_TESTS !== true) { return SmartComponents::operation_notice('Test Unit File System Tests are DISABLED ...'); } //end if //-- //-- $time = microtime(true); //-- //-- $err = ''; $tests = array(); //-- //-- if ((string) DIRECTORY_SEPARATOR != '\\') { // broken links do not work on Windows ! $tests[] = '##### FileSystem OPERATIONS / TESTS - ALL: #####'; } else { $tests[] = '##### FileSystem OPERATIONS / TESTS *** PARTIAL SUPPORT ONLY (BY PLATFORM) ***: #####'; } //end if else //-- //-- $test_string = '#START#' . "\n" . 'グッド' . "\n" . 'SmartFramework/Test/FileSystem' . "\n" . time() . "\n" . SMART_FRAMEWORK_HTACCESS_NOINDEXING . SMART_FRAMEWORK_HTACCESS_FORBIDDEN . SMART_FRAMEWORK_HTACCESS_NOEXECUTION . "\n" . '#END#'; $test_str_cksum = SmartHashCrypto::sha512($test_string); $long_prefixed = SmartFileSysUtils::prefixed_sha1_path(sha1(time())); $short_prefixed = SmartFileSysUtils::prefixed_uuid10_dir(Smart::uuid_10_seq()); //-- $the_base_folder = 'tmp/tests/'; $the_sufx_folder = 'Folder1'; $the_base_file = 'NORMAL-Write_123_@#.txt'; //-- $the_folder = $the_base_folder . $the_sufx_folder . '/'; $the_copy_folder = $the_base_folder . 'folder2'; $the_move_folder = $the_base_folder . 'FOLDER3'; $the_extra_folder = $the_folder . 'extra/'; $the_file = $the_folder . $the_base_file; //-- $get_folder = SmartFileSysUtils::add_dir_last_slash(SmartFileSysUtils::get_dir_from_path($the_folder)); $get_file = SmartFileSysUtils::get_file_name_from_path($the_file); $get_xfile = SmartFileSysUtils::get_noext_file_name_from_path($the_file); $get_ext = SmartFileSysUtils::get_file_extension_from_path($the_file); //-- $the_copy_file = $the_file . '.copy.txt'; $the_move_file = $the_extra_folder . $the_base_file . '.copy.moved.txt'; $the_broken_link = $the_extra_folder . 'a-broken-link'; $the_broken_dir_link = $the_extra_folder . 'a-broken-dir-link'; $the_good_link = $the_extra_folder . 'a-good-link'; $the_good_dir_link = $the_extra_folder . 'a-good-dir-link'; //-- //-- $tests[] = 'INITIAL-FOLDER: ' . $get_folder; $tests[] = 'NEW-FOLDER: ' . $the_folder; $tests[] = 'NEW-FILE: ' . $the_file; //-- //-- if ((string) $err == '') { $the_test = 'CHECK TEST SAFE PATH NAME: DIR / FILE ...'; $tests[] = $the_test; if ((string) Smart::safe_pathname((string) $get_folder) !== (string) $get_folder or (string) Smart::safe_pathname((string) $the_copy_file) !== (string) $the_copy_file) { $err = 'ERROR: SAFE PATH NAME TEST ... FAILED !!!'; } //end if } //end if //-- if ((string) $err == '') { $the_test = 'CHECK TEST ABSOLUTE / BACKWARD PATHS ...'; $tests[] = $the_test; if (!SmartFileSysUtils::check_file_or_dir_name('/this/is/absolute', 'no') or SmartFileSysUtils::check_file_or_dir_name('/this/is/absolute') or SmartFileSysUtils::check_file_or_dir_name('/this/is/../backward/path')) { $err = 'ERROR: CHECK TEST ABSOLUTE / BACKWARD PATHS ... FAILED !!!'; } //end if } //end if //-- if ((string) $err == '') { $the_test = 'CHECK EXTRACT FOLDER FROM PATH ...'; $tests[] = $the_test; if ((string) $get_folder != SmartFileSysUtils::add_dir_last_slash(Smart::dir_name($the_folder))) { $err = 'ERROR: Path Extraction FAILED: Dir=' . $get_folder . ' ; DirName=' . SmartFileSysUtils::add_dir_last_slash(Smart::dir_name($the_folder)); } //end if } //end if if ((string) $err == '') { $the_test = 'CHECK EXTRACT FILE AND EXTENSION FROM PATH (1) ...'; $tests[] = $the_test; if ((string) $get_folder . SmartFileSysUtils::add_dir_last_slash($the_sufx_folder) . $get_file != $the_file) { $err = 'ERROR :: Path Extraction FAILED: Re-Composed-File=' . $get_folder . SmartFileSysUtils::add_dir_last_slash($the_sufx_folder) . $get_file . ' ; File=' . $the_file; } //end if } //end if if ((string) $err == '') { $the_test = 'CHECK EXTRACT FILE AND EXTENSION FROM PATH (2) ...'; $tests[] = $the_test; if ((string) $get_file != $get_xfile . '.' . $get_ext) { $err = 'ERROR :: Path Extraction FAILED: File=' . $get_file . ' ; XFile=' . $get_xfile . ' ; Ext=' . $get_ext; } //end if } //end if //-- SmartFileSysUtils::raise_error_if_unsafe_path($the_folder); if ((string) $err == '') { $the_test = 'CHECK PATH NAME DIR: check_file_or_dir_name() : ' . $the_folder; $tests[] = $the_test; $result = 0; $result = SmartFileSysUtils::check_file_or_dir_name($the_folder); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if SmartFileSysUtils::raise_error_if_unsafe_path($the_file); if ((string) $err == '') { $the_test = 'CHECK PATH NAME FILE: check_file_or_dir_name() : ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSysUtils::check_file_or_dir_name($the_file); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- //-- if ((string) $err == '') { $parent_folder = SmartFileSysUtils::add_dir_last_slash(''); $the_test = 'Check Add Dir Last (trailing) Slash: Empty Folder Name'; $tests[] = $the_test; if ((string) $parent_folder != './') { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $parent_folder = SmartFileSysUtils::add_dir_last_slash('.'); $the_test = 'Check Add Dir Last (trailing) Slash: Dot Folder Name: ' . $parent_folder; $tests[] = $the_test; if ((string) $parent_folder != './') { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $parent_folder = SmartFileSysUtils::add_dir_last_slash('./'); $the_test = 'Check Add Dir Last (trailing) Slash: DotSlash Folder Name: ' . $parent_folder; $tests[] = $the_test; if ((string) $parent_folder != './') { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $parent_folder = SmartFileSysUtils::add_dir_last_slash(Smart::dir_name($the_base_folder)); $the_test = 'Check Parent Dir Name with Add Dir Last (trailing) Slash: ' . $parent_folder . ' # from: ' . $the_base_folder; $tests[] = $the_test; if ((string) $parent_folder != 'tmp/') { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- //-- if ((string) $err == '') { if (is_dir($get_folder)) { $the_test = 'DIR DELETE - INIT CLEANUP: dir_delete() + recursive: ' . $get_folder; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_delete($the_base_folder, true); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } else { $tests[] = 'DIR DELETE - INIT CLEANUP: Test Not Run (folder does not exists): ' . $get_folder; } //end if else } //end if //-- if ((string) $err == '') { $the_test = 'DIR CREATE RECURSIVE: dir_recursive_create() : ' . $the_folder . $long_prefixed . $short_prefixed; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_recursive_create($the_folder . $long_prefixed . $short_prefixed); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'DIR CREATE NON-RECURSIVE: dir_create() : extra/ in : ' . $the_extra_folder; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_recursive_create($the_extra_folder); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- if ((string) DIRECTORY_SEPARATOR != '\\') { // broken links do not work on Windows ! if ((string) $err == '') { $the_test = 'CREATE BROKEN FILE LINK FOR DELETION (1): link_create() : as : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::link_create('tmp/cache', $the_broken_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'DELETE BROKEN FILE LINK (1): delete() : as : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::delete($the_broken_link); if ($result !== 1 || is_link($the_broken_link)) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'CREATE BROKEN FILE LINK FOR DELETION (2): link_create() : as : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::link_create('tmp/index.html', $the_broken_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'DELETE BROKEN FILE LINK (2): dir_delete() : as : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_delete($the_broken_link); if ($result !== 1 || is_link($the_broken_link)) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'CREATE BROKEN FILE LINK: link_create() : as : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::link_create('tmp/index.html', $the_broken_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'CREATE BROKEN DIR LINK: link_create() : as : ' . $the_broken_dir_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::link_create('tmp/', $the_broken_dir_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'CREATE A FILE LINK: link_create() : as : ' . $the_good_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::link_create(Smart::real_path('tmp/index.html'), $the_good_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'CREATE A DIR LINK: link_create() : as : ' . $the_good_dir_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::link_create(Smart::real_path('tmp/'), $the_good_dir_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if } //end if //-- if ((string) $err == '') { $the_test = 'FILE WRITE with empty content: write() : ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::write($the_file, ''); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE WRITE: write() / before append : ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::write($the_file, $test_string); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE WRITE: write() +append : ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::write($the_file, $test_string, 'a'); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE READ / Append: read() Full Size: ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::read($the_file); if ((string) SmartHashCrypto::sha512($result) != (string) SmartHashCrypto::sha512($test_string . $test_string)) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE WRITE: re-write() : ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::write($the_file, $test_string); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- if ((string) DIRECTORY_SEPARATOR != '\\') { // broken links do not work on Windows ! if ((string) $err == '') { $the_test = 'FILE WRITE TO A BROKEN LINK: write() : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::write($the_broken_link, $test_string); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'DELETE THE BROKEN LINK AFTER write() and RE-CREATE IT : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::delete($the_broken_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'RE-CREATE BROKEN FILE LINK [AFTER WRITE]: link_create() : as : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::link_create('tmp/index.html', $the_broken_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE WRITE: write_if_not_exists() with Content Compare to a broken link : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::write_if_not_exists($the_broken_link, $test_string, 'yes'); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'DELETE THE BROKEN LINK AFTER write_if_not_exists() and RE-CREATE IT : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::delete($the_broken_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'RE-CREATE BROKEN FILE LINK [AFTER WRITE-IF-NOT-EXISTS]: link_create() : as : ' . $the_broken_link; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::link_create('tmp/index.html', $the_broken_link); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if } //end if //-- if ((string) $err == '') { $the_test = 'FILE WRITE: write_if_not_exists() without Content Compare : ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::write_if_not_exists($the_file, $test_string, 'no'); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- if ((string) $err == '') { $the_test = 'FILE READ: read() Full Size: ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::read($the_file); if ((string) SmartHashCrypto::sha512($result) != (string) $test_str_cksum) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE READ: read() Partial Size, First 10 bytes: ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::read($the_file, 10); if ((string) sha1($result) != (string) sha1(substr($test_string, 0, 10))) { // here we read bytes so substr() not SmartUnicode::sub_str() should be used $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- if ((string) $err == '') { $the_test = 'FILE STATIC-READ: staticread() Full Size: ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::staticread($the_file); if ((string) SmartHashCrypto::sha512($result) != (string) $test_str_cksum) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE STATIC-READ: staticread() Partial Size, First 10 bytes: ' . $the_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::staticread($the_file, 10); if ((string) sha1($result) != (string) sha1(substr($test_string, 0, 10))) { // here we read bytes so substr() not SmartUnicode::sub_str() should be used $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- if ((string) $err == '') { $the_test = 'FILE COPY: copy() : ' . $the_file . ' to: ' . $the_copy_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::copy($the_file, $the_copy_file); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE COPY with OVERWRITE: copy() : ' . $the_file . ' to: ' . $the_copy_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::copy($the_file, $the_copy_file, true); // overwrite destination file(s) if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'FILE RE-COPY (test should re-write the destination): copy() : ' . $the_file . ' to: ' . $the_move_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::copy($the_file, $the_move_file); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } else { $the_test = 'FILE DELETE: delete() : ' . $the_move_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::delete($the_move_file); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if } //end if if ((string) $err == '') { $the_test = 'FILE RENAME/MOVE: rename() : ' . $the_copy_file . ' to: ' . $the_move_file; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::rename($the_copy_file, $the_move_file); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- if ((string) $err == '') { if (is_dir('__development/')) { //-- $the_test = 'RECURSIVE COPY (CLONE) DIR [DEVELOPMENT]: dir_copy() : ' . '__development/' . ' to: ' . $the_folder . '__development'; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_copy('__development/', $the_folder . '__development'); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if //-- if ((string) $err == '') { $the_test = 'DIR COMPARE THE [DEVELOPMENT] SOURCE WITH [DEVELOPMENT] DESTINATION AFTER DIR COPY AND DIR MOVE:' . "\n" . 'compare_folders() : ' . '__development/' . ' with: ' . $the_folder . '__development/'; $tests[] = $the_test; $arr_diff = array(); $arr_diff = SmartFileSystem::compare_folders('__development', $the_folder . '__development', true, true); if (Smart::array_size($arr_diff) > 0) { $err = 'ERROR :: ' . $the_test . ' #DIFFERENCES=' . print_r($arr_diff, 1); } //end if } //end if //-- } else { $tests[] = 'RECURSIVE COPY (CLONE) DIR [DEVELOPMENT]: Test Not Run (Development environment not detected) ...'; } //end if else } //end if //-- if ((string) $err == '') { $the_test = 'RECURSIVE COPY (CLONE) DIR: dir_copy() : ' . $the_folder . ' to: ' . $the_copy_folder; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_copy($the_folder, $the_copy_folder); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- if ((string) $err == '') { $the_test = 'MOVE/RENAME DIR: dir_rename() : ' . $the_copy_folder . ' to: ' . $the_move_folder; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_rename($the_copy_folder, $the_move_folder); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- if ((string) $err == '') { $the_test = 'DIR COMPARE THE SOURCE WITH DESTINATION AFTER DIR COPY AND DIR MOVE: ' . $the_folder . ' with: ' . $the_move_folder; $tests[] = $the_test; $arr_diff = array(); $arr_diff = SmartFileSystem::compare_folders($the_folder, $the_move_folder, true, true); if (Smart::array_size($arr_diff) > 0) { $err = 'ERROR :: ' . $the_test . ' #DIFFERENCES=' . print_r($arr_diff, 1); } //end if } //end if //-- if ((string) $err == '') { $the_test = 'DIR DELETE - SIMPLE: dir_delete() non-recursive: ' . $the_extra_folder; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_delete($the_extra_folder, false); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if if ((string) $err == '') { $the_test = 'DIR DELETE - LAST CLEANUP: dir_delete() + recursive: ' . $get_folder; $tests[] = $the_test; $result = 0; $result = SmartFileSystem::dir_delete($the_base_folder, true); if ($result !== 1) { $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result; } //end if } //end if //-- //-- $time = 'TOTAL TIME was: ' . (microtime(true) - $time); //-- //-- $end_tests = '##### END TESTS ... ' . $time . ' sec. #####'; //-- //-- if ((string) $err == '') { $img_sign = 'lib/core/img/sign_info.png'; $img_check = 'lib/core/img/q_completed.png'; $text_main = Smart::escape_js('<span style="color:#83B953;">Good ... Perfect :: グッド ... パーフェクト</span>'); $text_info = Smart::escape_js('<h2><span style="color:#83B953;">All</span> the SmartFramework FS Operations <span style="color:#83B953;">Tests PASSED on PHP</span><hr></h2><span style="font-size:14px;">' . Smart::nl_2_br(Smart::escape_html(implode("\n" . '* ', $tests) . "\n" . $end_tests)) . '</span>'); } else { $img_sign = 'lib/core/img/sign_error.png'; $img_check = 'lib/core/img/q_warning.png'; $text_main = Smart::escape_js('<span style="color:#FF5500;">An ERROR occured ... :: エラーが発生しました ...</span>'); $text_info = Smart::escape_js('<h2><span style="color:#FF5500;">A test FAILED</span> when testing FS Operations.<span style="color:#FF5500;"><hr>FAILED Test Details</span>:</h2><br><h3>' . Smart::escape_html($tests[Smart::array_size($tests) - 1]) . '</h3><br><span style="font-size:14px;"><pre>' . Smart::escape_html($err) . '</pre></span>'); } //end if else //-- //-- $html = <<<HTML <h1>SmartFramework LibFileSystem Tests: DONE ... [ Time: {$time} sec. ]</h1> <script type="text/javascript"> \tSmartJS_BrowserUtils.alert_Dialog( \t\t'<img src="{$img_sign}" align="right"><h1>{$text_main}</h1><hr><span style="color:#333333;"><img src="{$img_check}" align="right">{$text_info}<br>', \t\t'', \t\t'FileSystem Operations Test Suite for SmartFramework: PHP', \t\t'920', \t\t'480' \t); </script> HTML; //-- //-- return $html; //-- }
public function Run() { //-- sample page variable from Request (GET/POST) $some_var_from_request = $this->RequestVarGet('extra_text', 'default', 'string'); //-- //-- $module_area = $this->ControllerGetParam('module-area'); $the_lang = (string) $this->ConfigParamGet('regional.language-id'); $the_xlang = (string) $this->ConfigParamGet('regional.language-id'); // repeat this to check if caching works //-- if ($this->IfDebug()) { $this->SetDebugData('Module Area', $module_area); $this->SetDebugData('Module Path', $this->ControllerGetParam('module-path')); $this->SetDebugData('Module Name', $this->ControllerGetParam('module-name')); $this->SetDebugData('URL Script', $this->ControllerGetParam('url-script')); $this->SetDebugData('URL Path', $this->ControllerGetParam('url-path')); $this->SetDebugData('URL Address', $this->ControllerGetParam('url-addr')); $this->SetDebugData('URL Page', $this->ControllerGetParam('url-page')); $this->SetDebugData('Config / Language ID', $the_lang); } //end if //-- //-- if ($this->PageCacheisActive()) { //-- because the Request can modify the content, also the unique key must take in account variables that will vary the page config or page content vars $the_page_cache_key = 'samples-toolkit-' . $module_area . '__' . SmartHashCrypto::sha384((string) $some_var_from_request); //-- } //end if //-- //-- if ($this->PageCacheisActive()) { //-- $test_cache = $this->PageGetFromCache('cached-samples', $the_page_cache_key); //-- if (Smart::array_size($test_cache) > 0) { if (is_array($test_cache['configs']) && is_array($test_cache['vars'])) { // if valid cache (test as we exported both arrays ... so they must be the 2 arrays again) $this->PageViewSetCfgs((array) $test_cache['configs']); $this->PageViewSetVars((array) $test_cache['vars']); $this->PageViewAppendVar('main', "\n" . '<!-- Redis Cached Content Key: ' . Smart::escape_html($the_page_cache_key) . ' -->' . "\n"); // add a markup to the HTML to know was served from cache ... if ($this->IfDebug()) { $this->SetDebugData('Page Cache Info', 'Serving page from Persistent Cache: Redis (override PHP Execution). Page key is: ' . $the_page_cache_key); } // end if return; // the page was served from Cache (stop here) } //end if } //end if //-- } //end if //-- //=== if no cached, execute the code below ... //-- $this->PageViewSetCfg('template-path', 'default'); // set the template path (must be inside etc/templates/) $this->PageViewSetCfg('template-file', 'template.htm'); // set the template file //-- //-- $fcontent = SmartFileSystem::staticread('lib/framework/css/ux-toolkit-samples.html'); $arr_data = explode('<body>', $fcontent); $fcontent = (string) $arr_data[1]; $arr_data = explode('</body>', $fcontent); $fcontent = (string) $arr_data[0]; //-- //-- building a semantic URL $url_test_unit = Smart::url_add_params($this->ControllerGetParam('url-script'), array('page' => 'samples.testunit', 'tab' => 0)); // will generate: index.php?page=samples.testunit OR admin.php?page=samples.testunit $url_test_unit = Smart::url_make_semantic($url_test_unit); // convert the above to a pretty URL as: ?/page/samples.testunit (in this case index.php is ignored) OR admin.php?/page/samples.testunit //-- //-- building a regular URL $url_benchmark = Smart::url_add_params($this->ControllerGetParam('url-script'), array('page' => 'samples.benchmark.html')); $url_benchmark = Smart::url_make_semantic($url_benchmark); //-- //-- $translator_core = SmartTextTranslations::getTranslator('@core', 'messages'); //-- $translator_mod_samples = SmartTextTranslations::getTranslator('mod-samples', 'samples'); $txt_hello_world = $translator_mod_samples->text('hello-world'); unset($translator_mod_samples); // this is just an internal test, normally the translator should not be unset ... $translator_mod_samples = SmartTextTranslations::getTranslator('mod-samples', 'samples'); $txt_this_is_sf = $translator_mod_samples->text('this-is-smart-framework'); //-- //-- $this->PageViewSetVars(['title' => 'Toolkit Samples', 'main' => '<h1>This text should not be displayed, it was RESET !!!</h1>']); $this->PageViewResetVar('main'); // test reset $this->PageViewSetVar('main', SmartMarkersTemplating::render_template('<h1>' . '[####TXT-HELLO-WORLD####]</h1><div align="right"><b>[####DATE-TIME|html####] [[####TXT-OK####]]' . "\n" . '</b></div><br><a class="ux-button ux-button-special" href="http://sourceforge.net/projects/warp-cms/files/smart-framework/" target="_blank"><i class="fa fa-cloud-download"></i> Download Smart.Framework (latest stable releases)</a> <a class="ux-button ux-button-highlight" href="http://demo.unix-world.org/smart-framework.docs/" target="_blank"><i class="fa fa-book"></i> Documentation for the Smart.Framework</a><br>' . "\n" . '<br><a class="ux-button ux-button-primary" href="[####URL-TESTUNIT|html####]"><i class="fa fa-object-group"></i> Go to the Smart.Framework PHP/Javascript Test & Demo Suite</a> <a class="ux-button ux-button-secondary" href="[####URL-BENCHMARK|html####]"><i class="fa fa-line-chart"></i> Benchmark URL for Smart.Framework</a><br><br>', ['DATE-TIME' => date('Y-m-d H:i:s O'), 'TXT-OK' => $translator_core->text('ok'), 'TXT-HELLO-WORLD' => '<span title="LanguageID: ' . Smart::escape_html($the_xlang) . '" style="cursor:help;">' . '[' . Smart::escape_html($the_lang) . ']' . '</span>' . ' ' . $txt_hello_world . ', ' . $txt_this_is_sf . ' - a modern PHP / Javascript framework featuring MVC + Middlewares', 'URL-TESTUNIT' => $url_test_unit, 'URL-BENCHMARK' => $url_benchmark])); $this->PageViewAppendVar('main', '<hr><div style="color:#DDDDDD">' . Smart::escape_html('Unicode@String :: Smart スマート // Cloud Application Platform クラウドアプリケーションプラットフォーム :: áâãäåāăąÁÂÃÄÅĀĂĄ ćĉčçĆĈČÇ ďĎ èéêëēĕėěęÈÉÊËĒĔĖĚĘ ĝģĜĢ ĥħĤĦ ìíîïĩīĭȉȋįÌÍÎÏĨĪĬȈȊĮ ijĵIJĴ ķĶ ĺļľłĹĻĽŁ ñńņňÑŃŅŇ óôõöōŏőøœÒÓÔÕÖŌŎŐØŒ ŕŗřŔŖŘ șşšśŝßȘŞŠŚŜ țţťȚŢŤ ùúûüũūŭůűųÙÚÛÜŨŪŬŮŰŲ ŵŴ ẏỳŷÿýẎỲŶŸÝ źżžŹŻŽ') . '</div><hr><div align="right">[' . Smart::escape_html($some_var_from_request) . ']</div>'); $this->PageViewAppendVar('main', trim($fcontent)); //-- //== cache page (if redis - persistent cache is set in config) //-- if Redis is active this will cache the page for 1 hour ... if ($this->PageCacheisActive()) { //-- $this->PageSetInCache('cached-samples', $the_page_cache_key, array('configs' => $this->PageViewGetCfgs(), 'vars' => $this->PageViewGetVars()), 3600); //-- if ($this->IfDebug()) { $this->SetDebugData('Page Cache Info', 'Setting page in Persistent Cache: Redis (after PHP Execution). Page key is: ' . $the_page_cache_key); } //end if //-- } else { //-- if ($this->IfDebug()) { $this->SetDebugData('Page Cache Info', 'Persistent Cache (Redis) is not active. Serving Page from PHP Execution.'); } //end if //-- } //end if else //-- }
public static final function DownloadsHandler($encrypted_download_pack, $controller_key) { //-- $encrypted_download_pack = (string) $encrypted_download_pack; $controller_key = (string) $controller_key; //-- $client_signature = SmartUtils::get_visitor_signature(); //-- if ((string) SMART_APP_VISITOR_COOKIE == '') { Smart::log_info('File Download', 'Failed: 400 / Invalid Visitor Cookie' . ' on Client: ' . $client_signature); self::Raise400Error('ERROR: Invalid Visitor UUID. Cookies must be enabled to enable this feature !'); return ''; } //end if //-- $downloaded_file = ''; // init //-- $decoded_download_packet = (string) trim((string) SmartUtils::crypto_decrypt((string) $encrypted_download_pack, 'SmartFramework//DownloadLink' . SMART_FRAMEWORK_SECURITY_KEY)); //-- if ((string) $decoded_download_packet != '') { // if data is corrupted, decrypt checksum does not match, will return an empty string //-- if (SMART_FRAMEWORK_ADMIN_AREA === true) { // {{{SYNC-DWN-CTRL-PREFIX}}} $controller_key = (string) 'AdminArea/' . $controller_key; } else { $controller_key = (string) 'IndexArea/' . $controller_key; } //end if //-- {{{SYNC-DOWNLOAD-ENCRYPT-ARR}}} $arr_metadata = explode("\n", (string) $decoded_download_packet, 6); // only need first 5 parts //print_r($arr_metadata); // #PACKET-STRUCTURE# [we will have an array like below, according with the: SmartUtils::create_download_link()] // [TimedAccess]\n // [FilePath]\n // [AccessKey]\n // [UniqueKey]\n // [SFR.UA]\n // #END# //-- $crrtime = (string) trim((string) $arr_metadata[0]); $filepath = (string) trim((string) $arr_metadata[1]); $access_key = (string) trim((string) $arr_metadata[2]); $unique_key = (string) trim((string) $arr_metadata[3]); //-- unset($arr_metadata); //-- $timed_hours = 1; // default expire in 1 hour if (defined('SMART_FRAMEWORK_DOWNLOAD_EXPIRE')) { if ((int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE > 0) { if ((int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE <= 24) { // max is 24 hours (since download link is bind to unique browser signature + unique cookie ... make non-sense to keep more) $timed_hours = (int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE; } //end if } //end if } //end if //-- if ((int) $timed_hours > 0) { if ((int) $crrtime < (int) (time() - 60 * 60 * $timed_hours)) { Smart::log_info('File Download', 'Failed: 403 / Download expired at: ' . date('Y-m-d H:i:s O', (int) $crrtime) . ' for: ' . $filepath . ' on Client: ' . $client_signature); self::Raise403Error('ERROR: The Access Key for this Download is Expired !'); return ''; } //end if } //end if //-- if ((string) $access_key != (string) sha1('DownloadLink:' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . SMART_APP_VISITOR_COOKIE . ':' . $filepath . '^' . $controller_key)) { Smart::log_info('File Download', 'Failed: 403 / Invalid Access Key for: ' . $filepath . ' on Client: ' . $client_signature); self::Raise403Error('ERROR: Invalid Access Key for this Download !'); return ''; } //end if //-- if ((string) $unique_key != (string) SmartHashCrypto::sha1('Time=' . $crrtime . '#' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . $access_key . '-' . SmartUtils::unique_auth_client_private_key() . ':' . $filepath . '+' . $controller_key)) { Smart::log_info('File Download', 'Failed: 403 / Invalid Client (Unique) Key for: ' . $filepath . ' on Client: ' . $client_signature); self::Raise403Error('ERROR: Invalid Client Key to Access this Download !'); return ''; } //end if //-- if (SmartFileSysUtils::check_file_or_dir_name($filepath)) { //-- $skip_log = 'no'; // default log if (defined('SMART_FRAMEWORK_DOWNLOAD_SKIP_LOG')) { $skip_log = 'yes'; // do not log if accessed via admin area and user is authenticated } //end if //-- $tmp_file_ext = (string) strtolower(SmartFileSysUtils::get_file_extension_from_path($filepath)); // [OK] $tmp_file_name = (string) strtolower(SmartFileSysUtils::get_file_name_from_path($filepath)); //-- $tmp_eval = SmartFileSysUtils::mime_eval($tmp_file_name); $mime_type = (string) $tmp_eval[0]; $mime_disp = (string) $tmp_eval[1]; //-- the path must not start with / but this is tested below $tmp_arr_paths = (array) explode('/', $filepath, 2); // only need 1st part for testing //-- allow file downloads just from specific folders like wpub/ or wsys/ (this is a very important security fix to dissalow any downloads that are not in the specific folders) if (substr((string) $filepath, 0, 1) != '/' and strpos((string) SMART_FRAMEWORK_DOWNLOAD_FOLDERS, '<' . trim((string) $tmp_arr_paths[0]) . '>') !== false and stripos((string) SMART_FRAMEWORK_DENY_UPLOAD_EXTENSIONS, '<' . $tmp_file_ext . '>') === false) { //-- SmartFileSysUtils::raise_error_if_unsafe_path($filepath); // re-test finally //-- @clearstatcache(); //-- if (is_file($filepath)) { //-- if (!headers_sent()) { //-- $fp = @fopen($filepath, 'rb'); $fsize = @filesize($filepath); //-- if (!$fp || $fsize <= 0) { //-- Smart::log_info('File Download', 'Failed: 404 / The requested File is Empty or Not Readable: ' . $filepath . ' on Client: ' . $client_signature); self::Raise404Error('WARNING: The requested File is Empty or Not Readable !'); return ''; //-- } //end if //-- set max execution time to zero ini_set('max_execution_time', 0); // we can expect a long time if file is big, but this will be anyway overriden by the WebServer Timeout Directive //-- // cache headers are presumed to be sent by runtime before of this step //-- header('Content-Type: ' . $mime_type); header('Content-Disposition: ' . $mime_disp); header('Content-Length: ' . $fsize); //-- @fpassthru($fp); // output without reading all in memory //-- @fclose($fp); //-- } else { //-- Smart::log_info('File Download', 'Failed: 500 / Headers Already Sent: ' . $filepath . ' on Client: ' . $client_signature); self::Raise500Error('ERROR: Download Failed, Headers Already Sent !'); return ''; //-- } //end if else //-- if ((string) $skip_log != 'yes') { //-- $downloaded_file = (string) $filepath; // return the file name to be logged //-- } //end if //-- } else { //-- Smart::log_info('File Download', 'Failed: 404 / The requested File does not Exists: ' . $filepath . ' on Client: ' . $client_signature); self::Raise404Error('WARNING: The requested File for Download does not Exists !'); return ''; //-- } //end if else } else { //-- Smart::log_info('File Download', 'Failed: 403 / Access to this File is Denied: ' . $filepath . ' on Client: ' . $client_signature); self::Raise403Error('ERROR: Download Access to this File is Denied !'); return ''; //-- } //end if else //-- } else { //-- Smart::log_info('File Download', 'Failed: 400 / Unsafe File Path: ' . $filepath . ' on Client: ' . $client_signature); self::Raise400Error('ERROR: Unsafe Download File Path !'); return ''; //-- } //end if else //-- } else { //-- Smart::log_info('File Download', 'Failed: 400 / Invalid Data Packet' . ' on Client: ' . $client_signature); self::Raise400Error('ERROR: Invalid Download Data Packet !'); return ''; //-- } //end if else //-- return (string) $downloaded_file; //-- }
/** * Generate a PDF Document on the fly from a piece of HTML code. * * Notice: this is using a secured cache folder, unique per visitor ID * * @param STRING $y_html_content :: The HTML Code * @param ENUM $y_orientation :: Page Orientation: 'normal' | 'wide' * @param STRING $y_runtime_script :: The allowed Runtime Script to allow send credentials for sub-downloads. Ex: admin.php * @param STRING $y_runtime_url :: The allowed Runtime URL ended by '/' to allow send credentials for sub-downloads. Ex: http(s)://some-server/some_path/ ; normally this should be set in config to enforce https:// and a single URL only * @param BOOLEAN $y_allow_send_credentials :: Set to TRUE to allow or set to FALSE to dissalow sending the auth credentials for sub-downloads: in the case there are embedded pictures generated by admin.php which may need authentication before to work, the credentials need to be set automatically in this case * * @returns STRING :: The PDF Document Contents * */ public static function generate($y_html_content, $y_orientation = 'normal', $y_runtime_script = '', $y_runtime_url = '', $y_allow_send_credentials = false) { //-- $pdfdata = ''; //-- $htmldoc = self::is_active(); //-- if ((string) $htmldoc != '') { //-- if ((string) $y_orientation == 'wide') { $orientation = self::tag_page_wide(); } else { $orientation = self::tag_page_normal(); } //end if else //-- $tmp_prefix_dir = 'tmp/cache/pdf/'; $protect_file = $tmp_prefix_dir . '.htaccess'; $dir = $tmp_prefix_dir . SMART_FRAMEWORK_SESSION_PREFIX . '/'; // we use different for index / admin / @ //-- $uniquifier = SmartUtils::unique_auth_client_private_key() . SMART_APP_VISITOR_COOKIE; $the_dir = $dir . Smart::safe_varname(Smart::uuid_10_seq() . '_' . Smart::uuid_10_num() . '_' . SmartHashCrypto::sha1($uniquifier)) . '/'; //-- $tmp_uuid = Smart::uuid_45($uniquifier) . Smart::uuid_36($uniquifier); $file = $the_dir . '__document_' . SmartHashCrypto::sha256('@@PDF#File::Cache@@' . $tmp_uuid) . '.html'; $logfile = $the_dir . '__headers_' . SmartHashCrypto::sha256('@@PDF#File::Cache@@' . $tmp_uuid) . '.log'; //-- if (is_dir($the_dir)) { SmartFileSystem::dir_delete($the_dir); } //end if //-- if (!is_dir($the_dir)) { SmartFileSystem::dir_recursive_create($the_dir); } // end if //-- SmartFileSystem::write_if_not_exists($protect_file, trim(SMART_FRAMEWORK_HTACCESS_FORBIDDEN) . "\n", 'yes'); //-- process the code $y_html_content = (string) self::remove_between_tags((string) $y_html_content); $y_html_content = (string) self::safe_charset((string) $y_html_content); //-- extract images $htmlparser = new SmartHtmlParser((string) $y_html_content); $arr_imgs = $htmlparser->get_tags('img'); $htmlparser = ''; unset($htmlparser); //-- $chk_duplicates_arr = array(); //-- for ($i = 0; $i < Smart::array_size($arr_imgs); $i++) { //-- $tmp_img_src = trim((string) $arr_imgs[$i]['src']); //-- if (strlen($chk_duplicates_arr[$tmp_img_src]) <= 0) { //-- $tmp_url_img_src = ''; //-- if ((string) $y_runtime_script != '' and (string) $y_runtime_url != '') { // replace relative paths if (substr($tmp_img_src, 0, @strlen($y_runtime_script)) == (string) $y_runtime_script) { $tmp_url_img_src = (string) $y_runtime_url . $tmp_img_src; $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $tmp_url_img_src . '"', (string) $y_html_content); $tmp_img_src = (string) $tmp_url_img_src; } //end if } //end if //-- $tmp_img_ext = '.' . strtolower(SmartFileSysUtils::get_file_extension_from_path($tmp_img_src)); // [OK] $tmp_img_cache = 'pdf_img_' . SmartHashCrypto::sha256('@@PDF#File::Cache::IMG@@' . '#' . $i . '@' . $tmp_img_src . '//' . $tmp_uuid); //-- $tmp_arr = array(); //-- if (substr($tmp_img_src, 0, 7) == 'http://' or substr($tmp_img_src, 0, 8) == 'https://') { //-- $tmp_img_ext = ''; // we clear the extension as we don't know yet (we will get it from headers) $tmp_img_cache = 'pdf_url_img_' . SmartHashCrypto::sha256('@@PDF#File::Cache::URL::IMG@@' . '#' . $i . '@' . $tmp_img_src . '//' . $tmp_uuid); //-- } //end if //-- if ($y_allow_send_credentials === true) { $allow_set_credentials = 'yes'; } else { $allow_set_credentials = 'no'; } //end if else //-- $tmp_arr = SmartUtils::load_url_or_file($tmp_img_src, SMART_FRAMEWORK_NETSOCKET_TIMEOUT, 'GET', '', '', '', $allow_set_credentials); // [OK] :: allow set credentials //-- $tmp_img_ext = '.noextension'; $tmp_where_we_guess = ''; //-- $guess_arr = array(); //-- $guess_arr = SmartUtils::guess_image_extension_by_url_head($tmp_arr['headers']); $tmp_img_ext = (string) $guess_arr['extension']; $tmp_where_we_guess = (string) $guess_arr['where-was-detected']; $guess_arr = array(); if ((string) $tmp_img_ext == '') { $tmp_img_ext = SmartUtils::guess_image_extension_by_first_bytes(substr($tmp_arr['content'], 0, 256)); if ((string) $tmp_img_ext != '') { $tmp_where_we_guess = ' First Bytes ...'; } //end if } //end if //-- if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') { // if debug, append information to log SmartFileSystem::write($logfile, '####################' . "\n" . '#################### [FILE # ' . $i . ' = \'' . $tmp_img_src . '\']' . "\n\n" . '==== [MODE] :: ' . $tmp_arr['mode'] . "\n" . '==== [LOG] :: ' . "\n" . $tmp_arr['log'] . "\n" . '==== [HEADERS] ::' . "\n" . $tmp_arr['headers'] . "\n" . '########' . "\n" . '==== [GUESS EXTENSION] :: ' . $tmp_where_we_guess . "\n\n" . '###################' . "\n\n\n\n", 'a'); } //end if //-- if ((string) $tmp_arr['result'] == '1' and (string) $tmp_arr['code'] == '200') { //-- SmartFileSystem::write($the_dir . $tmp_img_cache . $tmp_img_ext, $tmp_arr['content']); //-- if empty, it may be a file if ((string) $tmp_img_ext == '' or (string) $tmp_img_ext == '.png' or (string) $tmp_img_ext == '.gif' or (string) $tmp_img_ext == '.jpg') { $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $tmp_img_cache . $tmp_img_ext . '"', (string) $y_html_content); } else { // we want to avoid html code to be loaded as image by mistakes of http browser class or servers $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $y_runtime_url . 'lib/framework/img/sign_warn.png"', (string) $y_html_content); } //end if else //-- } else { //-- $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $y_runtime_url . 'lib/framework/img/sign_error.png"', (string) $y_html_content); //-- } //end if //-- } //end if //-- $chk_duplicates_arr[$tmp_img_src] = 'processed'; //-- } //end for //-- $chk_duplicates_arr = array(); unset($chk_duplicates_arr); $arr_imgs = array(); unset($arr_imgs); //-- SmartFileSystem::write($file, $orientation . "\n" . $y_html_content); //-- if (is_file($file)) { //-- ob_start(); //-- @passthru($htmldoc . ' ' . self::pdf_options($file)); //-- $pdfdata = ob_get_clean(); //-- } else { //-- Smart::log_warning('ERROR: PDF Generator Failed to find the PDF Document: ' . $file . "\n" . $y_html_content); //-- } //end if else //-- cleanup if ((string) SMART_FRAMEWORK_DEBUG_MODE != 'yes') { // if not debug, cleanup the dir if (is_dir($the_dir)) { SmartFileSystem::dir_delete($the_dir); } //end if } //end if //-- } else { //-- Smart::log_notice('NOTICE: PDF Generator is INACTIVE ...'); //-- } //end if //-- return (string) $pdfdata; //-- }
/** * Start the Session on request * */ public static function start() { //===== //-- if (self::$started !== false) { return; // avoid start session if already started ... } //end if self::$started = true; // avoid run start again //-- //===== //-- $browser_os_ip_identification = SmartUtils::get_os_browser_ip(); // get browser and os identification //-- if ((string) $browser_os_ip_identification['bw'] == '@s#' or (string) $browser_os_ip_identification['bw'] == 'bot') { return; // in this case start no session for robots or the self browser (as they do not need to share info between many visits) ; if the self browser fail to identify will be at least identified as robot in the worst case } //end if //-- //===== //-- no log as the cookies can be dissalowed by the browser if ((string) SMART_APP_VISITOR_COOKIE == '') { return; // session need cookies } //end if //-- //===== //-- $sf_sess_mode = 'files'; $sf_sess_area = 'default-sess'; $sf_sess_ns = 'unknown'; $sf_sess_dir = 'tmp/sess'; //-- //===== if (!defined('SMART_FRAMEWORK_SESSION_PREFIX')) { Smart::log_warning('FATAL ERROR: Invalid Session Prefix :: SMART_FRAMEWORK_SESSION_PREFIX'); return; } //end if if (strlen(SMART_FRAMEWORK_SESSION_PREFIX) < 3 or strlen(SMART_FRAMEWORK_SESSION_PREFIX) > 9) { Smart::log_warning('WARNING: Session Prefix must have a length between 3 and 9 characters :: SMART_FRAMEWORK_SESSION_PREFIX'); return; } //end if if (!preg_match('/^[a-z\\-]+$/', (string) SMART_FRAMEWORK_SESSION_PREFIX)) { Smart::log_warning('WARNING: Session Prefix contains invalid characters :: SMART_FRAMEWORK_SESSION_PREFIX'); return; } //end if //-- if (!defined('SMART_FRAMEWORK_SESSION_NAME')) { Smart::log_warning('FATAL ERROR: Invalid Session Name :: SMART_FRAMEWORK_SESSION_NAME'); return; } //end if if (strlen(SMART_FRAMEWORK_SESSION_NAME) < 10 or strlen(SMART_FRAMEWORK_SESSION_NAME) > 25) { Smart::log_warning('WARNING: Session Name must have a length between 10 and 25 characters :: SMART_FRAMEWORK_SESSION_NAME'); return; } //end if if (!preg_match('/^[_A-Za-z0-9]+$/', (string) SMART_FRAMEWORK_SESSION_NAME)) { Smart::log_warning('WARNING: Session Name contains invalid characters :: SMART_FRAMEWORK_SESSION_NAME'); return; } //end if if (!SmartFrameworkSecurity::ValidateVariableName(strtolower(SMART_FRAMEWORK_SESSION_NAME))) { Smart::log_warning('WARNING: Session Name have an invalid value :: SMART_FRAMEWORK_SESSION_NAME'); return; } //end if //-- if (!defined('SMART_FRAMEWORK_SESSION_LIFETIME')) { Smart::log_warning('FATAL ERROR: Invalid Session GC Lifetime :: SMART_FRAMEWORK_SESSION_LIFETIME'); return; } //end if if (!is_int(SMART_FRAMEWORK_SESSION_LIFETIME)) { Smart::log_warning('Invalid INIT constant value for SMART_FRAMEWORK_SESSION_LIFETIME'); return; } //end if //-- if (!is_dir('tmp/sessions/')) { Smart::log_warning('FATAL ERROR: The Folder \'tmp/sessions/\' does not exists for use with Session !'); return; } //end if //-- $detected_session_mode = (string) ini_get('session.save_handler'); if ((string) $detected_session_mode === 'files') { if ((string) SMART_FRAMEWORK_SESSION_HANDLER !== 'files') { Smart::log_warning('FATAL ERROR: The value set for SMART_FRAMEWORK_SESSION_HANDLER is not set to: files / but the value found in session.save_handler is: ' . $detected_session_mode); return; } //end if } elseif ((string) $detected_session_mode === 'user') { if ((string) SMART_FRAMEWORK_SESSION_HANDLER === 'files') { Smart::log_warning('FATAL ERROR: The value set for SMART_FRAMEWORK_SESSION_HANDLER is set to: files / but the value found in session.save_handler is: ' . $detected_session_mode); return; } //end if } else { Smart::log_warning('FATAL ERROR: The value set for session.save_handler must be set to one of these modes: files or user'); return; } //end if //-- //===== //-- generate a the client private key based on it's IP and Browser $the_sess_client_uuid = SmartUtils::unique_client_private_key(); // SHA512 key to protect session data agains forgers //-- a very secure approach based on a chain, derived with a secret salt from the framework security key: // (1) an almost unique client private key lock based on it's IP and Browser // (2) an entropy derived from the client random cookie combined with the (1) // (3) a unique session name suffix derived from (1) and (2) // (4) a unique session id composed from (1) and (2) //-- thus the correlation between the random public client cookie, the session name suffix and the session id makes impossible to forge it as it locks to IP+Browser, using a public entropy cookie all encrypted with a secret key and derived and related, finally composed. $the_sess_client_lock = SmartHashCrypto::sha1(SMART_FRAMEWORK_SECURITY_KEY . '#' . $the_sess_client_uuid); $the_sess_client_entropy = SmartHashCrypto::sha1(SMART_APP_VISITOR_COOKIE . '*' . $the_sess_client_uuid . '%' . SMART_FRAMEWORK_SECURITY_KEY); $the_sess_nsuffix = SmartHashCrypto::sha1($the_sess_client_uuid . ':' . SMART_FRAMEWORK_SECURITY_KEY . '^' . $the_sess_client_entropy . '+' . $the_sess_client_lock . '$' . SMART_APP_VISITOR_COOKIE); $the_sess_id = $the_sess_client_entropy . '-' . $the_sess_client_lock; // session ID combines the secret client key based on it's IP / Browser and the Client Entropy Cookie //-- $sf_sess_area = Smart::safe_filename((string) SMART_FRAMEWORK_SESSION_PREFIX); $sf_sess_dpfx = substr($the_sess_client_entropy, 0, 1) . '-' . substr($the_sess_client_lock, 0, 1); // this come from hexa so 3 chars are 16x16x16=4096 dirs //-- if ((string) $browser_os_ip_identification['bw'] == '@s#') { $sf_sess_ns = '@sr-' . $sf_sess_dpfx; } elseif ((string) $browser_os_ip_identification['bw'] == 'bot') { $sf_sess_ns = 'r0-' . $sf_sess_dpfx; // we just need a short prefix for robots (on disk is costly for GC to keep separate folders, but of course, not so safe) } else { $sf_sess_ns = 'c-' . substr($browser_os_ip_identification['bw'], 0, 3) . '-' . $sf_sess_dpfx; // we just need a short prefix for clients (on disk is costly for GC to keep separate folders, but of course, not so safe) } //end if else $sf_sess_ns = Smart::safe_filename($sf_sess_ns); //-- by default set for files $sf_sess_mode = 'files'; $sf_sess_dir = 'tmp/sessions/' . $sf_sess_area . '/' . $sf_sess_ns . '/'; if ((string) $detected_session_mode === 'user') { if (class_exists('SmartCustomSession')) { if ((string) get_parent_class('SmartCustomSession') == 'SmartAbstractCustomSession') { $sf_sess_mode = 'user-custom'; $sf_sess_dir = 'tmp/sessions/' . $sf_sess_area . '/'; // here the NS is saved in DB so we do not need to complicate paths } else { Smart::log_warning('SESSION INIT ERROR: Invalid Custom Session Handler. The class SmartCustomSession must be extended from class SmartAbstractCustomSession ...'); return; } //end if else } else { Smart::log_warning('SESSION INIT ERROR: Custom Session Handler requires the class SmartCustomSession ...'); return; } //end if } //end if $sf_sess_dir = Smart::safe_pathname($sf_sess_dir); //-- if (!is_dir($sf_sess_dir)) { SmartFileSystem::dir_recursive_create($sf_sess_dir); } //end if SmartFileSystem::write_if_not_exists('tmp/sessions/' . $sf_sess_area . '/' . 'index.html', ''); //===== //-- @session_save_path($sf_sess_dir); @session_cache_limiter('nocache'); //-- $the_name_of_session = (string) SMART_FRAMEWORK_SESSION_NAME . '__Key_' . $the_sess_nsuffix; // protect session name data agains forgers //-- @session_id((string) $the_sess_id); @session_name((string) $the_name_of_session); //-- $tmp_exp_seconds = Smart::format_number_int(SMART_FRAMEWORK_SESSION_LIFETIME, '+'); if ($tmp_exp_seconds > 0) { @session_set_cookie_params((int) $tmp_exp_seconds, '/'); // session cookie expire and the path } // end if //-- be sure that session_write_close() is executed at the end of script if script if die('') premature and before pgsql shutdown register in the case of DB sessions register_shutdown_function('session_write_close'); //-- handle custom session handler if ((string) $sf_sess_mode === 'user-custom') { //-- $sess_obj = new SmartCustomSession(); $sess_obj->sess_area = (string) $sf_sess_area; $sess_obj->sess_ns = (string) $sf_sess_ns; $sess_obj->sess_expire = (int) $tmp_exp_seconds; //-- session_set_save_handler(array($sess_obj, 'open'), array($sess_obj, 'close'), array($sess_obj, 'read'), array($sess_obj, 'write'), array($sess_obj, 'destroy'), array($sess_obj, 'gc')); //-- } //end if else //-- start session @session_start(); //-- if ((string) $_SESSION['SoftwareFramework_VERSION'] != (string) SMART_FRAMEWORK_VERSION or (string) $_SESSION['website_ID'] != (string) SMART_SOFTWARE_NAMESPACE or strlen($_SESSION['session_ID']) < 32) { //-- $_SESSION['SoftwareFramework_VERSION'] = (string) SMART_FRAMEWORK_VERSION; // software version $_SESSION['SoftwareFramework_SessionMode'] = (string) $sf_sess_mode; // session mode $_SESSION['website_ID'] = (string) SMART_SOFTWARE_NAMESPACE; // the website ID $_SESSION['uniqbrowser_ID'] = (string) $the_sess_client_uuid; // a true unique browser ID (this is a protection against sessionID forgers) $_SESSION['session_ID'] = (string) @session_id(); // read current session ID $_SESSION['session_STARTED'] = (string) date('Y-m-d H:i:s O'); // read current session ID //-- } //end if //-- if (!isset($_SESSION['visit_COUNTER'])) { $_SESSION['visit_COUNTER'] = 1; } else { $_SESSION['visit_COUNTER'] += 1; } //end if else //-- $_SESSION['SmartFramework__Browser__Identification__Data'] = (array) $browser_os_ip_identification; //-- if ((string) $_SESSION['uniqbrowser_ID'] != (string) $the_sess_client_uuid) { // we need at least a md5 session //-- log, then unset old session (these are not well tested ...) Smart::log_notice('Session Security Breakpoint :: Session-BrowserUniqueID = ' . $_SESSION['uniqbrowser_ID'] . "\n" . 'SessionSecurityUniqueID = ' . $the_sess_client_uuid . "\n" . 'Browser Ident = ' . $browser_os_ip_identification['bw'] . "\n" . 'Cookies = ' . print_r($_COOKIE, 1) . "\n" . 'SessID = ' . $_SESSION['session_ID'] . "\n" . 'ClientIP = ' . SmartUtils::get_ip_client() . ' @ ' . $_SERVER['REMOTE_ADDR'] . "\n" . 'UserAgent = ' . $_SERVER['HTTP_USER_AGENT']); $_SESSION = array(); // reset it //-- unset the cookie (from this below is tested) @setcookie($the_name_of_session, 'EXPIRED', 1, '/'); //-- stop execution with message Smart::raise_error('SESSION // SECURITY BREAK POINT: Possible Session Forgery Detected ...', 'SESSION // SECURITY BREAK POINT: Possible Session Forgery Detected ! Please refresh the page ... A new session will be assigned ! If you are not trying to forge another user\' session this situation can occur also if you are behind a proxy and some of your navigation parameters has been changed ! If this problem persist try to restart your browser or use other browser. If still persist, contact the website administrator'); die(''); // just in case return; // or is better to silent discard it ? //-- } //end if //-- self::$active = time(); // successfuly started //-- }
public static function get_visitor_tracking_uid() { //-- return (string) SmartHashCrypto::sha1('>' . SMART_SOFTWARE_NAMESPACE . '[' . SMART_FRAMEWORK_SECURITY_KEY . ']' . self::client_ident_private_key() . '>' . SMART_APP_VISITOR_COOKIE); //-- }
private function _hash($string) { // force use sha1() encryption (unixman) //$result = sha1($string); //$out =''; // Convert hexadecimal hash value to binary string //for($c=0;$c<strlen($result);$c+=2) { // $out .= chr(hexdec($result[$c].$result[$c+1])); //} //end for //return $out; switch ((string) $this->mode) { // enhancement by unixman case 'md5': $result = SmartHashCrypto::md5($string); break; case 'sha1': $result = SmartHashCrypto::sha1($string); break; case 'sha256': $result = SmartHashCrypto::sha256($string); break; case 'sha384': $result = SmartHashCrypto::sha384($string); break; case 'sha512': $result = SmartHashCrypto::sha512($string); break; default: Smart::log_warning('ERROR: Invalid mode for: SmartCryptoCipherHash / _hash: ' . $this->mode . ' ; Using sha1()'); $result = sha1($string); } //end switch return (string) @hex2bin((string) $result); // convert hexadecimal hash value to binary string }