public function __construct($y_font_size = '9pt')
    {
        //--
        if (!class_exists('SmartZipArchive')) {
            Smart::raise_error('The ODS Exporter (SmartExportToOpenOffice) requires the class: SmartZipArchive which could not be found !', 'Export To OpenOffice cannot find Zip Archive Class !');
            die('');
            return;
        }
        //end if
        //--
        //--
        $this->font_size = (string) $y_font_size;
        //--
        $this->mime_ods = 'application/vnd.oasis.opendocument.spreadsheet';
        //--
        $this->open_document_ns = '' . 'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" ' . 'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" ' . 'xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" ' . 'xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" ' . 'xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" ' . '';
        //--
        $this->open_document_styles = '
		<office:automatic-styles>
			<style:style style:name="co1" style:family="table-column">
				<style:table-column-properties fo:break-before="auto" style:use-optimal-column-width="true"/>
			</style:style>
			<style:style style:name="ro1" style:family="table-row">
				<style:table-row-properties fo:break-before="auto" style:use-optimal-row-height="true"/>
			</style:style>
			<style:style style:name="ta1" style:family="table" style:master-page-name="Default">
				<style:table-properties table:display="true" style:writing-mode="lr-tb"/>
			</style:style>
			<style:style style:name="he1" style:family="table-cell" style:use-optimal-column-width="true" style:parent-style-name="Default">
				<style:table-cell-properties fo:background-color="#AECF00"/>
				<style:text-properties style:font-name="Tahoma" fo:font-size="' . $this->font_size . '" fo:font-weight="bold" style:font-size-asian="' . $this->font_size . '" style:font-weight-asian="bold" style:font-size-complex="' . $this->font_size . '" style:font-weight-complex="bold"/>
			</style:style>
			<style:style style:name="he2" style:family="table-cell" style:use-optimal-column-width="true" style:parent-style-name="Default">
				<style:table-cell-properties fo:background-color="#FFFFCC"/>
				<style:text-properties style:font-name="Tahoma" fo:font-size="' . $this->font_size . '" fo:font-weight="bold" style:font-size-asian="' . $this->font_size . '" style:font-weight-asian="bold" style:font-size-complex="' . $this->font_size . '" style:font-weight-complex="bold"/>
			</style:style>
			<style:style style:name="he3" style:family="table-cell" style:use-optimal-column-width="true" style:parent-style-name="Default">
				<style:table-cell-properties fo:background-color="#FF9900"/>
				<style:text-properties style:font-name="Tahoma" fo:font-size="' . $this->font_size . '" fo:font-weight="bold" style:font-size-asian="' . $this->font_size . '" style:font-weight-asian="bold" style:font-size-complex="' . $this->font_size . '" style:font-weight-complex="bold"/>
			</style:style>
			<style:style style:name="ce1" style:family="table-cell" style:use-optimal-column-width="true" style:parent-style-name="Default">
				<style:table-cell-properties fo:background-color="#ECEAFF"/>
				<style:text-properties style:font-name="Tahoma" fo:font-size="' . $this->font_size . '" fo:font-weight="bold" style:font-size-asian="' . $this->font_size . '" style:font-weight-asian="bold" style:font-size-complex="' . $this->font_size . '" style:font-weight-complex="bold"/>
			</style:style>
			<style:style style:name="ce2" style:family="table-cell" style:use-optimal-column-width="true" style:parent-style-name="Default">
				<style:text-properties style:font-name="Tahoma" fo:font-size="' . $this->font_size . '" style:font-size-asian="' . $this->font_size . '" style:font-size-complex="' . $this->font_size . '"/>
			</style:style>
			<style:style style:name="ce3" style:family="table-cell" style:use-optimal-column-width="true" style:parent-style-name="Default">
				<style:table-cell-properties fo:background-color="#ECECEC"/>
				<style:text-properties style:font-name="Tahoma" fo:font-size="' . $this->font_size . '" fo:font-weight="bold" style:font-size-asian="' . $this->font_size . '" style:font-weight-asian="bold" style:font-size-complex="' . $this->font_size . '" style:font-weight-complex="bold"/>
			</style:style>
		</office:automatic-styles>
	';
        //--
    }
Пример #2
0
 private static function dir_recursive_private_copy($dirsource, $dirdest, $protected_dirsource = '', $protected_dirdest = '')
 {
     //--
     $dirsource = (string) $dirsource;
     $dirdest = (string) $dirdest;
     $protected_dirsource = (string) $protected_dirsource;
     $protected_dirdest = (string) $protected_dirdest;
     //--
     if (strlen($dirsource) <= 0) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Source Dir Name is Empty !');
         return 0;
         // empty source dir
     }
     //end if
     if (strlen($dirdest) <= 0) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Destination Dir Name is Empty !');
         return 0;
         // empty destination dir
     }
     //end if
     //--
     @clearstatcache();
     //--
     if (strlen($protected_dirsource) <= 0) {
         $protected_dirsource = (string) $dirsource;
         // 1st time
     }
     //end if
     if (strlen($protected_dirdest) <= 0) {
         if (self::file_or_link_exists($dirdest)) {
             Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Destination Dir exists: S=' . $destination);
             return 0;
         }
         //end if else
         $protected_dirdest = (string) $dirdest;
         // 1st time
     }
     //end if
     //-- add trailing slash
     $dirsource = SmartFileSysUtils::add_dir_last_slash($dirsource);
     $dirdest = SmartFileSysUtils::add_dir_last_slash($dirdest);
     //-- checks (must be after adding trailing slashes)
     SmartFileSysUtils::raise_error_if_unsafe_path($dirsource);
     SmartFileSysUtils::raise_error_if_unsafe_path($dirdest);
     SmartFileSysUtils::raise_error_if_unsafe_path($protected_dirsource);
     SmartFileSysUtils::raise_error_if_unsafe_path($protected_dirdest);
     //-- protect against infinite loop if the source and destination are the same or destination contained in source
     if ((string) $dirdest == (string) $dirsource) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Source Dir is the same as Destination Dir: S&D=' . $dirdest);
         return 0;
     }
     //end if
     if ((string) $dirdest == (string) SmartFileSysUtils::add_dir_last_slash(Smart::dir_name($dirsource))) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Destination Dir is the same as Source Parent Dir: S=' . $dirsource . ' ; D=' . $dirdest);
         return 0;
     }
     //end if
     if ((string) substr($dirdest, 0, strlen($dirsource)) == (string) $dirsource) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Destination Dir is inside the Source Dir: S=' . $dirsource . ' ; D=' . $dirdest);
         return 0;
     }
     //end if
     if ((string) substr($protected_dirdest, 0, strlen($protected_dirsource)) == (string) $protected_dirsource) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Original Destination Dir is inside the Original Source Dir: S*=' . $protected_dirsource . ' ; D*=' . $protected_dirdest);
         return 0;
     }
     //end if
     //-- protect against infinite loop (this can happen with loop sym-links)
     if ((string) $dirsource == (string) $protected_dirdest) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Source Dir is the same as Previous Step Source Dir (Loop Detected): S=' . $dirsource . ' ; S*=' . $protected_dirdest);
         return 0;
     }
     //end if
     //--
     if (!SmartFileSysUtils::check_file_or_dir_name($dirsource)) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Source Dir Name is Invalid: S=' . $dirsource);
         return 0;
     }
     //end if
     if (!SmartFileSysUtils::check_file_or_dir_name($dirdest)) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Destination Dir Name is Invalid: D=' . $dirdest);
         return 0;
     }
     //end if
     //--
     if (!is_dir($dirsource)) {
         Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Source Dir Name is not a Directory or does not exists: S=' . $dirsource);
         return 0;
     }
     //end if else
     //--
     if (self::file_or_link_exists($dirdest)) {
         if (!is_dir($dirdest)) {
             Smart::log_warning('SmartFramework // FileSystem / Copy Dir: The Destination Dir appear to be a file: D=' . $dirdest);
             return 0;
         }
         //end if
     } else {
         if (self::dir_recursive_create($dirdest) !== 1) {
             Smart::log_warning('SmartFramework // FileSystem / Copy Dir: Could Not Recursively Create the Destination: D=' . $dirdest);
             return 0;
         }
         //end if
     }
     //end if else
     //--
     $out = 1;
     // default is ok
     //--
     if ($handle = opendir($dirsource)) {
         //--
         while (false !== ($file = readdir($handle))) {
             //--
             if ((string) $file != '.' and (string) $file != '..') {
                 //--
                 $tmp_path = $dirsource . $file;
                 $tmp_dest = $dirdest . $file;
                 //--
                 SmartFileSysUtils::raise_error_if_unsafe_path($tmp_path);
                 SmartFileSysUtils::raise_error_if_unsafe_path($tmp_dest);
                 //--
                 if (self::file_or_link_exists($tmp_path)) {
                     //--
                     if (is_link($tmp_path)) {
                         // link
                         //--
                         $tmp_readlink = self::link_get_origin($tmp_path);
                         if (!is_dir($tmp_readlink)) {
                             if ((string) self::lock_file_check(self::lock_file_name($tmp_readlink)) == '1') {
                                 Smart::raise_error('SmartFramework // FileSystem / Copy Dir: Link is Locked (Read-Link Source): ' . $tmp_readlink, 'ERROR: FS :: A Link is still LOCKED while trying to COPY [READLINK-SOURCE] ... Please Try Again in few seconds as the Server is too Busy ...!');
                                 die('');
                                 // just in case
                                 return 0;
                             }
                             //end if
                             if ((string) self::lock_file_check(self::lock_file_name($tmp_path)) == '1') {
                                 Smart::raise_error('SmartFramework // FileSystem / Copy Dir: Link is Locked (Source): ' . $tmp_path, 'ERROR: FS :: A Link is still LOCKED while trying to COPY [SOURCE] ... Please Try Again in few seconds as the Server is too Busy ...!');
                                 die('');
                                 // just in case
                                 return 0;
                             }
                             //end if
                         }
                         //end if
                         //--
                         if ((string) self::lock_file_check(self::lock_file_name($tmp_dest)) == '1') {
                             Smart::raise_error('SmartFramework // FileSystem / Copy Dir: Link is Locked (Destination): ' . $tmp_dest, 'ERROR: FS :: A Link is still LOCKED while trying to COPY [DESTINATION] ... Please Try Again in few seconds as the Server is too Busy ...!');
                             die('');
                             // just in case
                             return 0;
                         }
                         //end if
                         //--
                         self::delete($tmp_dest);
                         if (self::file_or_link_exists($tmp_dest)) {
                             Smart::log_warning('LibFileSys // RecursiveDirCopy // Destination link still exists: ' . $tmp_dest);
                         }
                         //end if
                         //--
                         if (self::link_create($tmp_readlink, $tmp_dest) !== 1) {
                             Smart::log_warning('LibFileSys // RecursiveDirCopy // Failed to copy a Link: ' . $tmp_path);
                             return 0;
                         }
                         //end if else
                         //--
                     } elseif (is_file($tmp_path)) {
                         // file
                         //--
                         if ((string) self::lock_file_check(self::lock_file_name($tmp_path)) == '1') {
                             Smart::raise_error('SmartFramework // FileSystem / Copy Dir: File is Locked (Source): ' . $tmp_path, 'ERROR: FS :: A File is still LOCKED while trying to COPY [SOURCE] ... Please Try Again in few seconds as the Server is too Busy ...!');
                             die('');
                             // just in case
                             return 0;
                         }
                         //end if
                         //--
                         if ((string) self::lock_file_check(self::lock_file_name($tmp_dest)) == '1') {
                             Smart::raise_error('SmartFramework // FileSystem / Copy Dir: File is Locked (Destination): ' . $tmp_dest, 'ERROR: FS :: A File is still LOCKED while trying to COPY [DESTINATION] ... Please Try Again in few seconds as the Server is too Busy ...!');
                             die('');
                             // just in case
                             return 0;
                         }
                         //end if
                         //--
                         self::delete($tmp_dest);
                         if (self::file_or_link_exists($tmp_dest)) {
                             Smart::log_warning('LibFileSys // RecursiveDirCopy // Destination file still exists: ' . $tmp_dest);
                         }
                         //end if
                         //--
                         if (self::copy($tmp_path, $tmp_dest) !== 1) {
                             Smart::log_warning('LibFileSys // RecursiveDirCopy // Failed to copy a File: ' . $tmp_path);
                             return 0;
                         }
                         //end if else
                         //--
                     } elseif (is_dir($tmp_path)) {
                         // dir
                         //--
                         if (self::dir_recursive_private_copy($tmp_path, $tmp_dest, $protected_dirsource, $protected_dirdest) !== 1) {
                             Smart::log_warning('LibFileSys // RecursiveDirCopy // Failed on Dir: ' . $tmp_path);
                             return 0;
                         }
                         //end if
                         //--
                     } else {
                         //--
                         Smart::log_warning('LibFileSys // RecursiveDirCopy // Invalid Type: ' . $tmp_path);
                         return 0;
                         //--
                     }
                     //end if else
                     //--
                 } elseif (is_link($tmp_path)) {
                     // broken link (we still copy it)
                     //--
                     self::delete($tmp_dest);
                     if (self::file_or_link_exists($tmp_dest)) {
                         Smart::log_warning('LibFileSys // RecursiveDirCopy // Destination Link still exists: ' . $tmp_dest);
                     }
                     //end if
                     //--
                     if (self::link_create(self::link_get_origin($tmp_path), $tmp_dest) !== 1) {
                         Smart::log_warning('LibFileSys // RecursiveDirCopy // Failed to copy a Link: ' . $tmp_path);
                         return 0;
                     }
                     //end if else
                     //--
                 } else {
                     //--
                     Smart::log_warning('LibFileSys // RecursiveDirCopy // File does not exists or is not accessible: ' . $tmp_path);
                     return 0;
                     //--
                 }
                 //end if
                 //--
             }
             //end if
             //--
         }
         //end while
         //--
         @closedir($handle);
         //--
     } else {
         //--
         $out = 0;
         //--
     }
     //end if else
     //--
     return $out;
     //--
 }
Пример #3
0
 /**
  * Displays the SQLite Errors and HALT EXECUTION (This have to be a FATAL ERROR as it occur when a FATAL SQLite ERROR happens or when a Query Syntax is malformed)
  * PRIVATE
  *
  * @return :: HALT EXECUTION WITH ERROR MESSAGE
  *
  */
 private static function error($db, $y_area, $y_error_message, $y_query, $y_params_or_title, $y_warning = '')
 {
     //--
     $def_warn = 'Execution Halted !';
     $y_warning = (string) trim((string) $y_warning);
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         $width = 750;
         $the_area = (string) $y_area;
         if ((string) $y_warning == '') {
             $y_warning = (string) $def_warn;
         }
         //end if
         $the_error_message = 'Operation FAILED: ' . $def_warn . "\n" . $y_error_message;
         if (is_array($y_params_or_title)) {
             $the_params = '*** Params ***' . "\n" . print_r($y_params_or_title, 1);
         } elseif ((string) $y_params_or_title != '') {
             $the_params = '[ Reference Title ]: ' . $y_params_or_title;
         } else {
             $the_params = '- No Params or Reference Title -';
         }
         //end if
         $the_query_info = (string) trim((string) $y_query);
         if ((string) $the_query_info == '') {
             $the_query_info = '-';
             // query cannot e empty in this case (templating enforcement)
         }
         //end if
     } else {
         $width = 550;
         $the_area = '';
         $the_error_message = 'Operation FAILED: ' . $def_warn;
         $the_params = '';
         $the_query_info = '';
         // do not display query if not in debug mode ... this a security issue if displayed to public ;)
     }
     //end if else
     //--
     $out = SmartComponents::db_error_message('SQLite Client', 'SQLite', 'Embedded', 'SQL/DB', 'lib/core/img/db/sqlite_logo.png', $width, $the_area, $the_error_message, $the_params, $the_query_info);
     //--
     if (!$db instanceof SQLite3) {
         $the_conn = (string) $db;
     } else {
         $the_conn = (string) self::get_connection_id($db);
     }
     //end if else
     //--
     Smart::raise_error('#SQLITE-DB@' . $the_conn . '# :: Q# // SQLite Client :: ERROR :: ' . $y_area . "\n" . '*** Error-Message: ' . $y_error_message . "\n" . '*** Params / Title:' . "\n" . print_r($y_params_or_title, 1) . "\n" . '*** Query:' . "\n" . $y_query, $out);
     die('');
     // just in case
     //--
 }
 private static function check_gd_truecolor()
 {
     //--
     if (!function_exists('imagecreatetruecolor')) {
         Smart::raise_error('[ERROR] :: SmartGdImageProcess LIB :: PHP-GD extension (TrueColor) is required.', 'A required component is missing ... See error log for more details');
         die('Missing GD True Color');
     }
     //end if
     //--
 }
 /**
  * Displays the Solr Errors and HALT EXECUTION (This have to be a FATAL ERROR as it occur when a FATAL Solr ERROR happens or when a Data Query fails)
  * PRIVATE
  *
  * @param STRING $y_area :: The Area
  * @param STRING $y_error_message :: The Error Message to Display
  * @param STRING $y_query :: The query
  * @param STRING $y_warning :: The Warning Title
  *
  * @return :: HALT EXECUTION WITH ERROR MESSAGE
  *
  */
 private function error($y_area, $y_error_message, $y_query = '', $y_warning = '')
 {
     //--
     $def_warn = 'Execution Halted !';
     $y_warning = (string) trim((string) $y_warning);
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         $width = 750;
         $the_area = (string) $y_area;
         if ((string) $y_warning == '') {
             $y_warning = (string) $def_warn;
         }
         //end if
         $the_error_message = 'Operation FAILED: ' . $def_warn . "\n" . $y_error_message;
         $the_params = '- Mode: ' . $this->mode . ' -';
         $the_query_info = (string) $y_query;
         if ((string) $the_query_info == '') {
             $the_query_info = '-';
             // query cannot e empty in this case (templating enforcement)
         }
         //end if
     } else {
         $width = 550;
         $the_area = '';
         $the_error_message = 'Operation FAILED: ' . $def_warn;
         $the_params = '';
         $the_query_info = '';
         // do not display query if not in debug mode ... this a security issue if displayed to public ;)
     }
     //end if else
     //--
     $out = SmartComponents::db_error_message('Solr Client', 'Apache-Solr', 'FTS', 'Server', 'modules/smart-extra-libs/img/solr_logo_trans.png', $width, $the_area, $the_error_message, $the_params, $the_query_info);
     //--
     Smart::raise_error('#SOLR-DB# :: Q# // Solr :: ERROR :: ' . $y_area . "\n" . '*** Error-Message: ' . $y_error_message . "\n" . '*** Stetement:' . "\n" . $y_query, $out);
     die('');
     // just in case
     //--
 }
 /**
  * Displays the MySQL Errors and HALT EXECUTION (This have to be a FATAL ERROR as it occur when a FATAL MySQLi ERROR happens or when a Query Syntax is malformed)
  * PRIVATE
  *
  * @return :: HALT EXECUTION WITH ERROR MESSAGE
  *
  */
 private static function error($y_connection_id, $y_area, $y_error_message, $y_query, $y_params_or_title, $y_warning = '')
 {
     //--
     $err_log = $y_area . "\n" . '*** Error-Message: ' . $y_error_message . "\n" . '*** Params / Title:' . "\n" . print_r($y_params_or_title, 1) . "\n" . '*** Query:' . "\n" . $y_query;
     //--
     if (defined('SMART_SOFTWARE_SQLDB_FATAL_ERR') and SMART_SOFTWARE_SQLDB_FATAL_ERR === false) {
         Smart::log_warning('#MYSQL-DB@' . $y_connection_id . '# :: Q# // MySQL :: WARNING :: ' . $err_log);
         throw new Exception('#MYSQL-DB@' . $y_connection_id . '# :: Q# // MySQL :: EXCEPTION :: ' . $y_area . "\n" . $y_error_message);
         return;
     }
     //end if
     //--
     $def_warn = 'Execution Halted !';
     $y_warning = (string) trim((string) $y_warning);
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         $width = 750;
         $the_area = (string) $y_area;
         if ((string) $y_warning == '') {
             $y_warning = (string) $def_warn;
         }
         //end if
         $the_error_message = 'Operation FAILED: ' . $def_warn . "\n" . $y_error_message;
         if (is_array($y_params_or_title)) {
             $the_params = '*** Params ***' . "\n" . print_r($y_params_or_title, 1);
         } elseif ((string) $y_params_or_title != '') {
             $the_params = '[ Reference Title ]: ' . $y_params_or_title;
         } else {
             $the_params = '- No Params or Reference Title -';
         }
         //end if
         $the_query_info = (string) trim((string) $y_query);
         if ((string) $the_query_info == '') {
             $the_query_info = '-';
             // query cannot e empty in this case (templating enforcement)
         }
         //end if
     } else {
         $width = 550;
         $the_area = '';
         $the_error_message = 'Operation FAILED: ' . $def_warn;
         $the_params = '';
         $the_query_info = '';
         // do not display query if not in debug mode ... this a security issue if displayed to public ;)
     }
     //end if else
     //--
     $out = SmartComponents::db_error_message('MySQLi Client', 'MySQL', 'SQL/DB', 'Server', 'modules/smart-extra-libs/img/mysql_logo_trans.png', $width, $the_area, $the_error_message, $the_params, $the_query_info);
     //--
     Smart::raise_error('#MYSQL-DB@' . $y_connection_id . '# :: Q# // MySQL :: ERROR :: ' . $err_log, $out);
     die('');
     // just in case
     //--
 }
 public static function test_crypto()
 {
     //--
     $time = microtime(true);
     //--
     //--
     $unicode_text = "Unicode String [ " . time() . " ]: @ Smart スマート // Cloud Application Platform クラウドアプリケーションプラットフォーム '" . implode('', array_keys(SmartUnicode::accented_chars())) . " \" <p></p>\n\t? & * ^ \$ @ ! ` ~ % () [] {} | \\ / + - _ : ; , . #'" . microtime() . '#';
     //--
     //--
     $b64enc = base64_encode($unicode_text);
     $b64dec = base64_decode($b64enc);
     //--
     //--
     $bin2hex = strtoupper(bin2hex((string) $unicode_text));
     $hex2bin = hex2bin(strtolower(trim((string) $bin2hex)));
     //--
     //--
     $hkey = 'TestUnit // This is a test key for Crypto Cipher ...' . time() . $unicode_text;
     //--
     $he_enc = SmartUtils::crypto_encrypt($unicode_text, $hkey);
     $he_dec = SmartUtils::crypto_decrypt($he_enc, $hkey);
     //--
     if ((string) $he_dec != (string) $unicode_text or sha1($he_dec) != sha1($unicode_text)) {
         Smart::raise_error('TestUnit FAILED in ' . __FUNCTION__ . '() :: Crypto Cipher test', 'TestUnit: Crypto Cipher test failed ...');
         return;
     }
     //end if
     //--
     //--
     $bf_key = SmartHashCrypto::sha512('TestUnit // This is a test key for Blowfish ...' . time() . $unicode_text);
     $bf_enc = SmartUtils::crypto_blowfish_encrypt($unicode_text, $bf_key);
     $bf_dec = SmartUtils::crypto_blowfish_decrypt($bf_enc, $bf_key);
     if ((string) $bf_dec != (string) $unicode_text or sha1($bf_dec) != sha1($unicode_text)) {
         Smart::raise_error('TestUnit FAILED in ' . __FUNCTION__ . '() :: Crypto Blowfish test', 'TestUnit: Blowfish test failed ...');
         return;
     }
     //end if
     //--
     //--
     $arch_lzs = SmartArchiverLZS::compressToBase64($unicode_text);
     $unarch_lzs = SmartArchiverLZS::decompressFromBase64($arch_lzs);
     if ((string) $unarch_lzs != (string) $unicode_text or sha1($unarch_lzs) != sha1($unicode_text)) {
         Smart::raise_error('TestUnit FAILED in ' . __FUNCTION__ . '() :: Crypto Arch-LZS test', 'TestUnit: Arch-LZS test failed ...');
         return;
     }
     //end if
     //--
     //--
     $arch_bf_lzs = SmartArchiverLZS::compressToBase64($bf_enc);
     $unarch_bf_lzs = SmartArchiverLZS::decompressFromBase64($arch_bf_lzs);
     if ((string) $unarch_bf_lzs != (string) $bf_enc or sha1($unarch_bf_lzs) != sha1($bf_enc)) {
         Smart::raise_error('TestUnit FAILED in ' . __FUNCTION__ . '() :: Crypto Blowfish-Arch-LZS test', 'TestUnit: Blowfish-Arch-LZS test failed ...');
         return;
     }
     //end if
     //--
     //--
     $time = 'TOTAL TIME was: ' . (microtime(true) - $time);
     //--
     //--
     return SmartMarkersTemplating::render_file_template('lib/core/templates/testunit/crypto-test.inc.htm', array('EXE-TIME' => Smart::escape_html($time), 'UNICODE-TEXT' => Smart::escape_html($unicode_text), 'JS-ESCAPED' => $unicode_text, 'HASH-SHA512' => Smart::escape_html(SmartHashCrypto::sha512($unicode_text)), 'HASH-SHA1' => Smart::escape_html(sha1($unicode_text)), 'HASH-MD5' => Smart::escape_html(md5($unicode_text)), 'BASE64-ENCODED' => Smart::escape_html($b64enc), 'BASE64-DECODED' => Smart::escape_html($b64dec), 'BIN2HEX-ENCODED' => Smart::escape_html($bin2hex), 'HEX2BIN-DECODED' => Smart::escape_html($hex2bin), 'LZS-ARCHIVED' => Smart::escape_html($arch_lzs), 'LZS-UNARCHIVED' => Smart::escape_html($unarch_lzs), 'BLOWFISH-ENCRYPTED' => Smart::escape_html($bf_enc), 'BLOWFISH-LZS-ENCRYPTED' => Smart::escape_html($arch_bf_lzs), 'BLOWFISH-DECRYPTED' => Smart::escape_html($bf_dec), 'BLOWFISH-KEY' => Smart::escape_html($bf_key), 'BLOWFISH-OPTIONS' => Smart::escape_html(SmartCipherCrypto::crypto_options('blowfish')), 'HASHCRYPT-ENC' => Smart::escape_html($he_enc), 'HASHCRYPT-DEC' => Smart::escape_html($he_dec), 'HASHCRYPT-OPTIONS' => Smart::escape_html(SmartCipherCrypto::crypto_options('custom'))));
     //--
 }
Пример #8
0
 private static function read_mime_message($y_enc_msg_file, $y_ctrl_key, $y_process_mode, $y_show_headers, $y_title, $y_link, $y_target)
 {
     // $y_process_mode : 'default' | 'print' | 'data-full' | 'data-reply'
     // $y_show_headers : 'default' | 'subject' (just for mode: 'default' | 'print')
     //--
     $msg_decode_arr = (array) self::decode_mime_fileurl((string) $y_enc_msg_file, (string) $y_ctrl_key);
     //--
     if ((string) $msg_decode_arr['error'] != '') {
         Smart::raise_error('ERROR: MIME Parser // Mesage File Decode: ' . $msg_decode_arr['error'], 'ERROR: MIME Parser // Mesage File Decode // See error log for details ...');
         return '';
     }
     //end if
     //--
     //--
     $the_message_eml = (string) trim((string) $msg_decode_arr['message-file']);
     $the_part_id = (string) trim((string) $msg_decode_arr['message-part']);
     //--
     //--
     if ((string) $the_message_eml == '' or !is_file((string) $the_message_eml)) {
         Smart::raise_error('ERROR: MIME Parser // Message File EMPTY or NOT FOUND !: ' . $the_message_eml, 'ERROR: MIME Parser // Mesage File Decode // See error log for details ...');
         return '';
     }
     //end if
     //--
     if (substr((string) $the_message_eml, -4, 4) != '.eml') {
         Smart::raise_error('ERROR: MIME Parser // Message File Extension is not .eml !: ' . $the_message_eml, 'ERROR: MIME Parser // Mesage File Decode // See error log for details ...');
         return '';
     }
     //end if
     //--
     //--
     $out = '';
     // init
     $reply_text = array();
     // init
     //--
     //==
     //--
     $content = SmartFileSystem::read((string) $the_message_eml);
     $eml = new SmartMailerMimeDecode();
     $head = $eml->get_header(SmartUnicode::sub_str((string) $content, 0, 65535));
     // some messages fail with 8192 to decode ; a faster compromise would be 16384, but here we can use a higher value since is done once (text 65535)
     $msg = $eml->get_bodies((string) $content, (string) $the_part_id);
     unset($eml);
     unset($content);
     //--
     //==
     //--
     $reg_atts_num = 0;
     $reg_atts_list = '';
     // list separed by \n
     //--
     if (strlen($the_part_id) <= 0) {
         //-- display whole message
         $reg_is_part = 'no';
         $skip_part_processing = 'no';
         $skip_part_linking = 'no';
         //--
     } else {
         //-- display only a part of the message
         $reg_is_part = 'yes';
         $skip_part_processing = 'no';
         $skip_part_linking = 'yes';
         //--
         if (substr($the_part_id, 0, 4) == 'txt_') {
             //-- text part
             $tmp_part = $msg['texts'][$the_part_id];
             $msg = array();
             $msg['texts'][$the_part_id] = (array) $tmp_part;
             unset($tmp_part);
             //--
         } else {
             //-- att / cid part
             $skip_part_processing = 'yes';
             //--
             if (!is_array($msg['attachments'][$the_part_id])) {
                 // try to normalize name
                 $the_part_id = trim(str_replace(' ', '', $the_part_id));
             }
             //end if
             //--
             $out = (string) $msg['attachments'][$the_part_id]['content'];
             // DO NO MORE ADD ANYTHING TO $out ... downloading, there are no risk of code injection
             //--
         }
         //end if else
         //--
     }
     //end if else
     //--
     //--
     if ((string) $y_process_mode == 'print') {
         $skip_part_linking = 'yes';
         // skip links to other sub-parts like texts / attachments but not cids !
     } elseif ((string) $y_process_mode == 'data-reply') {
         $skip_part_linking = 'yes';
     }
     //end if
     //--
     //--
     if ((string) $skip_part_processing != 'yes') {
         //--
         if ((string) $y_title != '') {
             $out .= (string) $y_title;
             // expects '' or valid HTML
         }
         //end if
         //--
         $out .= '<!-- Smart.Framework // MIME MESSAGE HTML --><div align="left"><div id="mime_msg_box">';
         //--
         if (strlen($the_part_id) <= 0) {
             //--
             $priority_img = '';
             switch ((string) $head['priority']) {
                 case '1':
                     // high
                     $priority_img = '<img src="lib/core/plugins/img/email/priority_high.png" align="left" alt="High Priority" title="High Priority">';
                     break;
                 case '5':
                     // low
                     $priority_img = '<img src="lib/core/plugins/img/email/priority_low.png" align="left" alt="Low Priority" title="Low Priority">';
                     break;
                 case '3':
                     // medium
                 // medium
                 default:
                     $priority_img = '';
                     //$priority_img = '<img src="lib/core/plugins/img/email/priority_normal.png" align="left" alt="Normal Priority" title="Normal Priority">';
             }
             //end switch
             //--
             if ((string) $skip_part_linking != 'yes') {
                 // avoid display the print link when only a part is displayed
                 $out .= '<a href="' . self::mime_link($y_ctrl_key, $the_message_eml, $the_part_id, $y_link, $eval_arr[0], $eval_arr[1], 'print') . '" target="' . $y_target . '__mimepart" data-smart="open.modal">' . '<img align="right" src="lib/core/img/buttons/bttn_print.png">' . '</a>';
             }
             //end if
             //--
             switch ((string) $y_show_headers) {
                 case 'subject':
                     //--
                     if ((string) $head['subject'] != '[?]') {
                         $out .= '<h1><font size="4">' . Smart::escape_html($head['subject']) . '</font></h1><br>';
                     }
                     //end if
                     //--
                     break;
                 case 'default':
                 default:
                     //--
                     if ((string) $head['subject'] != '[?]') {
                         $out .= '<h1><font size="4">&nbsp;' . Smart::escape_html($head['subject']) . '</font>' . $priority_img . '</h1><hr>';
                     }
                     //end if
                     //--
                     if ((string) $head['date'] != '(?)') {
                         $out .= '<font size="3"><b>Date:</b> ' . Smart::escape_html(date('Y-m-d H:i:s O', @strtotime($head['date']))) . '</font><br>';
                     }
                     //end if
                     //--
                     $out .= '<font size="2"><b>From:</b> ' . Smart::escape_html($head['from_addr']) . ' &nbsp; <i>' . Smart::escape_html($head['from_name']) . '</i>' . '</font><br>';
                     $out .= '<font size="2"><b>To:</b> ' . Smart::escape_html($head['to_addr']) . ' &nbsp; <i>' . Smart::escape_html($head['to_name']) . '</i>' . '</font><br>';
                     //--
                     if (strlen($head['cc_addr']) > 0) {
                         $out .= '<font size="2"><b>Cc:</b> ';
                         if (SmartUnicode::str_contains($head['cc_addr'], ',')) {
                             $arr_cc_addr = (array) explode(',', (string) $head['cc_addr']);
                             $arr_cc_name = (array) explode(',', (string) $head['cc_name']);
                             $out .= '[@]';
                             for ($z = 0; $z < Smart::array_size($arr_cc_addr); $z++) {
                                 $out .= '<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . Smart::escape_html(trim($arr_cc_addr[$z])) . ' &nbsp; <i>' . Smart::escape_html(trim($arr_cc_name[$z])) . '</i>';
                             }
                             //end for
                         } else {
                             $out .= Smart::escape_html($head['cc_addr']) . ' &nbsp; <i>' . Smart::escape_html($head['cc_name']) . '</i>';
                         }
                         //end if else
                         $out .= '</font><br>';
                     }
                     //end if
                     //--
                     if (strlen($head['bcc_addr']) > 0) {
                         $out .= '<font size="2"><b>Bcc:</b> ';
                         $out .= Smart::escape_html($head['bcc_addr']) . ' &nbsp; <i>' . Smart::escape_html($head['bcc_name']) . '</i>';
                         $out .= '</font><br>';
                     }
                     //end if
                     //--
             }
             //end switch
             //-- print attachments
             if (is_array($msg['attachments'])) {
                 //--
                 $cnt = 0;
                 //--
                 $atts = '';
                 // atts with link
                 $xatts = '';
                 // atts without link
                 //--
                 $tmp_att_img = '<img src="lib/core/plugins/img/email/attachment.png">';
                 //--
                 foreach ($msg['attachments'] as $key => $val) {
                     //--
                     $tmp_arr = array();
                     $tmp_arr = (array) $val;
                     //--
                     if ((string) $tmp_arr['mode'] == 'normal') {
                         //--
                         $cnt += 1;
                         //--
                         $eval_arr = SmartFileSysUtils::mime_eval((string) $tmp_arr['filename']);
                         $tmp_att_name = Smart::escape_html((string) $tmp_arr['filename']);
                         $tmp_att_size = Smart::escape_html((string) SmartUtils::pretty_print_bytes((int) $tmp_arr['filesize'], 1));
                         //--
                         $reg_atts_num += 1;
                         $reg_atts_list .= str_replace(array("\r", "\n", "\t"), array('', '', ''), (string) $tmp_arr['filename']) . "\n";
                         //--
                         $atts .= '<div align="left"><table border="0" cellpadding="2" cellspacing="0" title="Attachment #' . $cnt . '"><tr><td>' . $tmp_att_img . '</td><td>&nbsp;</td><td><a href="' . self::mime_link($y_ctrl_key, $the_message_eml, $key, $y_link, $eval_arr[0], $eval_arr[1]) . '" target="' . $y_target . '__mimepart" data-smart="open.modal"><font size="1"><b>' . $tmp_att_name . '</b></font></a></td><td><font size="1"> &nbsp;<b><i>' . $tmp_att_size . '</i></b></font></td></tr></table></div>';
                         $xatts .= '<div align="left">' . $tmp_att_img . '&nbsp;&nbsp;<font size="1">' . $tmp_att_name . '&nbsp;&nbsp;<i>' . $tmp_att_size . '</i></font></div>';
                         //--
                     }
                     //end if
                     //--
                 }
                 //end foreach
                 //--
                 if ($cnt > 0) {
                     if ((string) $skip_part_linking == 'yes') {
                         // avoid displaying attachments links when only a part is displayed
                         $out .= '<hr><div align="left">' . $xatts . '</div>';
                     } else {
                         $out .= '<hr><div align="left">' . $atts . '</div>';
                     }
                     //end if
                 }
                 //end if
                 //--
                 $tmp_att_name = '';
                 $tmp_att_size = '';
                 //--
                 $atts = '';
                 $xatts = '';
                 //--
             }
             //end if
             //--
         } else {
             //--
             $out .= '<div align="right"><font size="1">' . Smart::escape_html($head['subject']) . ' // ' . 'MIME Part ID : <i>' . Smart::escape_html($the_part_id) . '</i></font></div>';
             //--
         }
         //end if
         //-- print text bodies
         $markup_multipart = 'This is a multi-part message in MIME format.';
         if (is_array($msg['texts'])) {
             //-- check similarity and prepare the HTML parts
             $buff = '';
             $buff_id = '';
             $xbuff = '';
             $xbuff_id = '';
             $skips = array();
             $numparts = 0;
             foreach ($msg['texts'] as $key => $val) {
                 //--
                 $numparts += 1;
                 //--
                 if ((string) $val['type'] == 'text') {
                     // assure we don't print other things
                     //--
                     if ((string) $val['mode'] == 'text/plain') {
                         // Plain TEXT
                         //-- sanitize text
                         $val['content'] = '<!-- MIMEREAD:PART:TEXT -->' . Smart::escape_html($val['content']);
                         $val['content'] = str_replace(array("\r\n", "\r", "\n"), array("\n", "\n", '<br>'), $val['content']);
                         $val['content'] = SmartParser::text_urls($val['content']);
                         //--
                         $msg['texts'][$key]['content'] = $val['content'];
                         // rewrite back
                         //-- assign buffer
                         $buff = SmartUnicode::sub_str($val['content'], 0, 16384);
                         $buff_id = $key;
                         //--
                         $percent_similar = 0;
                         if (strlen($the_part_id) <= 0) {
                             @similar_text($buff, $markup_multipart, $percent_similar);
                             if ($percent_similar >= 25) {
                                 // 25% at least similarity
                                 $skips[$buff_id] = $percent_similar;
                                 // skip this alternate html part ...
                             }
                             //end if
                         }
                         //end if
                         //--
                         // clean buffer
                         $xbuff = '';
                         $xbuff_id = '';
                         //--
                     } else {
                         // HTML Parts :: check similarity
                         //--
                         $val['content'] = '<!-- MIMEREAD:PART:HTML -->' . preg_replace("'" . '<\\?xml' . ".*?" . '>' . "'si", " ", (string) $val['content']);
                         // remove always fake "< ?" as "< ?xml" (fixed with /u modifier for unicode strings)
                         //--
                         if (SmartUnicode::str_contains($val['content'], '<' . '?') or SmartUnicode::str_contains($val['content'], '?' . '>') or SmartUnicode::str_contains($val['content'], '<' . '%') or SmartUnicode::str_contains($val['content'], '%' . '>')) {
                             //--
                             $val['content'] = @highlight_string($val['content'], 1);
                             // highlight the PHP* code & sanitize the parts
                             //--
                         } else {
                             //-- sanitize this html part
                             $val['content'] = (new SmartHtmlParser($val['content']))->get_clean_html();
                             //-- replace cid images
                             $tmp_matches = array();
                             preg_match_all('/<img[^>]+src=[\'"]?(cid:)([^\'"]*)[\'"]?[^>]*>/si', (string) $val['content'], $tmp_matches);
                             // fix: previous was just i (not si) ; modified on 160205
                             // $tmp_matches[0][i] : the full link
                             // $tmp_matches[1][i] : 'cid:'
                             // $tmp_matches[2][i] : cid part id
                             for ($cids = 0; $cids < Smart::array_size($tmp_matches[0]); $cids++) {
                                 $tmp_replace_cid_link = '';
                                 $tmp_replace_cid_link = (string) $tmp_matches[0][$cids];
                                 $tmp_replace_cid_link = str_replace("\n", ' ', $tmp_replace_cid_link);
                                 $tmp_replace_cid_link = str_replace($tmp_matches[1][$cids] . $tmp_matches[2][$cids], self::mime_link($y_ctrl_key, $the_message_eml, 'cid_' . $tmp_matches[2][$cids], $y_link, 'image', 'inline'), $tmp_replace_cid_link);
                                 //echo '<pre>'.Smart::escape_html($tmp_replace_cid_link).'</pre>';
                                 $val['content'] = str_replace($tmp_matches[0][$cids], $tmp_replace_cid_link, $val['content']);
                             }
                             //end for
                             $tmp_matches = array();
                             //--
                         }
                         //end if else
                         //--
                         $msg['texts'][$key]['content'] = $val['content'];
                         // rewrite back
                         //--
                         $xbuff = SmartUnicode::sub_str(Smart::striptags($val['content']), 0, 16384);
                         $xbuff_id = $key;
                         //--
                         $percent_similar = 0;
                         if (strlen($the_part_id) <= 0) {
                             @similar_text($buff, $xbuff, $percent_similar);
                             if ($percent_similar >= 15) {
                                 // 15% at least similarity
                                 $skips[$buff_id] = $percent_similar;
                                 // skip this alternate text part ...
                             }
                             //end if
                         }
                         //end if
                         //--
                         // clean buffer
                         $buff = '';
                         $buff_id = '';
                         //--
                     }
                     //end if
                     //--
                 }
                 //end if
                 //--
             }
             //end foreach
             //--
             if ($numparts <= 1) {
                 $skips = array();
                 // disallow skips if only one part
             }
             //end if
             //-- print bodies except the skipped by similarity
             $out .= '<hr>';
             //--
             $cnt = 0;
             foreach ($msg['texts'] as $key => $val) {
                 //--
                 if ((string) $val['type'] == 'text') {
                     // assure we don't print other things
                     //--
                     $cnt += 1;
                     //--
                     $eval_arr = array();
                     $eval_arr = SmartFileSysUtils::mime_eval('part_' . $cnt . '.html', 'inline');
                     //--
                     $tmp_link_pre = '<span title="Mime Part #' . $cnt . ' ( ' . Smart::escape_html(strtolower($val['mode']) . ' : ' . strtoupper($val['charset'])) . ' )"><a href="' . self::mime_link($y_ctrl_key, $the_message_eml, $key, $y_link, $eval_arr[0], $eval_arr[1], 'minimal') . '" target="' . $y_target . '__mimepart" data-smart="open.modal">';
                     $tmp_link_pst = '</a></span>';
                     //--
                     if (strlen($skips[$key]) <= 0) {
                         // print part if not skipped by similarity ...
                         //--
                         if ((string) $skip_part_linking == 'yes') {
                             // avoid display sub-text part links when only a part is displayed
                             $tmp_pict_img = '';
                         } else {
                             $tmp_pict_img = '<div align="right">' . $tmp_link_pre . '<img src="lib/framework/img/mark_right.gif">' . $tmp_link_pst . '</div>';
                         }
                         //end if
                         //--
                         if ((string) $y_process_mode == 'data-reply') {
                             if (strlen($reply_text['message']) <= 0) {
                                 $reply_text['message'] = (string) $val['content'];
                             }
                             //end if
                         } else {
                             $out .= $tmp_pict_img;
                             $out .= $val['content'];
                             $out .= '<br><hr><br>';
                         }
                         //end if
                         //--
                     } else {
                         //--
                         if ((string) $skip_part_linking != 'yes') {
                             // for replies, avoid display sub-text part links when only a part is displayed
                             if ((string) $y_process_mode == 'data-reply') {
                                 // nothing
                             } else {
                                 $out .= '<div align="right">' . '<span title="' . '~' . Smart::escape_html(Smart::format_number_dec($skips[$key], 0, '.', ',') . '%') . '">&nbsp;</span>' . $tmp_link_pre . '<img src="lib/framework/img/mark_check.gif">' . $tmp_link_pst . '</div>';
                             }
                             //end if else
                         }
                         //end if
                         //--
                     }
                     //end if else
                     //--
                 }
                 //end if
                 //--
             }
             //end foreach
             //--
         }
         //end if
         //--
         $out .= '</div></div><!-- END MIME MESSAGE HTML -->';
         //--
     }
     //end if else
     //--
     //--
     if ((string) $y_process_mode == 'data-full') {
         // output an array with message and all header info as data structure
         //--
         return array('message' => (string) $out, 'message-id' => (string) $head['message-id'], 'in-reply-to' => (string) $head['in-reply-to'], 'from' => (string) $head['from_addr'], 'to' => (string) $head['to_addr'], 'cc' => (string) $head['cc_addr'], 'date' => (string) $head['date'], 'atts_num' => (int) $reg_atts_num, 'atts_lst' => (string) $reg_atts_list, 'filepath' => (string) $the_message_eml, 'is_part' => (string) $reg_is_part);
         //--
     } elseif ((string) $y_process_mode == 'data-reply') {
         // output a special array for replies only
         //--
         $reply_text['message'] = (string) $reply_text['message'];
         // this comes from above
         $reply_text['from'] = (string) $head['from_addr'];
         $reply_text['to'] = (string) $head['to_addr'];
         $reply_text['cc'] = (string) $head['cc_addr'];
         $reply_text['date'] = (string) $head['date'];
         $reply_text['subject'] = (string) $head['subject'];
         $reply_text['message-id'] = (string) $head['message-id'];
         $reply_text['in-reply-to'] = (string) $head['in-reply-to'];
         //--
         return (array) $reply_text;
         //--
     } else {
         // 'default' or 'print' :: message as html view
         //--
         return (string) $out;
         //--
     }
     //end if
     //--
 }
Пример #9
0
 /**
  * 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
     //--
 }
Пример #10
0
 /**
  * Regex Segment to build Regex Expressions (Internal Use Only)
  *
  * @access 		private
  * @internal
  *
  * @param 	ENUM 	$y_mode 			:: The Regex mode to be returned (see in function)
  *
  * @return 	STRING						:: The Regex expression or empty if invalid mode is provided
  */
 public static function regex_stringvalidation_segment($y_mode)
 {
     //--
     switch (strtolower((string) $y_mode)) {
         // WARNING: Never use class modifiers like [:print:] with /u modifier as it fails with some versions of PHP / Regex / PCRE
         //--
         //== #INTERNAL USE ONLY
         //-- {{{SYNC-HTML-TAGS-REGEX}}} ; expression delimiter must be # (not / or others ...)
         case 'tag-name':
             $regex = 'a-z0-9\\-\\:';
             // regex expr: the allowed characters in tag names (just for open tags ... the end tags will add / and space
             break;
         case 'tag-start':
             $regex = '\\<\\s*?';
             // regex expr: tag start
             break;
         case 'tag-end-start':
             $regex = '\\<\\s*?/\\s*?';
             // regex expr: end tag start
             break;
         case 'tag-simple-end':
             $regex = '\\s*?\\>';
             // regex expr: tag end without attributes
             break;
         case 'tag-complex-end':
             $regex = '\\s+[^>]*?\\>';
             // regex expr: tag end with attributes or / (it needs at least one space after tag name)
             break;
             //--
             //== #ERROR: INVALID
             //--
         //--
         //== #ERROR: INVALID
         //--
         default:
             $regex = '+';
             Smart::raise_error('INVALID mode in function ' . __CLASS__ . '::' . __FUNCTION__ . '(): ' . $y_mode, 'Segment Validations Internal ERROR');
             die('');
             // just in case
             //--
             //== #END
             //--
     }
     //end switch
     //--
     return (string) $regex;
     //--
 }
Пример #11
0
 public static function get_ip_client()
 {
     //--
     $xout = (string) self::$cache['get_ip_client'];
     //--
     if ((string) $xout == '') {
         //--
         $ip = '';
         //--
         $ip = SmartValidator::validate_filter_ip_address((string) $_SERVER['REMOTE_ADDR']);
         // no forward or client IP should be considered here as they can be a security risk as they are untrusted !!
         //--
         if ((string) $ip == '') {
             Smart::raise_error('Cannot Determine Current Client IP Address', 'Invalid Client IP Address');
             return '';
         }
         //end if
         //--
         $xout = (string) $ip;
         //--
         self::$cache['get_ip_client'] = (string) $xout;
         //--
     }
     //end if
     //--
     return (string) $xout;
     //--
 }
Пример #12
0
 /**
  * Displays the Redis Errors and HALT EXECUTION (This have to be a FATAL ERROR as it occur when a FATAL Redis ERROR happens or when Data Exchange fails)
  * PRIVATE
  *
  * @param BOOL $is_fatal :: TRUE / FALSE if the Error is Fatal or Not
  * @param STRING $y_area :: The Area
  * @param STRING $y_error_message :: The Error Message to Display
  * @param STRING $y_query :: The query
  * @param STRING $y_warning :: The Warning Title
  *
  * @return :: HALT EXECUTION WITH ERROR MESSAGE
  *
  */
 private function error($is_fatal, $y_area, $y_error_message, $y_query = '', $y_warning = '')
 {
     //--
     $this->err = true;
     // required, to halt driver
     //--
     $is_fatal = (bool) $is_fatal;
     //--
     if ($is_fatal !== false) {
         // FATAL ERROR
         //--
         $def_warn = 'Execution Halted !';
         $y_warning = (string) trim((string) $y_warning);
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             $width = 750;
             $the_area = (string) $y_area;
             if ((string) $y_warning == '') {
                 $y_warning = (string) $def_warn;
             }
             //end if
             $the_error_message = 'Operation FAILED: ' . $def_warn . "\n" . $y_error_message;
             $the_params = '- ' . $this->description . ' -';
             $the_query_info = (string) $y_query;
             if ((string) $the_query_info == '') {
                 $the_query_info = '-';
                 // query cannot e empty in this case (templating enforcement)
             }
             //end if
         } else {
             $width = 550;
             $the_area = '';
             $the_error_message = 'Operation FAILED: ' . $def_warn;
             $the_params = '';
             $the_query_info = '';
             // do not display query if not in debug mode ... this a security issue if displayed to public ;)
         }
         //end if else
         //--
         $out = SmartComponents::db_error_message('Redis Client', 'Redis', 'Caching', 'Server', 'lib/core/img/db/redis_logo_trans.png', $width, $the_area, $the_error_message, $the_params, $the_query_info);
         //--
         Smart::raise_error('#REDIS@' . $this->socket . '# :: Q# // Redis Client :: ERROR :: ' . $y_area . "\n" . '*** Error-Message: ' . $y_error_message . "\n" . '*** Command:' . "\n" . $y_query, $out);
         die('');
         // just in case
         //--
     } else {
         // SILENT WARNING
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             //--
             SmartFrameworkRegistry::setDebugMsg('db', 'redis|log', ['type' => 'metainfo', 'data' => 'Redis SILENT WARNING: ' . $y_area . "\n" . $y_query . "\n" . 'Error-Message: ' . $y_error_message . "\n" . 'The settings for this Redis instance allow just silent warnings on connection fail.' . "\n" . 'All next method calls to this Redis instance will be discarded silently ...']);
             //--
         }
         //end if
         //--
         Smart::log_warning('#REDIS@' . $this->socket . '# :: Q# // Redis :: WARNING :: ' . $y_area . "\n" . '*** Error-Message: ' . $y_error_message . "\n" . '*** Command:' . "\n" . $y_query);
         //--
     }
     //end if else
     //--
 }
Пример #13
0
 public static function Authenticate($area)
 {
     //--
     global $configs;
     //--
     if (self::$authCompleted !== false) {
         http_response_code(500);
         die(SmartComponents::http_message_500_internalerror('App Boostrap Auth already loaded ...'));
     }
     //end if
     self::$authCompleted = true;
     //--
     switch ((string) $area) {
         case 'index':
             require 'modules/app/app-auth-index.inc.php';
             break;
         case 'admin':
             require 'modules/app/app-auth-admin.inc.php';
             break;
         default:
             $msg = 'Invalid Authentication Realm: ' . $area;
             Smart::raise_error('App Bootstrap / Authenticate: ' . $msg, 'App Bootstrap / Authenticate: ' . $msg);
             die('Invalid Auth Realm');
             // just in case
     }
     //end switch
     //--
 }
 public static function Run()
 {
     //--
     global $configs;
     //--
     //==
     //--
     if (self::$MiddlewareCompleted !== false) {
         // avoid to execute more than 1 this middleware !
         self::Raise500Error('Middleware App Execution already completed ...');
         return;
     }
     //end if
     self::$MiddlewareCompleted = true;
     //--
     $the_midmark = '[A]';
     //--
     if (SMART_FRAMEWORK_ADMIN_AREA !== true) {
         Smart::raise_error('Admin Middleware ERROR: SMART_FRAMEWORK_ADMIN_AREA is not set to TRUE', 'Invalid Area / This middleware is designed for Admin area and requires to turn ON the Administration flag ...');
         return;
     }
     //end if
     //--
     if (!defined('SMART_APP_TEMPLATES_DIR')) {
         self::Raise500Error('The SMART_APP_TEMPLATES_DIR not defined ...');
         return;
     }
     //end if
     //--
     if (defined('SMART_APP_MODULE_AREA')) {
         self::Raise500Error('Smart App Area must NOT be Defined outside controllers ...');
         return;
     }
     //end if
     if (defined('SMART_APP_MODULE_AUTH')) {
         self::Raise500Error('Smart App Module Auth must NOT be Defined outside controllers ...');
         return;
     }
     //end if
     if (defined('SMART_APP_MODULE_REALM_AUTH')) {
         self::Raise500Error('Smart App Module Realm Auth must NOT be Defined outside controllers ...');
         return;
     }
     //end if
     if (defined('SMART_APP_MODULE_DIRECT_OUTPUT')) {
         self::Raise500Error('Smart App Module Direct Output must NOT be Defined outside controllers ...');
         return;
     }
     //end if
     //--
     //==
     //--
     $smartframeworkservice = '';
     // special operation
     if (SmartFrameworkRegistry::issetRequestVar('smartframeworkservice') === true) {
         $smartframeworkservice = (string) strtolower((string) SmartUnicode::utf8_to_iso((string) SmartFrameworkRegistry::getRequestVar('smartframeworkservice')));
         switch ((string) $smartframeworkservice) {
             case 'status':
             case 'debug':
                 break;
             default:
                 // invalid value
                 $smartframeworkservice = '';
         }
         //end switch
     }
     //end if
     //--
     //==
     //-- switch language by cookie (this needs to be before loading the app core)
     if (strlen(trim((string) $_COOKIE['SmartApp_ADM_LANGUAGE_SET'])) > 0) {
         SmartTextTranslations::setLanguage(trim((string) $_COOKIE['SmartApp_ADM_LANGUAGE_SET']));
     }
     //end if
     //-- switch language by print cookie (this needs to be before loading the app core and after language by cookie)
     if (SmartFrameworkRegistry::issetRequestVar((string) SMART_FRAMEWORK_URL_PARAM_PRINTABLE) === true) {
         if (strtolower((string) SmartFrameworkRegistry::getRequestVar((string) SMART_FRAMEWORK_URL_PARAM_PRINTABLE)) == strtolower((string) SMART_FRAMEWORK_URL_VALUE_ENABLED)) {
             if (strlen(trim((string) $_COOKIE['SmartApp_ADM_PRINT_LANGUAGE_SET'])) > 0) {
                 SmartTextTranslations::setLanguage(trim((string) $_COOKIE['SmartApp_ADM_PRINT_LANGUAGE_SET']));
             }
             //end if
         }
         //end if
     }
     //end if
     //--
     //== RAW OUTPUT FOR STATUS
     //--
     if ((string) $smartframeworkservice == 'status') {
         //--
         if (SMART_SOFTWARE_DISABLE_STATUS_POWERED === true) {
             $status_powered_info = '';
         } else {
             $status_powered_info = (string) SmartComponents::draw_powered_info('no');
         }
         //end if else
         //--
         self::HeadersNoCache();
         // headers: cache control, force no-cache
         echo SmartComponents::http_status_message('Smart.Framework :: Status :: [OK]', '<script type="text/javascript">setTimeout(function(){ self.location = self.location; }, 60000);</script><img src="lib/core/img/busy_bar.gif"><div><h1>' . date('Y-m-d H:i:s O') . ' // Service Ready :: ' . $the_midmark . '</h1></div>' . $status_powered_info . '<br>');
         //--
         return;
         // break stop
         //--
     }
     //end if
     //--
     //== OVERALL AUTHENTICATION BREAKPOINT
     //--
     SmartAppBootstrap::Authenticate('admin');
     // if the auth uses session it may start now
     //--
     //== RAW OUTPUT FOR DEBUG
     //--
     if ((string) $smartframeworkservice == 'debug') {
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             self::HeadersNoCache();
             // headers: cache control, force no-cache
             $the_debug_cookie = trim((string) $_COOKIE['SmartFramework__DebugAdmID']);
             echo SmartDebugProfiler::print_debug_info('adm', $the_debug_cookie);
         } else {
             http_response_code(404);
             echo SmartComponents::http_message_404_notfound('No Debug service has been activated on this server ...');
         }
         //end if
         //--
         return;
         // break stop
         //--
     }
     //end if else
     //--
     //== LOAD THE MODULE (OR DEFAULT MODULE)
     //--
     $reserved_controller_names = ['php', 'html', 'stml', 'css', 'js', 'json', 'xml', 'rss', 'txt', 'csv', 'sql', 'png', 'gif', 'jpg', 'pdf', 'svg', 'zip', '7z', 'netarch'];
     // these are reserved extensions and cannot be used as controller names because they need to be used also with friendly URLs as the 2nd param if module is missing from URL page param
     //--
     $err404 = '';
     $arr = array();
     //--
     $page = (string) SmartUnicode::utf8_to_iso((string) SmartFrameworkRegistry::getRequestVar('page'));
     $page = trim(str_replace(array('/', '\\', ':', '?', '&', '=', '%'), array('', '', '', '', '', '', ''), $page));
     // fix for get as it automatically replaces . with _ (so, reverse), but also fix some invalid characters ...
     if ((string) $page == '') {
         $page = (string) $configs['app']['admin-home'];
     }
     //end if
     //--
     if (strpos($page, '.') !== false) {
         // page can be as module.controller / module.controller(.php|html|stml|css|js|json|xml|rss|txt|csv|sql|png|gif|jpg|pdf|svg|zip|7z|netarch)
         //--
         $arr = (array) explode('.', (string) $page, 3);
         // separe 1st and 2nd from the rest
         //--
         //#
         //#
         $arr[0] = trim(strtolower((string) $arr[0]));
         // module
         $arr[1] = trim(strtolower((string) $arr[1]));
         // controller
         //#
         //# Admin will NOT integrate with friendly URLs SMART_FRAMEWORK_SEMANTIC_URL_SKIP_MODULE
         //# that feature is just for Index
         //#
         //--
     } elseif ((string) $configs['app']['admin-default-module'] != '') {
         //--
         $arr[0] = trim(strtolower((string) $configs['app']['admin-default-module']));
         // get default module
         $arr[1] = trim(strtolower((string) $page));
         // controller
         //--
     } else {
         //--
         if ((string) $err404 == '') {
             $err404 = 'Invalid Page (Invalid URL Page Segments Syntax): ' . $page;
         }
         //end if
         //--
     }
     //end if else
     //--
     if ((string) $arr[0] == '' or (string) $arr[1] == '') {
         if ((string) $err404 == '') {
             $err404 = 'Invalid Page (Empty or Missing URL Page Segments): ' . $page;
         }
         //end if
     }
     //end if
     if (!preg_match('/^[a-z0-9_\\-]+$/', (string) $arr[0]) or !preg_match('/^[a-z0-9_\\-]+$/', (string) $arr[1])) {
         if ((string) $err404 == '') {
             $err404 = 'Invalid Page (Invalid Characters in the URL Page Segments): ' . $page;
         }
         //end if
     }
     //end if
     if (in_array((string) $arr[1], (array) $reserved_controller_names)) {
         if ((string) $err404 == '') {
             $err404 = 'Invalid Page (Reserved Page Controller Name): [' . $arr[1] . '] in: ' . $page;
         }
         //end if
     }
     //end if
     //--
     $the_controller_name = (string) $arr[0] . '.' . $arr[1];
     $the_path_to_module = Smart::safe_pathname(SmartFileSysUtils::add_dir_last_slash('modules/mod-' . Smart::safe_filename($arr[0])));
     $the_module = Smart::safe_pathname($the_path_to_module . Smart::safe_filename($arr[1]) . '.php');
     if (!is_file($the_module)) {
         if ((string) $err404 == '') {
             $err404 = 'Page does not exist: ' . $page;
         }
         //end if
     }
     //end if
     //--
     if ((string) $err404 != '') {
         self::Raise404Error((string) $err404);
         return;
     }
     //end if
     //--
     if (!SmartFileSysUtils::check_file_or_dir_name($the_path_to_module) or !SmartFileSysUtils::check_file_or_dir_name($the_module)) {
         self::Raise400Error('Insecure Module Access for Page: ' . $page);
         return;
     }
     //end if
     //--
     if (class_exists('SmartAppIndexController') or class_exists('SmartAppAdminController')) {
         self::Raise500Error('Module Class Runtimes must be defined only in modules ...');
         return;
     }
     //end if
     //--
     require (string) $the_module;
     //--
     if ((string) SMART_APP_MODULE_AREA !== 'ADMIN' and (string) SMART_APP_MODULE_AREA !== 'SHARED') {
         self::Raise403Error('Page Access Denied for Admin Area: ' . $page);
         return;
     }
     //end if
     if (defined('SMART_APP_MODULE_AUTH')) {
         if (SmartAuth::check_login() !== true) {
             self::Raise403Error('Page Access Denied ! No Authentication: ' . $page);
             return;
         }
         //end if
         if (defined('SMART_APP_MODULE_REALM_AUTH')) {
             if ((string) SmartAuth::get_login_realm() !== (string) SMART_APP_MODULE_REALM_AUTH) {
                 self::Raise403Error('Page Access Denied ! Invalid Login Realm: ' . $page);
                 return;
             }
             //end if
         }
         //end if
     }
     //end if
     //--
     if (!class_exists('SmartAppAdminController')) {
         self::Raise500Error('Invalid Module Class Runtime for Page: ' . $page);
         return;
     }
     //end if
     if (!is_subclass_of('SmartAppAdminController', 'SmartAbstractAppController')) {
         self::Raise500Error('Invalid Module Class Inheritance for Controller Page: ' . $page);
         return;
     }
     //end if
     //--
     //== PATHS
     //--
     $base_script = SmartUtils::get_server_current_script();
     $base_full_path = SmartUtils::get_server_current_path();
     $base_full_url = SmartUtils::get_server_current_url();
     //--
     //== RUN THE MODULE
     //--
     $appModule = new SmartAppAdminController($the_path_to_module, $base_script, $base_full_path, $base_full_url, $page, $the_controller_name);
     //--
     if (SMART_APP_MODULE_DIRECT_OUTPUT !== true) {
         ob_start();
     }
     //end if
     $appStatusCode = (int) $appModule->Run();
     $appModule->ShutDown();
     if (SMART_APP_MODULE_DIRECT_OUTPUT !== true) {
         $ctrl_output = ob_get_contents();
         ob_end_clean();
         if ((string) $ctrl_output != '') {
             Smart::log_warning('The middleware service ' . $the_midmark . ' detected an illegal output in the controller: ' . $page . "\n" . 'The result of this output is: ' . $ctrl_output);
         }
         //end if
         $ctrl_output = '';
     } else {
         return;
         // break stop after the controller has terminated the direct output
     }
     //end if else
     //--
     $appSettings = (array) $appModule->PageViewGetCfgs();
     //--
     //== CACHE CONTROL
     //--
     if ((int) $appSettings['expires'] > 0 and (string) SMART_FRAMEWORK_DEBUG_MODE != 'yes') {
         self::HeadersCacheExpire((int) $appSettings['expires'], (int) $appSettings['modified']);
         // headers: cache expiration control
     } else {
         self::HeadersNoCache();
         // headers: cache control, force no-cache
     }
     //end if else
     //--
     //== STATUS CODE
     //--
     switch ((int) $appStatusCode) {
         //-- client errors
         case 400:
             self::Raise400Error((string) $appSettings['error']);
             return;
             break;
         case 401:
             self::Raise401Error((string) $appSettings['error']);
             return;
             break;
         case 403:
             self::Raise403Error((string) $appSettings['error']);
             return;
             break;
         case 404:
             self::Raise404Error((string) $appSettings['error']);
             return;
             break;
         case 429:
             self::Raise429Error((string) $appSettings['error']);
             return;
             break;
             //-- server errors
         //-- server errors
         case 500:
             self::Raise500Error((string) $appSettings['error']);
             return;
             break;
         case 502:
             self::Raise502Error((string) $appSettings['error']);
             return;
             break;
         case 503:
             self::Raise503Error((string) $appSettings['error']);
             return;
             break;
         case 504:
             self::Raise504Error((string) $appSettings['error']);
             return;
             break;
             //-- extended 2xx statuses: NOTICE / WARNING / ERROR that can be used for REST / API
         //-- extended 2xx statuses: NOTICE / WARNING / ERROR that can be used for REST / API
         case 202:
             // NOTICE
             if (!headers_sent()) {
                 http_response_code(202);
                 // Accepted (this should be used only as an alternate SUCCESS code instead of 200 for NOTICES)
             } else {
                 Smart::log_warning('Headers Already Sent before 202 ...');
             }
             //end if else
             break;
         case 203:
             // WARNING
             if (!headers_sent()) {
                 http_response_code(203);
                 // Non-Authoritative Information (this should be used only as an alternate SUCCESS code instead of 200 for WARNINGS)
             } else {
                 Smart::log_warning('Headers Already Sent before 203 ...');
             }
             //end if else
             break;
         case 208:
             // ERROR
             if (!headers_sent()) {
                 http_response_code(208);
                 // Already Reported (this should be used only as an alternate SUCCESS code instead of 200 for ERRORS)
             } else {
                 Smart::log_warning('Headers Already Sent before 208 ...');
             }
             //end if else
             break;
             //-- DEFAULT: OK
         //-- DEFAULT: OK
         case 200:
         default:
             // any other codes not listed above are not supported and will be interpreted as 200
             // nothing to do here ...
     }
     //end switch
     //--
     //== PREPARE THE OUTPUT
     //--
     if (stripos((string) $configs['js']['popup-override-mobiles'], '<' . SmartUtils::get_os_browser_ip('os') . '>') !== false) {
         $configs['js']['popup-mode'] = 'popup';
         // particular os settings for mobiles
     }
     //end if
     //--
     $rawpage = '';
     if (isset($appSettings['rawpage'])) {
         $rawpage = strtolower((string) $appSettings['rawpage']);
         if ((string) $rawpage == 'yes') {
             $rawpage = 'yes';
             // standardize the value
         }
         //end if
     }
     //end if
     if ((string) $rawpage != 'yes') {
         $rawpage = '';
     }
     //end if
     //--
     $rawmime = '';
     if (isset($appSettings['rawmime'])) {
         $rawmime = (string) $appSettings['rawmime'];
         if ((string) $rawmime != '') {
             $rawmime = SmartValidator::validate_mime_type($rawmime);
         }
         //end if
     }
     //end if else
     //--
     $rawdisp = '';
     if (isset($appSettings['rawdisp'])) {
         $rawdisp = (string) $appSettings['rawdisp'];
         if ((string) $rawdisp != '') {
             $rawdisp = SmartValidator::validate_mime_disposition($rawdisp);
         }
         //end if
     }
     //end if else
     //--
     $appData = (array) $appModule->PageViewGetVars();
     //--
     $appData['base-path'] = (string) $base_full_path;
     $appData['base-url'] = (string) $base_full_url;
     //--
     //== REDIRECTION HANDLER (this can be set only explicit from Controllers)
     //--
     if ((string) $appSettings['redirect-url'] != '') {
         // expects a valid URL
         //--
         $the_redirect_link = '<a href="' . Smart::escape_html((string) $appSettings['redirect-url']) . '">' . Smart::escape_html((string) $appSettings['redirect-url']) . '</a>';
         //--
         if (headers_sent()) {
             Smart::log_warning('Headers Already Sent before Redirection: [' . $appStatusCode . '] ; URL: ' . $appSettings['redirect-url']);
             self::Raise500Error('The app failed to Redirect to: ' . $the_redirect_link);
             return;
         }
         //end if
         switch ((int) $appStatusCode) {
             case 301:
                 http_response_code(301);
                 $the_redirect_text = 'Moved Permanently';
                 // permanent redirect for HTTP 1.0 / HTTP 1.1
                 break;
             case 302:
             default:
                 // any other code will be interpreted as 302 (the default redirection in PHP)
                 http_response_code(302);
                 $the_redirect_text = 'Found';
                 // temporary redirect for HTTP 1.0 / HTTP 1.1
                 break;
         }
         //end switch
         header('Location: ' . SmartFrameworkSecurity::FilterUnsafeString((string) $appSettings['redirect-url']));
         echo '<h1>' . Smart::escape_html($the_redirect_text) . '</h1>' . '<br>' . 'If the page redirection fails, click on the below link:' . '<br>' . $the_redirect_link;
         return;
         // break stop
     }
     //end if
     //--
     //== DOWNLOADS HANDLER (downloads can be set only explicit from Controllers)
     //--
     if ((string) $appSettings['download-packet'] != '' and (string) $appSettings['download-key'] != '') {
         // expects an encrypted data packet and a key
         $dwl_result = self::DownloadsHandler((string) $appSettings['download-packet'], (string) $appSettings['download-key']);
         if ((string) $dwl_result != '') {
             Smart::log_info('File Download - Client: ' . SmartUtils::get_visitor_signature(), (string) $dwl_result);
             // log result and mark it as finalized
         }
         //end if
         return;
         // break stop
     }
     //end if
     //--
     //== RAW OUTPUT FOR PAGES
     //--
     if ((string) $rawpage == 'yes') {
         //-- {{{SYNC-RESOURCES}}}
         if (function_exists('memory_get_peak_usage')) {
             $res_memory = @memory_get_peak_usage(false);
         } else {
             $res_memory = 'unknown';
         }
         //end if else
         $res_time = (double) (microtime(true) - (double) SMART_FRAMEWORK_RUNTIME_READY);
         //-- #END-SYNC
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             //-- {{{SYNC-DEBUG-META-INFO}}}
             SmartFrameworkRegistry::setDebugMsg('stats', 'memory', $res_memory);
             // bytes
             SmartFrameworkRegistry::setDebugMsg('stats', 'time', $res_time);
             // seconds
             //-- #END-SYNC
             $the_debug_cookie = trim((string) $_COOKIE['SmartFramework__DebugAdmID']);
             SmartDebugProfiler::save_debug_info('adm', $the_debug_cookie, false);
         } else {
             $the_debug_cookie = '';
         }
         //end if
         //--
         if (headers_sent()) {
             Smart::raise_error('Middleware ERROR: Headers already sent', 'ERROR: Headers already sent !');
             return;
             // avoid serve raw pages with errors injections before headers
         }
         //end if
         //--
         if ((string) $rawmime != '') {
             header('Content-Type: ' . $rawmime);
         }
         //end if
         if ((string) $rawdisp != '') {
             header('Content-Disposition: ' . $rawdisp);
         }
         //end if
         header('Content-Length: ' . (0 + strlen((string) $appData['main'])));
         // must be strlen NOT SmartUnicode::str_len as it must get number of bytes not characters
         echo (string) $appData['main'];
         return;
         // break stop
         //--
     }
     //end if else
     //--
     //== DEFAULT OUTPUT
     //--
     if (isset($appSettings['template-path'])) {
         if ((string) $appSettings['template-path'] == '@') {
             // if template path is set to self (module)
             $the_template_path = '@';
             // this is a special setting
         } else {
             $the_template_path = Smart::safe_pathname(SmartFileSysUtils::add_dir_last_slash(trim((string) $appSettings['template-path'])));
         }
         //end if else
     } else {
         $the_template_path = Smart::safe_pathname(SmartFileSysUtils::add_dir_last_slash(trim((string) $configs['app']['admin-template-path'])));
         // use default template path
     }
     //end if else
     //--
     if (isset($appSettings['template-file'])) {
         $the_template_file = Smart::safe_filename(trim((string) $appSettings['template-file']));
     } else {
         $the_template_file = Smart::safe_filename(trim((string) $configs['app']['admin-template-file']));
         // use default template
     }
     //end if else
     //--
     if ((string) $the_template_path == '@') {
         $the_template_path = (string) $the_path_to_module . 'templates/';
         // must have the dir last slash as above
     } else {
         $the_template_path = (string) SMART_APP_TEMPLATES_DIR . $the_template_path;
         // finally normalize and set the complete template path
     }
     //end if else
     $the_template_file = (string) $the_template_file;
     // finally normalize
     //--
     if (!SmartFileSysUtils::check_file_or_dir_name($the_template_path)) {
         Smart::log_warning('Invalid Page Template Path: ' . $the_template_path);
         self::Raise500Error('Invalid Page Template Path. See the error log !');
         return;
     }
     //end if
     if (!is_dir($the_template_path)) {
         Smart::log_warning('Page Template Path does not Exists: ' . $the_template_path);
         self::Raise500Error('Page Template Path does not Exists. See the error log !');
         return;
     }
     //end if
     if (!SmartFileSysUtils::check_file_or_dir_name($the_template_path . $the_template_file)) {
         Smart::log_warning('Invalid Page Template File: ' . $the_template_path . $the_template_file);
         self::Raise500Error('Invalid Page Template File. See the error log !');
         return;
     }
     //end if
     if (!is_file($the_template_path . $the_template_file)) {
         Smart::log_warning('Page Template File does not Exists: ' . $the_template_path . $the_template_file);
         self::Raise500Error('Page Template File does not Exists. See the error log !');
         return;
     }
     //end if
     //--
     $the_template_content = trim(SmartMarkersTemplating::read_template_file($the_template_path . $the_template_file));
     if ((string) $the_template_content == '') {
         Smart::log_warning('Page Template File is Empty or cannot be read: ' . $the_template_path . $the_template_file);
         self::Raise500Error('Page Template File is Empty or cannot be read. See the error log !');
         return;
     }
     //end if
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         $the_template_content = str_ireplace('</head>', "\n" . SmartDebugProfiler::js_headers_debug('admin.php?smartframeworkservice=debug') . "\n" . '</head>', $the_template_content);
         $the_template_content = str_ireplace('</body>', "\n" . SmartDebugProfiler::div_main_debug() . "\n" . '</body>', $the_template_content);
     }
     //end if
     //--
     $appData['app-domain'] = (string) $configs['app']['admin-domain'];
     $appData['template-file'] = $the_template_path . $the_template_file;
     $appData['template-path'] = $the_template_path;
     $appData['js.settings'] = SmartComponents::js_inc_settings((string) $configs['js']['popup-mode'], true, (bool) SMART_APP_VISITOR_COOKIE);
     $appData['head-meta'] = (string) $appData['head-meta'];
     if ((string) $appData['head-meta'] == '') {
         $appData['head-meta'] = '<!-- Head Meta -->';
     }
     //end if
     $appData['title'] = (string) $appData['title'];
     $appData['main'] = (string) $appData['main'];
     $appData['lang'] = SmartTextTranslations::getLanguage();
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         $the_debug_cookie = 'adm-' . Smart::uuid_10_seq() . '-' . Smart::uuid_10_num() . '-' . Smart::uuid_10_str();
         @setcookie('SmartFramework__DebugAdmID', (string) $the_debug_cookie, 0, '/');
         // debug token cookie is set just on main request
         //--
     }
     //end if
     //--
     echo SmartMarkersTemplating::render_mixed_template((string) $the_template_content, (array) $appData, (string) $appData['template-path'], 'no', 'no');
     //-- {{{SYNC-RESOURCES}}}
     if (function_exists('memory_get_peak_usage')) {
         $res_memory = @memory_get_peak_usage(false);
     } else {
         $res_memory = 'unknown';
     }
     //end if else
     $res_time = (double) (microtime(true) - (double) SMART_FRAMEWORK_RUNTIME_READY);
     //-- #END-SYNC
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //-- {{{SYNC-DEBUG-META-INFO}}}
         SmartFrameworkRegistry::setDebugMsg('stats', 'memory', $res_memory);
         // bytes
         SmartFrameworkRegistry::setDebugMsg('stats', 'time', $res_time);
         // seconds
         //-- #END-SYNC
         SmartDebugProfiler::save_debug_info('adm', $the_debug_cookie, true);
         //--
     }
     //end if else
     //--
     if (SMART_SOFTWARE_DISABLE_STATUS_POWERED !== true) {
         echo "\n" . '<!-- Smart.Framework スマート.フレームワーク :: ' . SMART_FRAMEWORK_RELEASE_TAGVERSION . ' / ' . SMART_FRAMEWORK_RELEASE_VERSION . ' @ ' . $the_midmark . ' :: ' . SMART_FRAMEWORK_RELEASE_URL . ' -->';
     }
     //end if
     echo "\n" . '<!-- Resources: [' . Smart::format_number_dec($res_time, 13, '.', '') . ' sec.] / [' . Smart::format_number_dec($res_memory, 0, '.', ' ') . ' by.]' . ' -->' . "\n";
     //--
 }
 public static function getTranslationsFromSource($the_lang, $y_area, $y_subarea)
 {
     //--
     if (substr((string) $y_area, 0, 1) == '@') {
         if ((string) $the_lang == 'en') {
             $fdb_dir = 'lib/app/translations/';
         } else {
             // default is: modules/app/translations/
             $fdb_dir = (string) SMART_FRAMEWORK_LANGUAGES_CACHE_DIR;
         }
         //end if else
         $fdb_template = strtolower($y_area . '/' . $y_subarea . '-' . $the_lang);
     } else {
         // $y_area can be: apps, mod-something, ...
         $fdb_dir = (string) Smart::safe_pathname('modules/' . $y_area . '/translations/');
         $fdb_template = strtolower($y_subarea . '-' . $the_lang);
     }
     //end if else
     //--
     $fdb_file = (string) $fdb_dir . $fdb_template . '.yaml';
     SmartFileSysUtils::raise_error_if_unsafe_path($fdb_file);
     //--
     if (!is_dir($fdb_dir)) {
         Smart::raise_error('Invalid Language Dir: ' . $fdb_dir . ' :: for: ' . $y_area . '@' . $y_subarea, 'Invalid Language Dir for: ' . $y_area . '@' . $y_subarea);
         return array();
     }
     //end if
     //--
     if (!is_file($fdb_file)) {
         //--
         Smart::raise_error('Invalid Language File: ' . $fdb_file, 'Invalid Language File: ' . $fdb_template);
         return array();
         //--
     }
     //end if
     //--
     $fcontent = SmartFileSystem::staticread($fdb_file);
     $arr = (new SmartYamlConverter())->parse((string) $fcontent);
     //--
     if (!is_array($arr)) {
         Smart::raise_error('Parse Error / TRANSLATIONS :: Language File: ' . $fdb_file, 'Parse Error / TRANSLATIONS :: Language File: ' . $fdb_template);
         return array();
     }
     //end if
     //--
     if (!is_array($arr['TRANSLATIONS'])) {
         Smart::raise_error('Parse Error / TRANSLATIONS :: Language File: ' . $fdb_file, 'Parse Error / TRANSLATIONS :: Language File: ' . $fdb_template);
         return array();
     }
     //end if
     if (Smart::array_size($arr['TRANSLATIONS'][(string) $y_subarea]) <= 0) {
         Smart::log_warning('Parse Error / TRANSLATIONS.' . $y_subarea . ' :: Language File: ' . $fdb_template);
         return array();
     }
     //end if
     //--
     return (array) $arr['TRANSLATIONS'][(string) $y_subarea];
     //--
 }
Пример #16
0
 public static function Create_Required_Dirs()
 {
     //--
     if (!defined('SMART_FRAMEWORK_VERSION')) {
         die('Smart Runtime // Create Required Dirs :: Requires SmartFramework to be loaded ...');
     }
     //end if
     //--
     if (self::$RequiredDirsCreated !== false) {
         return;
         // avoid run after it was used by runtime
     }
     //end if
     self::$RequiredDirsCreated = true;
     //--
     @clearstatcache();
     //-- tmp dir
     $dir = 'tmp/';
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
         SmartFileSystem::write($dir . '.htaccess', trim((string) SMART_FRAMEWORK_HTACCESS_NOINDEXING) . "\n" . trim((string) SMART_FRAMEWORK_HTACCESS_NOEXECUTION) . "\n" . trim((string) SMART_FRAMEWORK_HTACCESS_FORBIDDEN) . "\n");
     } else {
         // manage debug cleanup
         if ((string) SMART_FRAMEWORK_DEBUG_MODE != 'yes') {
             if (is_file('tmp/SMART-FRAMEWORK__DEBUG-ON')) {
                 if (is_dir('tmp/logs/idx/')) {
                     SmartFileSystem::dir_delete('tmp/logs/idx/', true);
                 }
                 //end if
                 if (is_dir('tmp/logs/adm/')) {
                     SmartFileSystem::dir_delete('tmp/logs/adm/', true);
                 }
                 //end if
                 SmartFileSystem::delete('tmp/SMART-FRAMEWORK__DEBUG-ON');
             }
             //end if
         } else {
             SmartFileSystem::write_if_not_exists('tmp/SMART-FRAMEWORK__DEBUG-ON', 'DEBUG:ON');
         }
         //end if else
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (Temporary Folder is Not Writable)');
         die;
     }
     //end if
     if (!is_file($dir . '.htaccess')) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'The .htaccess file is missing on FileSystem #TMP: ' . $dir . '.htaccess', 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     //-- tmp locks dir
     $dir = 'tmp/locks/';
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     //-- tmp cache dir
     $dir = 'tmp/cache/';
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     //-- tmp logs dir
     $dir = 'tmp/logs/';
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (Error Log Folder is Not Writable)');
         die;
     }
     //end if
     //-- tmp logs/admin dir
     $dir = 'tmp/logs/adm/';
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     //-- tmp logs/idx dir
     $dir = 'tmp/logs/idx/';
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     //-- tmp sessions dir
     $dir = 'tmp/sessions/';
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     //-- wpub dir
     $dir = 'wpub/';
     // {{{SYNC-WPUB-DIR}}}
     $ctrlfile = $dir . '#wpub';
     $htfile = $dir . '.htaccess';
     $robotsfile = $dir . 'robots.txt';
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
         SmartFileSystem::write($robotsfile, 'User-agent: *' . "\n" . 'Disallow: *');
         // avoid robots to index it
         SmartFileSystem::write($ctrlfile, 'FileName: #wpub (#WEB-PUBLIC)' . "\n" . 'Created by: App-Runtime' . "\n" . date('Y-m-d H:i:s O'));
         SmartFileSystem::write($htfile, trim((string) SMART_FRAMEWORK_HTACCESS_NOEXECUTION) . "\n");
         // trim((string)SMART_FRAMEWORK_HTACCESS_NOINDEXING)."\n".
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: #WEB-PUBLIC Folder: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     if (!is_file($ctrlfile)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'Cannot Connect to FileSystem #WEB-PUBLIC: ' . $ctrlfile, 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     if (!is_file($htfile)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'The .htaccess file is missing on FileSystem #WEB-PUBLIC: ' . $htfile, 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     //-- wpub/webapps-content
     $dir = 'wpub/webapps-content/';
     // {{{SYNC-WEBAPPS-DIR}}}
     if (!is_dir($dir)) {
         SmartFileSystem::dir_create($dir);
         SmartFileSystem::write($dir . 'index.html', '');
     }
     // end if
     if (!is_writable($dir)) {
         Smart::raise_error('#SMART-FRAMEWORK-CREATE-REQUIRED-DIRS#' . "\n" . 'General ERROR :: \'' . $dir . '\' is NOT writable !', 'App Init ERROR :: (See Error Log for More Details)');
         die;
     }
     //end if
     //--
 }
Пример #17
0
 /**
  * Constructor
  * Initializes the blowfish cipher object, and gives a sets
  * the secret key
  *
  * @param string $key
  * @param enum $runmode		ex: mcrypt/blowfish/CBC
  * @access public
  */
 public function __construct($key, $runmode)
 {
     //--
     if (!function_exists('mcrypt_module_self_test')) {
         Smart::raise_error('SmartCryptoMCryptCipher requires the PHP MCRYPT Extension ! If is not available use the alternative Encryption Mode in Configuration INITS !', 'PHP MCRYPT Extension is missing');
         return '';
     }
     //end if
     //-- Blowfish uses a variable size key, ranging from 32 to 448 bits (4 to 56 characters)
     if ((string) $key == '') {
         $key = SMART_FRAMEWORK_SECURITY_KEY;
     }
     //end if
     //--
     $tmp_mode_crypto = explode('/', (string) $runmode);
     // Example: 'mcrypt/blowfish/CBC'
     $tmp_mcrypt_check = trim(strtolower($tmp_mode_crypto[0]));
     $tmp_mcrypt_algo = trim(strtolower($tmp_mode_crypto[1]));
     $tmp_mcrypt_method = trim(strtoupper($tmp_mode_crypto[2]));
     //--
     if ((string) $tmp_mcrypt_check != 'mcrypt') {
         Smart::raise_error('M-Crypt-Encryption // Invalid Settings: ' . $tmp_mode_crypto, 'M-Crypt-Encryption // Invalid Settings !');
         return '';
     }
     //end if
     //-- ECB or OFB are not secure so not accepted ; The CBC and CFB mode requires a initialization vector (iv).
     switch ((string) $tmp_mcrypt_method) {
         // cipher
         case 'CBC':
             // currently this is the only-one compatible with the Blowfish JS Api
             $this->mcrypt_mode = MCRYPT_MODE_CBC;
             // the best choice
             break;
         case 'CFB':
             $this->mcrypt_mode = MCRYPT_MODE_CFB;
             break;
         default:
             Smart::raise_error('M-Crypt-Encryption // Invalid Mode: ' . $tmp_mcrypt_method, 'M-Crypt-Encryption // Invalid Mode !');
             return '';
     }
     //end if
     //--
     switch ((string) $tmp_mcrypt_algo) {
         // cipher
         case 'blowfish':
             // currently this is the only-one compatible with the Symmetric Crypto JS Api
             //--
             $this->mcrypt_cipher = MCRYPT_BLOWFISH;
             // chipher (Blowfish is a 64-bit (8 bytes) block cipher)
             //-- Blowfish key {{{SYNC-BLOWFISH-KEY}}} ; key size: 32 .. 448 bits (4 .. 56 chars) ; default used is 384 bits = 48 chars.
             $this->mcrypt_key = (string) substr(SmartHashCrypto::sha512($key), 13, 29) . substr(sha1($key), 13, 10) . substr(md5($key), 13, 9);
             //-- Blowfish iv {{{SYNC-BLOWFISH-IV}}} ; block size: 64 bits = 8 chars
             $this->mcrypt_iv = (string) substr(sha1('@SmartFrameworkCrypto/BlowFish:' . $key . '#' . sha1('BlowFish-iv-SHA1' . $key) . '-' . md5('BlowFish-iv-MD5' . $key) . '#'), 29, 8);
             //--
             break;
         case 'twofish':
             //--
             $this->mcrypt_cipher = MCRYPT_TWOFISH;
             //-- key sizes: 128, 192 or 256 bits = max 32 chars
             $this->mcrypt_key = (string) substr(SmartHashCrypto::sha512($key), 13, 20) . substr(sha1($key), 13, 10) . substr(md5($key), 13, 2);
             //-- block sizes: 128 bits = 16 chars
             $this->mcrypt_iv = (string) substr(sha1('@SmartFrameworkCrypto/TwoFish:' . $key . '#' . sha1('TwoFish-iv-SHA1' . $key) . '-' . md5('TwoFish-iv-MD5' . $key) . '#'), 19, 16);
             //--
             break;
         case 'serpent':
             //--
             $this->mcrypt_cipher = MCRYPT_SERPENT;
             //-- key sizes: 128, 192 or 256 bits = max 32 chars
             $this->mcrypt_key = (string) substr(SmartHashCrypto::sha512($key), 13, 20) . substr(sha1($key), 13, 10) . substr(md5($key), 13, 2);
             //-- block sizes: 128 bits = 16 chars
             $this->mcrypt_iv = (string) substr(sha1('@SmartFrameworkCrypto/Serpent:' . $key . '#' . sha1('Serpent-iv-SHA1' . $key) . '-' . md5('Serpent-iv-MD5' . $key) . '#'), 19, 16);
             //--
             break;
         case 'ghost':
             //--
             $this->mcrypt_cipher = MCRYPT_GOST;
             //-- key sizes: 256 bits = max 32 chars
             $this->mcrypt_key = (string) substr(SmartHashCrypto::sha512($key), 13, 20) . substr(sha1($key), 13, 10) . substr(md5($key), 13, 2);
             //-- block sizes: 64 bits = 8 chars
             $this->mcrypt_iv = (string) substr(sha1('@SmartFrameworkCrypto/Ghost:' . $key . '#' . sha1('Ghost-iv-SHA1' . $key) . '-' . md5('Ghost-iv-MD5' . $key) . '#'), 29, 8);
             break;
         default:
             Smart::raise_error('M-Crypt-Encryption // Invalid Cipher: ' . $tmp_mcrypt_algo, 'M-Crypt-Encryption // Invalid Cipher !');
             return '';
     }
     //end if
     //--
 }