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];
     //--
 }
 public function render($file, $arr_vars = array())
 {
     //--
     if (!is_array($arr_vars)) {
         $arr_vars = array();
     }
     //end if
     //--
     if (!\SmartFileSysUtils::check_file_or_dir_name($this->dir . $file)) {
         throw new \Exception('Twig Templating / Render File / The file name / path contains invalid characters: ' . $this->dir . $file);
         return;
     }
     //end if
     //--
     if (!is_file($this->dir . $file)) {
         throw new \Exception('Twig Templating / The Template file to render does not exists: ' . $this->dir . $file);
         return;
     }
     //end if
     //--
     return (string) $this->twig->render((string) $file, (array) $arr_vars);
     //--
 }
 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";
     //--
 }
Пример #4
0
 private function folder_iterator($recurring, $dir_name, $include_dot_files, $search_pattern = '', $search_prevent_file = '', $search_prevent_override = '')
 {
     //--
     $recurring = (bool) $recurring;
     $dir_name = (string) $dir_name;
     $include_dot_files = (bool) $include_dot_files;
     $search_pattern = (string) $search_pattern;
     $search_prevent_file = (string) $search_prevent_file;
     $search_prevent_override = (string) $search_prevent_override;
     //--
     if ((string) $dir_name == '') {
         Smart::log_warning('LibFileSys // ReadsFolderRecurring // Dir Name is Empty !');
         return;
         // this function does not return anything, but just stop here in this case
     }
     //end if
     //-- fix invalid path (must end with /)
     $dir_name = SmartFileSysUtils::add_dir_last_slash($dir_name);
     //-- protection
     SmartFileSysUtils::raise_error_if_unsafe_path($dir_name);
     //--
     @clearstatcache();
     //--
     $this->pattern_search_str = $search_pattern;
     $this->search_prevent_file = $search_prevent_file;
     $this->search_prevent_override = $search_prevent_override;
     //--
     if (SmartFileSystem::file_or_link_exists($dir_name) and !is_file($dir_name)) {
         // can be dir or link
         //list
         //--
         if ($handle = opendir($dir_name)) {
             //---------------------------------------
             while (false !== ($file = readdir($handle))) {
                 //--
                 if ((string) $file != '.' and (string) $file != '..') {
                     //--
                     if ($include_dot_files or !$include_dot_files and substr($file, 0, 1) != '.') {
                         //--
                         SmartFileSysUtils::raise_error_if_unsafe_path($dir_name . $file);
                         //-- params to see if counted or added to pattern matches
                         $tmp_allow_addition = 1;
                         $tmp_add_pattern = 0;
                         //-- this is for #private folders, will prevent searching in folders containing for example this file: .private-folder but can be overriden by the $search_prevent_override option exluding a particular path like folder/private/user1
                         if (strlen($search_prevent_file) > 0 and is_file($dir_name . $search_prevent_file)) {
                             if (strlen($search_prevent_override) <= 0 or strlen($search_prevent_override) > 0 and !is_file($dir_name . $search_prevent_override)) {
                                 $tmp_allow_addition = 0;
                             }
                             //end if
                         }
                         //end if
                         //-- this is a search pattern (search pattern does not apply to folders !!) ; if no empty will populate the pattern matches array with all files and folders matching ; to include all, use * or a particular search for the rest like myfile1
                         if ((string) $search_pattern == '' or is_dir($dir_name . $file)) {
                             if ($tmp_allow_addition) {
                                 if ($this->list_files_and_dirs) {
                                     $tmp_add_pattern = 1;
                                 }
                                 //end if
                             }
                             //end if
                         } else {
                             if ($this->limit_search_files <= 0 or Smart::array_size($this->pattern_file_matches) < $this->limit_search_files) {
                                 if ((string) $search_pattern == '*' or (string) $search_pattern == '[image]' and (substr($file, -4, 4) == '.png' or substr($file, -4, 4) == '.gif' or substr($file, -4, 4) == '.jpg' or substr($file, -5, 5) == '.jpeg') or (string) $search_pattern != '*' and (string) $search_pattern != '[image]' and stripos($file, $search_pattern) !== false) {
                                     if ($tmp_allow_addition) {
                                         if ($this->list_files_and_dirs) {
                                             $tmp_add_pattern = 1;
                                         }
                                         //end if
                                     }
                                     //end if
                                 } else {
                                     $tmp_allow_addition = 0;
                                 }
                                 //end if else
                             }
                             //end if
                         }
                         //end if
                         //--
                         if ($this->limit_search_files > 0) {
                             // the dir should not be taken in count here
                             if ($this->num_files + $this->num_links >= $this->limit_search_files) {
                                 break;
                             }
                             //end if
                         }
                         //end if
                         //--
                         if (!is_link($dir_name . $file)) {
                             //--
                             if (is_dir($dir_name . $file)) {
                                 //-- dir
                                 if ($tmp_allow_addition) {
                                     //--
                                     $tmp_fsize = Smart::format_number_int(@filesize($dir_name . $file), '+');
                                     //--
                                     $this->num_dirs++;
                                     $this->num_size += $tmp_fsize;
                                     $this->num_dirs_size += $tmp_fsize;
                                     //--
                                     $tmp_fsize = 0;
                                     //--
                                     if ($tmp_add_pattern) {
                                         if ($recurring) {
                                             // if recurring, add the full path
                                             $this->pattern_dir_matches[$dir_name . $file] = @filemtime($dir_name . $file);
                                         } else {
                                             // if not recurring, add just base path, without dirname prefix
                                             $this->pattern_dir_matches[$file] = @filemtime($dir_name . $file);
                                         }
                                         //end if else
                                     }
                                     //end if
                                     //--
                                 }
                                 //end if
                                 //--
                                 if ($recurring) {
                                     //-- we go search inside even if this folder name may not match the search pattern, it is a folder, except if dissalow addition from above
                                     $this->folder_iterator($recurring, SmartFileSysUtils::add_dir_last_slash($dir_name . $file), $include_dot_files, $search_pattern, $search_prevent_file, $search_prevent_override);
                                     //--
                                 }
                                 //end if
                                 //--
                             } else {
                                 //-- file
                                 if ($tmp_allow_addition) {
                                     //--
                                     $tmp_fsize = Smart::format_number_int(@filesize($dir_name . $file), '+');
                                     //--
                                     $this->num_files++;
                                     $this->num_size += $tmp_fsize;
                                     $this->num_files_size += $tmp_fsize;
                                     //--
                                     $tmp_fsize = 0;
                                     //--
                                     if ($tmp_add_pattern) {
                                         if ($recurring) {
                                             // if recurring, add the full path
                                             $this->pattern_file_matches[$dir_name . $file] = @filemtime($dir_name . $file);
                                         } else {
                                             // if not recurring, add just base path, without dirname prefix
                                             $this->pattern_file_matches[$file] = @filemtime($dir_name . $file);
                                         }
                                         //end if else
                                     }
                                     //end if
                                     //--
                                 }
                                 //end if
                                 //--
                             }
                             //end else
                             //--
                         } else {
                             //-- link
                             if ($tmp_allow_addition) {
                                 //--
                                 $link_result = SmartFileSystem::link_get_origin($dir_name . $file);
                                 //--
                                 if (empty($link_result) or (string) $link_result == '' or !SmartFileSystem::file_or_link_exists($link_result)) {
                                     //--
                                     // case of readlink error ..., not includding broken links, they are useless
                                     //--
                                 } else {
                                     //--
                                     $tmp_size_arr = array();
                                     $tmp_fsize = 0;
                                     //$tmp_size_arr = (array) @lstat($dir_name.$file);
                                     //$tmp_fsize = Smart::format_number_int($tmp_size_arr[7],'+'); // $tmp_size_arr[7] -> size, but may break compare if on a different file system or in distributed storage on various OS
                                     //--
                                     $this->num_links++;
                                     //--
                                     if (file_exists($dir_name . $file)) {
                                         // here file_exists must be tested because if broken link not stat on it (filemtime) to avoid log un-necessary errors
                                         //-- bugfix: not if broken link
                                         $this->num_size += $tmp_fsize;
                                         if ($tmp_add_pattern) {
                                             if (is_dir($dir_name . $file)) {
                                                 $this->num_dirs++;
                                                 $this->num_dirs_size += $tmp_fsize;
                                                 if ($recurring) {
                                                     // if recurring, add the full path
                                                     $this->pattern_dir_matches[$dir_name . $file] = @filemtime($dir_name . $file);
                                                 } else {
                                                     // if not recurring, add just base path, without dirname prefix
                                                     $this->pattern_dir_matches[$file] = @filemtime($dir_name . $file);
                                                 }
                                                 //end if else
                                             } else {
                                                 $this->num_files++;
                                                 $this->num_files_size += $tmp_fsize;
                                                 if ($recurring) {
                                                     // if recurring, add the full path
                                                     $this->pattern_file_matches[$dir_name . $file] = @filemtime($dir_name . $file);
                                                 } else {
                                                     // if not recurring, add just base path, without dirname prefix
                                                     $this->pattern_file_matches[$file] = @filemtime($dir_name . $file);
                                                 }
                                                 //end if else
                                             }
                                             //end if else
                                         }
                                         //end if
                                         //--
                                     }
                                     //end if
                                     //--
                                     $tmp_fsize = 0;
                                     $tmp_size_arr = array();
                                     //--
                                 }
                                 //end if else
                                 //--
                             }
                             //end if
                             //--
                         }
                         //end if else
                         //--
                     }
                     //end if
                     //--
                 }
                 //end if(. ..)
                 //--
             }
             //end while
             //---------------------------------------
             @closedir($handle);
             //---------------------------------------
         } else {
             //---------------------------------------
             $this->errors_arr[] = $dir_name;
             //---------------------------------------
         }
         //end else
         //--
     } else {
         //---------------------------------------
         // nothing ...
         //---------------------------------------
     }
     //end if else
     //--
 }
Пример #5
0
 private static function load_subtemplates($y_use_caching, $y_base_path, $mtemplate, $y_arr_vars_sub_templates, $cycles = 0, $process_sub_sub_templates = true)
 {
     //--
     $y_use_caching = (string) $y_use_caching;
     $y_base_path = (string) $y_base_path;
     $mtemplate = (string) $mtemplate;
     $y_arr_vars_sub_templates = (array) $y_arr_vars_sub_templates;
     $cycles = (int) $cycles;
     //--
     if ((string) $y_base_path == '') {
         Smart::log_warning('Marker Template Load Sub-Templates: INVALID Base Path (Empty) ... / Template: ' . $mtemplate);
         return 'Marker Template Load Sub-Templates: INVALID Base Path (Empty). See the ErrorLog for Details.';
     }
     //end if
     //--
     if (Smart::array_size($y_arr_vars_sub_templates) > 0) {
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             $bench = microtime(true);
         }
         //end if
         //--
         foreach ($y_arr_vars_sub_templates as $key => $val) {
             //--
             $key = (string) $key;
             $val = (string) $val;
             //--
             if ((string) $key != '' and strpos($key, '..') === false and strpos($val, '..') === false and preg_match('/^[a-zA-Z0-9_\\-\\.\\/\\!%]+$/', $key)) {
                 //--
                 if ((string) $val == '') {
                     //--
                     $mtemplate = str_replace('[@@@@SUB-TEMPLATE:' . $key . '@@@@]', '', (string) $mtemplate);
                     //--
                     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                         SmartFrameworkRegistry::setDebugMsg('extra', 'SMART-TEMPLATING', ['title' => '[TPL-Parsing:Load] :: Markers-Templating / Skipping Sub-Template File: Key=' . $key . ' ; *Path=' . $val . ' ; Cycle=' . $cycles, 'data' => 'Unset based on empty Path value ...']);
                     }
                     //end if
                     //--
                 } else {
                     //--
                     if (substr($key, 0, 1) == '%' and substr($key, -1, 1) == '%') {
                         // variable, only can be set programatically, full path to the template file is specified
                         if (substr($val, 0, 2) == '@/') {
                             // use a path suffix relative path to parent template, starting with @/ ; otherwise the full relative path is expected
                             $val = (string) SmartFileSysUtils::add_dir_last_slash((string) $y_base_path) . substr($val, 2);
                         }
                         //end if
                         $stpl_path = (string) $val;
                     } elseif (strpos($key, '%') !== false) {
                         // % is not valid in other circumstances
                         Smart::log_warning('Invalid Markers-Sub-Template Syntax [%] as: ' . $key);
                         return 'Invalid Markers-Sub-Template Syntax. See the ErrorLog for Details.';
                     } elseif (substr($key, 0, 1) == '!' and substr($key, -1, 1) == '!') {
                         // path override: use this relative path instead of parent relative referenced path ; Ex: [@@@@SUB-TEMPLATE:!etc/templates/default/js-base.inc.htm!@@@@]
                         $stpl_path = (string) substr($key, 1, -1);
                     } elseif (strpos($key, '!') !== false) {
                         // ! is not valid in other circumstances
                         Smart::log_warning('Invalid Markers-Sub-Template Syntax [!] as: ' . $key);
                         return 'Invalid Markers-Sub-Template Syntax. See the ErrorLog for Details.';
                     } else {
                         if ((string) $val == '@') {
                             // use the same dir as parent
                             $val = (string) $y_base_path;
                         } elseif (substr($val, 0, 2) == '@/') {
                             // use a path suffix relative to parent template, starting with @/
                             $val = (string) SmartFileSysUtils::add_dir_last_slash((string) $y_base_path) . substr($val, 2);
                         }
                         //end if
                         $stpl_path = (string) SmartFileSysUtils::add_dir_last_slash($val) . $key;
                     }
                     //end if else
                     //--
                     if (!is_file((string) $stpl_path)) {
                         Smart::log_warning('Invalid Markers-Sub-Template File: ' . $stpl_path);
                         return 'Invalid Markers-Sub-Template File. See the ErrorLog for Details.';
                     }
                     //end if
                     //--
                     $stemplate = (string) self::read_template_or_subtemplate_file((string) $stpl_path, (string) $y_use_caching);
                     // read
                     if ($process_sub_sub_templates === true) {
                         $arr_sub_sub_templates = (array) self::detect_subtemplates((string) $stemplate);
                         // detect sub-sub templates
                         $num_sub_sub_templates = Smart::array_size($arr_sub_sub_templates);
                         if ($num_sub_sub_templates > 0) {
                             $stemplate = (string) self::load_subtemplates((string) $y_use_caching, $y_base_path, $stemplate, $arr_sub_sub_templates, $cycles, false);
                             // this is level 3 !!
                             $cycles += $num_sub_sub_templates;
                         }
                         //end if
                     }
                     //end if
                     $stemplate = str_replace(array('[@@@@', '@@@@]'), array('(@@@@-', '-@@@@)'), (string) $stemplate);
                     // protect against cascade recursion or undefined sub-templates
                     $mtemplate = str_replace('[@@@@SUB-TEMPLATE:' . $key . '@@@@]', (string) $stemplate, (string) $mtemplate);
                     // do replacements
                     $arr_sub_sub_templates = array();
                     $num_sub_sub_templates = 0;
                     //--
                     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                         SmartFrameworkRegistry::setDebugMsg('extra', 'SMART-TEMPLATING', ['title' => '[TPL-Parsing:Load] :: Markers-Templating / Loading Sub-Template File: Key=' . $key . ' ; Path=' . $stpl_path . ' ; Cycle=' . $cycles, 'data' => 'Content: ' . "\n" . SmartParser::text_endpoints($stemplate, 255)]);
                     }
                     //end if
                     //--
                     $stemplate = '';
                     //--
                 }
                 //end if else
                 //--
             } else {
                 // invalid key
                 //--
                 Smart::log_warning('Invalid Markers-Sub-Template Key: ' . $key . ' or Value: ' . $val);
                 //--
             }
             //end if else
             //--
             $cycles++;
             if ($cycles > 255) {
                 // protect against infinite loop, max 255 loops (incl. sub-sub templates) :: hard limit
                 Smart::log_warning('Inclusion of the Sub-Template: ' . $stpl_path . ' failed as it overflows the maximum hard limit: only 255 loops (sub-templates) are allowed. Current Cycle is: #' . $cycles);
                 break;
             }
             //end if
             //--
         }
         //end foreach
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             $bench = Smart::format_number_dec((double) (microtime(true) - (double) $bench), 9, '.', '');
             SmartFrameworkRegistry::setDebugMsg('extra', 'SMART-TEMPLATING', ['title' => '[TPL-Parsing:Load.DONE] :: Markers-Templating / Loading Sub-Templates Completed ; Time = ' . $bench . ' sec.', 'data' => 'Total Cycles: ' . $cycles]);
         }
         //end if
         //--
     }
     //end if
     //--
     if (self::have_subtemplate((string) $mtemplate) === true) {
         Smart::log_warning('Undefined Marker Sub-Templates detected in Template:' . "\n" . self::log_template($mtemplate));
         $mtemplate = str_replace(array('[@@@@', '@@@@]'), array('(@@@@-', '-@@@@)'), (string) $mtemplate);
         // finally protect against undefined sub-templates
     }
     //end if
     //--
     return (string) $mtemplate;
     //--
 }
Пример #6
0
 public static function open($file_name, $timeout_busy_sec = 60)
 {
     //--
     global $configs;
     //-- check if available
     self::check_is_available();
     //-- path protection
     SmartFileSysUtils::raise_error_if_unsafe_path($file_name);
     //--
     if (strlen($file_name) <= 1) {
         self::error((string) $file_name, 'OPEN', 'ERROR: DB name is empty !', '', '');
         return;
     }
     //end if
     //--
     $dir_of_db = Smart::dir_name($file_name);
     //--
     if (!is_dir($dir_of_db)) {
         self::error((string) $file_name, 'OPEN', 'ERROR: DB folder does not exists !', '', '');
         return;
     }
     //end if
     //--
     if (!is_writable($dir_of_db)) {
         self::error((string) $file_name, 'OPEN', 'ERROR: DB folder is not writable !', '', '');
         return;
     }
     //end if
     //-- open DB connection
     try {
         //--
         $db = @new SQLite3($file_name, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
         //--
         $db->busyTimeout((int) $timeout_busy_sec * 1000);
         // $timeout_busy_sec is in seconds ; we set a busy timeout in miliseconds
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             //--
             $arr_version = @$db->version();
             //--
             if (!is_array($arr_version)) {
                 $arr_version = array();
             }
             //end if
             //--
             SmartFrameworkRegistry::setDebugMsg('db', 'sqlite|log', ['type' => 'metainfo', 'data' => 'SQLite Library Version: ' . $arr_version['versionString'] . ' / ' . $arr_version['versionNumber']]);
             //--
             if ((double) $configs['sqlite']['slowtime'] > 0) {
                 self::$slow_time = (double) $configs['sqlite']['slowtime'];
             }
             //end if
             if (self::$slow_time < 1.0E-7) {
                 self::$slow_time = 1.0E-7;
             } elseif (self::$slow_time > 0.9999999000000001) {
                 self::$slow_time = 0.9999999000000001;
             }
             //end if
             //--
             SmartFrameworkRegistry::setDebugMsg('db', 'sqlite|slow-time', number_format(self::$slow_time, 7, '.', ''), '=');
             SmartFrameworkRegistry::setDebugMsg('db', 'sqlite|log', ['type' => 'metainfo', 'data' => 'Fast Query Reference Time < ' . self::$slow_time . ' seconds']);
             //--
         }
         //end if
         //--
     } catch (Exception $e) {
         //--
         self::error((string) $file_name, 'OPEN', $e->getMessage(), 'Catch Exception ...', '');
         return;
         //--
     }
     //end try catch
     //--
     if (is_file($file_name)) {
         @chmod($file_name, SMART_FRAMEWORK_CHMOD_FILES);
     }
     //end if
     //--
     self::check_connection($db);
     //--
     SmartFrameworkRegistry::$Connections['sqlite'][(string) self::get_connection_id($db)] = (string) $file_name;
     //--
     if (@$db->lastErrorCode() !== 0) {
         $sqlite_error = 'SQLite3-ERR:: ' . @$db->lastErrorMsg();
         self::error((string) $file_name, 'OPEN', 'Failed to Open DB File', $file_name . "\n" . 'ERR: ' . $sqlite_error, $file_name);
         return;
     }
     //end if
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         SmartFrameworkRegistry::setDebugMsg('db', 'sqlite|log', ['type' => 'open-close', 'data' => 'Open SQLite Database: ' . $file_name]);
     }
     //end if
     //-- create the first time table to record the sqlite version
     if (!self::check_if_table_exists($db, '_smartframework_metadata')) {
         self::create_table($db, '_smartframework_metadata', 'id VARCHAR(255) PRIMARY KEY UNIQUE, description TEXT');
         self::write_data($db, 'INSERT INTO _smartframework_metadata (id, description) VALUES (\'sqlite-version\', \'' . self::escape_str($db, '3') . '\')');
         self::write_data($db, 'INSERT INTO _smartframework_metadata (id, description) VALUES (\'smartframework-version\', \'' . self::escape_str($db, (string) SMART_FRAMEWORK_VERSION) . '\')');
         self::write_data($db, 'INSERT INTO _smartframework_metadata (id, description) VALUES (\'creation-date-and-time\', \'' . self::escape_str($db, (string) date('Y-m-d H:i:s O')) . '\')');
         self::write_data($db, 'INSERT INTO _smartframework_metadata (id, description) VALUES (\'database-name\', \'' . self::escape_str($db, (string) $file_name) . '\')');
         self::write_data($db, 'INSERT INTO _smartframework_metadata (id, description) VALUES (\'domain-realm-id\', \'' . self::escape_str($db, (string) SMART_SOFTWARE_NAMESPACE) . '\')');
     }
     //end if
     //--
     return $db;
     //--
 }
 public static function apply_watermark($imagePath, $watermarkPath, $quality, $gravity)
 {
     //-- check for required extension
     self::check_gd_truecolor();
     //--
     //--
     SmartFileSysUtils::raise_error_if_unsafe_path($imagePath);
     SmartFileSysUtils::raise_error_if_unsafe_path($watermarkPath);
     //--
     //--
     $imagePath = (string) $imagePath;
     $watermarkPath = (string) $watermarkPath;
     //--
     //--
     if (is_file($imagePath) and is_file($watermarkPath)) {
         //--
         $arr_imgsize = (array) @getimagesize($watermarkPath);
         $wtmW = (int) $arr_imgsize[0];
         $wtmH = (int) $arr_imgsize[1];
         $t_wtm = (int) $arr_imgsize[2];
         // OK
         unset($arr_imgsize);
         //--
         if ($t_wtm <= 0) {
             Smart::log_notice('Media Gallery // SmartGdImageProcess // Watermark :: Unknown Type [W]: ' . $watermarkPath);
             return 1;
             // not ok (unknown type)
         }
         //end if
         $t_wtm = (string) @image_type_to_mime_type((int) $t_wtm);
         // OK
         //--
         switch ((string) $t_wtm) {
             case 'image/png':
             case 'image/x-png':
                 $watermark = @imagecreatefrompng($watermarkPath);
                 break;
             case 'image/gif':
                 $watermark = @imagecreatefromgif($watermarkPath);
                 break;
             case 'image/pjpeg':
             case 'image/jpeg':
             case 'image/jpg':
                 $watermark = @imagecreatefromjpeg($watermarkPath);
                 break;
             default:
                 Smart::log_notice('Media Gallery // SmartGdImageProcess // Watermark :: Unsupported Type [W] (not PNG/GIF/JPEG ; Type=' . $t_wtm . '): ' . $watermarkPath);
                 return 1;
                 // not ok (invalid type)
         }
         //end switch
         //--
         if (!is_resource($watermark)) {
             // if the immage is corrupt or invalid ...
             Smart::log_warning('Media Gallery // SmartGdImageProcess // Watermark :: Source Watermark Image Failure: ' . $watermarkPath);
             return 2;
             // not ok (there was an error reading the image / have no privileges / or may be an invalid image type)
         }
         //end if
         //--
         //--
         $arr_imgsize = (array) @getimagesize($imagePath);
         $imgW = (int) $arr_imgsize[0];
         $imgH = (int) $arr_imgsize[1];
         $t_img = (int) $arr_imgsize[2];
         // OK
         unset($arr_imgsize);
         //--
         if ($t_img <= 0) {
             Smart::log_notice('Media Gallery // SmartGdImageProcess // Watermark :: Unknown Type [I]: ' . $imagePath);
             return 3;
             // not ok (unknown type)
         }
         //end if
         $t_img = (string) @image_type_to_mime_type((int) $t_img);
         // OK
         //--
         switch ((string) $t_img) {
             case 'image/png':
             case 'image/x-png':
                 $the_type = 'png';
                 $source = @imagecreatefrompng($imagePath);
                 break;
             case 'image/gif':
                 $the_type = 'gif';
                 $source = @imagecreatefromgif($imagePath);
                 break;
             case 'image/pjpeg':
             case 'image/jpeg':
             case 'image/jpg':
                 $the_type = 'jpg';
                 $source = @imagecreatefromjpeg($imagePath);
                 break;
             default:
                 Smart::log_notice('Media Gallery // SmartGdImageProcess // Watermark :: Unsupported Type [I] (not PNG/GIF/JPEG ; Type=' . $t_img . '): ' . $imagePath);
                 return 3;
                 // not ok (invalid type)
         }
         //end switch
         //--
         if (!is_resource($source)) {
             // if the immage is corrupt or invalid ...
             Smart::log_warning('Media Gallery // SmartGdImageProcess // Watermark :: Source Image Failure: ' . $watermarkPath);
             return 4;
             // not ok (there was an error reading the image / have no privileges / or may be an invalid image type)
         }
         //end if
         //--
         //-- apply watermark
         switch ((string) $gravity) {
             // {{{SYNC-GRAVITY}}}
             case 'northwest':
                 $gravityX = 0;
                 $gravityY = 0;
                 break;
             case 'northeast':
                 $gravityX = ceil($imgW - $wtmW);
                 $gravityY = 0;
                 break;
             case 'southwest':
                 $gravityX = 0;
                 $gravityY = ceil($imgH - $wtmH);
                 break;
             case 'southeast':
                 $gravityX = ceil($imgW - $wtmW);
                 $gravityY = ceil($imgH - $wtmH);
                 break;
             case 'center':
             default:
                 $gravityX = ceil($imgW / 2 - $wtmW / 2);
                 $gravityY = ceil($imgH / 2 - $wtmH / 2);
         }
         //end switch
         //--
         @imagecopy($source, $watermark, $gravityX, $gravityY, 0, 0, $wtmW, $wtmH);
         //--
         //-- saving new image
         switch ((string) $the_type) {
             case 'png':
                 @imagepng($source, $imagePath);
                 break;
             case 'gif':
                 @imagegif($source, $imagePath);
                 break;
             case 'jpg':
                 @imagejpeg($source, $imagePath, $quality);
                 // preserve 100% quality for jpeg
                 break;
             default:
                 // this should not happen, it is catched above
         }
         //end switch
         //--
         //--
         @imagedestroy($source);
         @imagedestroy($watermark);
         //--
         //--
         return 0;
         // OK
         //--
     }
     //end if else
     //--
     //--
     return -1;
     // not ok, files do not exists / not files / invalid paths provided
     //--
 }
    public static function test_fs()
    {
        //--
        if (SMART_FRAMEWORK_TESTUNIT_ALLOW_FS_TESTS !== true) {
            return SmartComponents::operation_notice('Test Unit File System Tests are DISABLED ...');
        }
        //end if
        //--
        //--
        $time = microtime(true);
        //--
        //--
        $err = '';
        $tests = array();
        //--
        //--
        if ((string) DIRECTORY_SEPARATOR != '\\') {
            // broken links do not work on Windows !
            $tests[] = '##### FileSystem OPERATIONS / TESTS - ALL: #####';
        } else {
            $tests[] = '##### FileSystem OPERATIONS / TESTS *** PARTIAL SUPPORT ONLY (BY PLATFORM) ***: #####';
        }
        //end if else
        //--
        //--
        $test_string = '#START#' . "\n" . 'グッド' . "\n" . 'SmartFramework/Test/FileSystem' . "\n" . time() . "\n" . SMART_FRAMEWORK_HTACCESS_NOINDEXING . SMART_FRAMEWORK_HTACCESS_FORBIDDEN . SMART_FRAMEWORK_HTACCESS_NOEXECUTION . "\n" . '#END#';
        $test_str_cksum = SmartHashCrypto::sha512($test_string);
        $long_prefixed = SmartFileSysUtils::prefixed_sha1_path(sha1(time()));
        $short_prefixed = SmartFileSysUtils::prefixed_uuid10_dir(Smart::uuid_10_seq());
        //--
        $the_base_folder = 'tmp/tests/';
        $the_sufx_folder = 'Folder1';
        $the_base_file = 'NORMAL-Write_123_@#.txt';
        //--
        $the_folder = $the_base_folder . $the_sufx_folder . '/';
        $the_copy_folder = $the_base_folder . 'folder2';
        $the_move_folder = $the_base_folder . 'FOLDER3';
        $the_extra_folder = $the_folder . 'extra/';
        $the_file = $the_folder . $the_base_file;
        //--
        $get_folder = SmartFileSysUtils::add_dir_last_slash(SmartFileSysUtils::get_dir_from_path($the_folder));
        $get_file = SmartFileSysUtils::get_file_name_from_path($the_file);
        $get_xfile = SmartFileSysUtils::get_noext_file_name_from_path($the_file);
        $get_ext = SmartFileSysUtils::get_file_extension_from_path($the_file);
        //--
        $the_copy_file = $the_file . '.copy.txt';
        $the_move_file = $the_extra_folder . $the_base_file . '.copy.moved.txt';
        $the_broken_link = $the_extra_folder . 'a-broken-link';
        $the_broken_dir_link = $the_extra_folder . 'a-broken-dir-link';
        $the_good_link = $the_extra_folder . 'a-good-link';
        $the_good_dir_link = $the_extra_folder . 'a-good-dir-link';
        //--
        //--
        $tests[] = 'INITIAL-FOLDER: ' . $get_folder;
        $tests[] = 'NEW-FOLDER: ' . $the_folder;
        $tests[] = 'NEW-FILE: ' . $the_file;
        //--
        //--
        if ((string) $err == '') {
            $the_test = 'CHECK TEST SAFE PATH NAME: DIR / FILE ...';
            $tests[] = $the_test;
            if ((string) Smart::safe_pathname((string) $get_folder) !== (string) $get_folder or (string) Smart::safe_pathname((string) $the_copy_file) !== (string) $the_copy_file) {
                $err = 'ERROR: SAFE PATH NAME TEST ... FAILED !!!';
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'CHECK TEST ABSOLUTE / BACKWARD PATHS ...';
            $tests[] = $the_test;
            if (!SmartFileSysUtils::check_file_or_dir_name('/this/is/absolute', 'no') or SmartFileSysUtils::check_file_or_dir_name('/this/is/absolute') or SmartFileSysUtils::check_file_or_dir_name('/this/is/../backward/path')) {
                $err = 'ERROR: CHECK TEST ABSOLUTE / BACKWARD PATHS ... FAILED !!!';
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'CHECK EXTRACT FOLDER FROM PATH ...';
            $tests[] = $the_test;
            if ((string) $get_folder != SmartFileSysUtils::add_dir_last_slash(Smart::dir_name($the_folder))) {
                $err = 'ERROR: Path Extraction FAILED: Dir=' . $get_folder . ' ; DirName=' . SmartFileSysUtils::add_dir_last_slash(Smart::dir_name($the_folder));
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'CHECK EXTRACT FILE AND EXTENSION FROM PATH (1) ...';
            $tests[] = $the_test;
            if ((string) $get_folder . SmartFileSysUtils::add_dir_last_slash($the_sufx_folder) . $get_file != $the_file) {
                $err = 'ERROR :: Path Extraction FAILED: Re-Composed-File=' . $get_folder . SmartFileSysUtils::add_dir_last_slash($the_sufx_folder) . $get_file . ' ; File=' . $the_file;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'CHECK EXTRACT FILE AND EXTENSION FROM PATH (2) ...';
            $tests[] = $the_test;
            if ((string) $get_file != $get_xfile . '.' . $get_ext) {
                $err = 'ERROR :: Path Extraction FAILED: File=' . $get_file . ' ; XFile=' . $get_xfile . ' ; Ext=' . $get_ext;
            }
            //end if
        }
        //end if
        //--
        SmartFileSysUtils::raise_error_if_unsafe_path($the_folder);
        if ((string) $err == '') {
            $the_test = 'CHECK PATH NAME DIR: check_file_or_dir_name() : ' . $the_folder;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSysUtils::check_file_or_dir_name($the_folder);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        SmartFileSysUtils::raise_error_if_unsafe_path($the_file);
        if ((string) $err == '') {
            $the_test = 'CHECK PATH NAME FILE: check_file_or_dir_name() : ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSysUtils::check_file_or_dir_name($the_file);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        //--
        if ((string) $err == '') {
            $parent_folder = SmartFileSysUtils::add_dir_last_slash('');
            $the_test = 'Check Add Dir Last (trailing) Slash: Empty Folder Name';
            $tests[] = $the_test;
            if ((string) $parent_folder != './') {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $parent_folder = SmartFileSysUtils::add_dir_last_slash('.');
            $the_test = 'Check Add Dir Last (trailing) Slash: Dot Folder Name: ' . $parent_folder;
            $tests[] = $the_test;
            if ((string) $parent_folder != './') {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $parent_folder = SmartFileSysUtils::add_dir_last_slash('./');
            $the_test = 'Check Add Dir Last (trailing) Slash: DotSlash Folder Name: ' . $parent_folder;
            $tests[] = $the_test;
            if ((string) $parent_folder != './') {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $parent_folder = SmartFileSysUtils::add_dir_last_slash(Smart::dir_name($the_base_folder));
            $the_test = 'Check Parent Dir Name with Add Dir Last (trailing) Slash: ' . $parent_folder . ' # from: ' . $the_base_folder;
            $tests[] = $the_test;
            if ((string) $parent_folder != 'tmp/') {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        //--
        if ((string) $err == '') {
            if (is_dir($get_folder)) {
                $the_test = 'DIR DELETE - INIT CLEANUP: dir_delete() + recursive: ' . $get_folder;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::dir_delete($the_base_folder, true);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            } else {
                $tests[] = 'DIR DELETE - INIT CLEANUP: Test Not Run (folder does not exists): ' . $get_folder;
            }
            //end if else
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'DIR CREATE RECURSIVE: dir_recursive_create() : ' . $the_folder . $long_prefixed . $short_prefixed;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::dir_recursive_create($the_folder . $long_prefixed . $short_prefixed);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'DIR CREATE NON-RECURSIVE: dir_create() : extra/ in : ' . $the_extra_folder;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::dir_recursive_create($the_extra_folder);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        if ((string) DIRECTORY_SEPARATOR != '\\') {
            // broken links do not work on Windows !
            if ((string) $err == '') {
                $the_test = 'CREATE BROKEN FILE LINK FOR DELETION (1): link_create() : as : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::link_create('tmp/cache', $the_broken_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'DELETE BROKEN FILE LINK (1): delete() : as : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::delete($the_broken_link);
                if ($result !== 1 || is_link($the_broken_link)) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'CREATE BROKEN FILE LINK FOR DELETION (2): link_create() : as : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::link_create('tmp/index.html', $the_broken_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'DELETE BROKEN FILE LINK (2): dir_delete() : as : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::dir_delete($the_broken_link);
                if ($result !== 1 || is_link($the_broken_link)) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'CREATE BROKEN FILE LINK: link_create() : as : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::link_create('tmp/index.html', $the_broken_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'CREATE BROKEN DIR LINK: link_create() : as : ' . $the_broken_dir_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::link_create('tmp/', $the_broken_dir_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'CREATE A FILE LINK: link_create() : as : ' . $the_good_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::link_create(Smart::real_path('tmp/index.html'), $the_good_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'CREATE A DIR LINK: link_create() : as : ' . $the_good_dir_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::link_create(Smart::real_path('tmp/'), $the_good_dir_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'FILE WRITE with empty content: write() : ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::write($the_file, '');
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE WRITE: write() / before append : ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::write($the_file, $test_string);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE WRITE: write() +append : ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::write($the_file, $test_string, 'a');
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE READ / Append: read() Full Size: ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::read($the_file);
            if ((string) SmartHashCrypto::sha512($result) != (string) SmartHashCrypto::sha512($test_string . $test_string)) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE WRITE: re-write() : ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::write($the_file, $test_string);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        if ((string) DIRECTORY_SEPARATOR != '\\') {
            // broken links do not work on Windows !
            if ((string) $err == '') {
                $the_test = 'FILE WRITE TO A BROKEN LINK: write() : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::write($the_broken_link, $test_string);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'DELETE THE BROKEN LINK AFTER write() and RE-CREATE IT : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::delete($the_broken_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'RE-CREATE BROKEN FILE LINK [AFTER WRITE]: link_create() : as : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::link_create('tmp/index.html', $the_broken_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'FILE WRITE: write_if_not_exists() with Content Compare to a broken link : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::write_if_not_exists($the_broken_link, $test_string, 'yes');
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'DELETE THE BROKEN LINK AFTER write_if_not_exists() and RE-CREATE IT : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::delete($the_broken_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
            if ((string) $err == '') {
                $the_test = 'RE-CREATE BROKEN FILE LINK [AFTER WRITE-IF-NOT-EXISTS]: link_create() : as : ' . $the_broken_link;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::link_create('tmp/index.html', $the_broken_link);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'FILE WRITE: write_if_not_exists() without Content Compare : ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::write_if_not_exists($the_file, $test_string, 'no');
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'FILE READ: read() Full Size: ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::read($the_file);
            if ((string) SmartHashCrypto::sha512($result) != (string) $test_str_cksum) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE READ: read() Partial Size, First 10 bytes: ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::read($the_file, 10);
            if ((string) sha1($result) != (string) sha1(substr($test_string, 0, 10))) {
                // here we read bytes so substr() not SmartUnicode::sub_str() should be used
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'FILE STATIC-READ: staticread() Full Size: ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::staticread($the_file);
            if ((string) SmartHashCrypto::sha512($result) != (string) $test_str_cksum) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE STATIC-READ: staticread() Partial Size, First 10 bytes: ' . $the_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::staticread($the_file, 10);
            if ((string) sha1($result) != (string) sha1(substr($test_string, 0, 10))) {
                // here we read bytes so substr() not SmartUnicode::sub_str() should be used
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'FILE COPY: copy() : ' . $the_file . ' to: ' . $the_copy_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::copy($the_file, $the_copy_file);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE COPY with OVERWRITE: copy() : ' . $the_file . ' to: ' . $the_copy_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::copy($the_file, $the_copy_file, true);
            // overwrite destination file(s)
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE RE-COPY (test should re-write the destination): copy() : ' . $the_file . ' to: ' . $the_move_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::copy($the_file, $the_move_file);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            } else {
                $the_test = 'FILE DELETE: delete() : ' . $the_move_file;
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::delete($the_move_file);
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'FILE RENAME/MOVE: rename() : ' . $the_copy_file . ' to: ' . $the_move_file;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::rename($the_copy_file, $the_move_file);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            if (is_dir('__development/')) {
                //--
                $the_test = 'RECURSIVE COPY (CLONE) DIR [DEVELOPMENT]: dir_copy() : ' . '__development/' . ' to: ' . $the_folder . '__development';
                $tests[] = $the_test;
                $result = 0;
                $result = SmartFileSystem::dir_copy('__development/', $the_folder . '__development');
                if ($result !== 1) {
                    $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
                }
                //end if
                //--
                if ((string) $err == '') {
                    $the_test = 'DIR COMPARE THE [DEVELOPMENT] SOURCE WITH [DEVELOPMENT] DESTINATION AFTER DIR COPY AND DIR MOVE:' . "\n" . 'compare_folders() : ' . '__development/' . ' with: ' . $the_folder . '__development/';
                    $tests[] = $the_test;
                    $arr_diff = array();
                    $arr_diff = SmartFileSystem::compare_folders('__development', $the_folder . '__development', true, true);
                    if (Smart::array_size($arr_diff) > 0) {
                        $err = 'ERROR :: ' . $the_test . ' #DIFFERENCES=' . print_r($arr_diff, 1);
                    }
                    //end if
                }
                //end if
                //--
            } else {
                $tests[] = 'RECURSIVE COPY (CLONE) DIR [DEVELOPMENT]: Test Not Run (Development environment not detected) ...';
            }
            //end if else
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'RECURSIVE COPY (CLONE) DIR: dir_copy() : ' . $the_folder . ' to: ' . $the_copy_folder;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::dir_copy($the_folder, $the_copy_folder);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'MOVE/RENAME DIR: dir_rename() : ' . $the_copy_folder . ' to: ' . $the_move_folder;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::dir_rename($the_copy_folder, $the_move_folder);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'DIR COMPARE THE SOURCE WITH DESTINATION AFTER DIR COPY AND DIR MOVE: ' . $the_folder . ' with: ' . $the_move_folder;
            $tests[] = $the_test;
            $arr_diff = array();
            $arr_diff = SmartFileSystem::compare_folders($the_folder, $the_move_folder, true, true);
            if (Smart::array_size($arr_diff) > 0) {
                $err = 'ERROR :: ' . $the_test . ' #DIFFERENCES=' . print_r($arr_diff, 1);
            }
            //end if
        }
        //end if
        //--
        if ((string) $err == '') {
            $the_test = 'DIR DELETE - SIMPLE: dir_delete() non-recursive: ' . $the_extra_folder;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::dir_delete($the_extra_folder, false);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        if ((string) $err == '') {
            $the_test = 'DIR DELETE - LAST CLEANUP: dir_delete() + recursive: ' . $get_folder;
            $tests[] = $the_test;
            $result = 0;
            $result = SmartFileSystem::dir_delete($the_base_folder, true);
            if ($result !== 1) {
                $err = 'ERROR :: ' . $the_test . ' #RESULT=' . $result;
            }
            //end if
        }
        //end if
        //--
        //--
        $time = 'TOTAL TIME was: ' . (microtime(true) - $time);
        //--
        //--
        $end_tests = '##### END TESTS ... ' . $time . ' sec. #####';
        //--
        //--
        if ((string) $err == '') {
            $img_sign = 'lib/core/img/sign_info.png';
            $img_check = 'lib/core/img/q_completed.png';
            $text_main = Smart::escape_js('<span style="color:#83B953;">Good ... Perfect &nbsp;&nbsp;&nbsp; :: &nbsp;&nbsp;&nbsp; グッド ... パーフェクト</span>');
            $text_info = Smart::escape_js('<h2><span style="color:#83B953;">All</span> the SmartFramework FS Operations <span style="color:#83B953;">Tests PASSED on PHP</span><hr></h2><span style="font-size:14px;">' . Smart::nl_2_br(Smart::escape_html(implode("\n" . '* ', $tests) . "\n" . $end_tests)) . '</span>');
        } else {
            $img_sign = 'lib/core/img/sign_error.png';
            $img_check = 'lib/core/img/q_warning.png';
            $text_main = Smart::escape_js('<span style="color:#FF5500;">An ERROR occured ... &nbsp;&nbsp;&nbsp; :: &nbsp;&nbsp;&nbsp; エラーが発生しました ...</span>');
            $text_info = Smart::escape_js('<h2><span style="color:#FF5500;">A test FAILED</span> when testing FS Operations.<span style="color:#FF5500;"><hr>FAILED Test Details</span>:</h2><br><h3>' . Smart::escape_html($tests[Smart::array_size($tests) - 1]) . '</h3><br><span style="font-size:14px;"><pre>' . Smart::escape_html($err) . '</pre></span>');
        }
        //end if else
        //--
        //--
        $html = <<<HTML
<h1>SmartFramework LibFileSystem Tests: DONE ... [ Time: {$time} sec. ]</h1>
<script type="text/javascript">
\tSmartJS_BrowserUtils.alert_Dialog(
\t\t'<img src="{$img_sign}" align="right"><h1>{$text_main}</h1><hr><span style="color:#333333;"><img src="{$img_check}" align="right">{$text_info}<br>',
\t\t'',
\t\t'FileSystem Operations Test Suite for SmartFramework: PHP',
\t\t'920',
\t\t'480'
\t);
</script>
HTML;
        //--
        //--
        return $html;
        //--
    }
Пример #9
0
 public static final function DownloadsHandler($encrypted_download_pack, $controller_key)
 {
     //--
     $encrypted_download_pack = (string) $encrypted_download_pack;
     $controller_key = (string) $controller_key;
     //--
     $client_signature = SmartUtils::get_visitor_signature();
     //--
     if ((string) SMART_APP_VISITOR_COOKIE == '') {
         Smart::log_info('File Download', 'Failed: 400 / Invalid Visitor Cookie' . ' on Client: ' . $client_signature);
         self::Raise400Error('ERROR: Invalid Visitor UUID. Cookies must be enabled to enable this feature !');
         return '';
     }
     //end if
     //--
     $downloaded_file = '';
     // init
     //--
     $decoded_download_packet = (string) trim((string) SmartUtils::crypto_decrypt((string) $encrypted_download_pack, 'SmartFramework//DownloadLink' . SMART_FRAMEWORK_SECURITY_KEY));
     //--
     if ((string) $decoded_download_packet != '') {
         // if data is corrupted, decrypt checksum does not match, will return an empty string
         //--
         if (SMART_FRAMEWORK_ADMIN_AREA === true) {
             // {{{SYNC-DWN-CTRL-PREFIX}}}
             $controller_key = (string) 'AdminArea/' . $controller_key;
         } else {
             $controller_key = (string) 'IndexArea/' . $controller_key;
         }
         //end if
         //-- {{{SYNC-DOWNLOAD-ENCRYPT-ARR}}}
         $arr_metadata = explode("\n", (string) $decoded_download_packet, 6);
         // only need first 5 parts
         //print_r($arr_metadata);
         // #PACKET-STRUCTURE# [we will have an array like below, according with the: SmartUtils::create_download_link()]
         // [TimedAccess]\n
         // [FilePath]\n
         // [AccessKey]\n
         // [UniqueKey]\n
         // [SFR.UA]\n
         // #END#
         //--
         $crrtime = (string) trim((string) $arr_metadata[0]);
         $filepath = (string) trim((string) $arr_metadata[1]);
         $access_key = (string) trim((string) $arr_metadata[2]);
         $unique_key = (string) trim((string) $arr_metadata[3]);
         //--
         unset($arr_metadata);
         //--
         $timed_hours = 1;
         // default expire in 1 hour
         if (defined('SMART_FRAMEWORK_DOWNLOAD_EXPIRE')) {
             if ((int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE > 0) {
                 if ((int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE <= 24) {
                     // max is 24 hours (since download link is bind to unique browser signature + unique cookie ... make non-sense to keep more)
                     $timed_hours = (int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE;
                 }
                 //end if
             }
             //end if
         }
         //end if
         //--
         if ((int) $timed_hours > 0) {
             if ((int) $crrtime < (int) (time() - 60 * 60 * $timed_hours)) {
                 Smart::log_info('File Download', 'Failed: 403 / Download expired at: ' . date('Y-m-d H:i:s O', (int) $crrtime) . ' for: ' . $filepath . ' on Client: ' . $client_signature);
                 self::Raise403Error('ERROR: The Access Key for this Download is Expired !');
                 return '';
             }
             //end if
         }
         //end if
         //--
         if ((string) $access_key != (string) sha1('DownloadLink:' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . SMART_APP_VISITOR_COOKIE . ':' . $filepath . '^' . $controller_key)) {
             Smart::log_info('File Download', 'Failed: 403 / Invalid Access Key for: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise403Error('ERROR: Invalid Access Key for this Download !');
             return '';
         }
         //end if
         //--
         if ((string) $unique_key != (string) SmartHashCrypto::sha1('Time=' . $crrtime . '#' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . $access_key . '-' . SmartUtils::unique_auth_client_private_key() . ':' . $filepath . '+' . $controller_key)) {
             Smart::log_info('File Download', 'Failed: 403 / Invalid Client (Unique) Key for: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise403Error('ERROR: Invalid Client Key to Access this Download !');
             return '';
         }
         //end if
         //--
         if (SmartFileSysUtils::check_file_or_dir_name($filepath)) {
             //--
             $skip_log = 'no';
             // default log
             if (defined('SMART_FRAMEWORK_DOWNLOAD_SKIP_LOG')) {
                 $skip_log = 'yes';
                 // do not log if accessed via admin area and user is authenticated
             }
             //end if
             //--
             $tmp_file_ext = (string) strtolower(SmartFileSysUtils::get_file_extension_from_path($filepath));
             // [OK]
             $tmp_file_name = (string) strtolower(SmartFileSysUtils::get_file_name_from_path($filepath));
             //--
             $tmp_eval = SmartFileSysUtils::mime_eval($tmp_file_name);
             $mime_type = (string) $tmp_eval[0];
             $mime_disp = (string) $tmp_eval[1];
             //-- the path must not start with / but this is tested below
             $tmp_arr_paths = (array) explode('/', $filepath, 2);
             // only need 1st part for testing
             //-- allow file downloads just from specific folders like wpub/ or wsys/ (this is a very important security fix to dissalow any downloads that are not in the specific folders)
             if (substr((string) $filepath, 0, 1) != '/' and strpos((string) SMART_FRAMEWORK_DOWNLOAD_FOLDERS, '<' . trim((string) $tmp_arr_paths[0]) . '>') !== false and stripos((string) SMART_FRAMEWORK_DENY_UPLOAD_EXTENSIONS, '<' . $tmp_file_ext . '>') === false) {
                 //--
                 SmartFileSysUtils::raise_error_if_unsafe_path($filepath);
                 // re-test finally
                 //--
                 @clearstatcache();
                 //--
                 if (is_file($filepath)) {
                     //--
                     if (!headers_sent()) {
                         //--
                         $fp = @fopen($filepath, 'rb');
                         $fsize = @filesize($filepath);
                         //--
                         if (!$fp || $fsize <= 0) {
                             //--
                             Smart::log_info('File Download', 'Failed: 404 / The requested File is Empty or Not Readable: ' . $filepath . ' on Client: ' . $client_signature);
                             self::Raise404Error('WARNING: The requested File is Empty or Not Readable !');
                             return '';
                             //--
                         }
                         //end if
                         //-- set max execution time to zero
                         ini_set('max_execution_time', 0);
                         // we can expect a long time if file is big, but this will be anyway overriden by the WebServer Timeout Directive
                         //--
                         // cache headers are presumed to be sent by runtime before of this step
                         //--
                         header('Content-Type: ' . $mime_type);
                         header('Content-Disposition: ' . $mime_disp);
                         header('Content-Length: ' . $fsize);
                         //--
                         @fpassthru($fp);
                         // output without reading all in memory
                         //--
                         @fclose($fp);
                         //--
                     } else {
                         //--
                         Smart::log_info('File Download', 'Failed: 500 / Headers Already Sent: ' . $filepath . ' on Client: ' . $client_signature);
                         self::Raise500Error('ERROR: Download Failed, Headers Already Sent !');
                         return '';
                         //--
                     }
                     //end if else
                     //--
                     if ((string) $skip_log != 'yes') {
                         //--
                         $downloaded_file = (string) $filepath;
                         // return the file name to be logged
                         //--
                     }
                     //end if
                     //--
                 } else {
                     //--
                     Smart::log_info('File Download', 'Failed: 404 / The requested File does not Exists: ' . $filepath . ' on Client: ' . $client_signature);
                     self::Raise404Error('WARNING: The requested File for Download does not Exists !');
                     return '';
                     //--
                 }
                 //end if else
             } else {
                 //--
                 Smart::log_info('File Download', 'Failed: 403 / Access to this File is Denied: ' . $filepath . ' on Client: ' . $client_signature);
                 self::Raise403Error('ERROR: Download Access to this File is Denied !');
                 return '';
                 //--
             }
             //end if else
             //--
         } else {
             //--
             Smart::log_info('File Download', 'Failed: 400 / Unsafe File Path: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise400Error('ERROR: Unsafe Download File Path !');
             return '';
             //--
         }
         //end if else
         //--
     } else {
         //--
         Smart::log_info('File Download', 'Failed: 400 / Invalid Data Packet' . ' on Client: ' . $client_signature);
         self::Raise400Error('ERROR: Invalid Download Data Packet !');
         return '';
         //--
     }
     //end if else
     //--
     return (string) $downloaded_file;
     //--
 }
 /**
  * Generate a PDF Document on the fly from a piece of HTML code.
  *
  * Notice: this is using a secured cache folder, unique per visitor ID
  *
  * @param STRING $y_html_content				:: The HTML Code
  * @param ENUM $y_orientation					:: Page Orientation: 'normal' | 'wide'
  * @param STRING $y_runtime_script 				:: The allowed Runtime Script to allow send credentials for sub-downloads. Ex: admin.php
  * @param STRING $y_runtime_url					:: The allowed Runtime URL ended by '/' to allow send credentials for sub-downloads. Ex: http(s)://some-server/some_path/ ; normally this should be set in config to enforce https:// and a single URL only
  * @param BOOLEAN $y_allow_send_credentials 	:: Set to TRUE to allow or set to FALSE to dissalow sending the auth credentials for sub-downloads: in the case there are embedded pictures generated by admin.php which may need authentication before to work, the credentials need to be set automatically in this case
  *
  * @returns STRING 							:: The PDF Document Contents
  *
  */
 public static function generate($y_html_content, $y_orientation = 'normal', $y_runtime_script = '', $y_runtime_url = '', $y_allow_send_credentials = false)
 {
     //--
     $pdfdata = '';
     //--
     $htmldoc = self::is_active();
     //--
     if ((string) $htmldoc != '') {
         //--
         if ((string) $y_orientation == 'wide') {
             $orientation = self::tag_page_wide();
         } else {
             $orientation = self::tag_page_normal();
         }
         //end if else
         //--
         $tmp_prefix_dir = 'tmp/cache/pdf/';
         $protect_file = $tmp_prefix_dir . '.htaccess';
         $dir = $tmp_prefix_dir . SMART_FRAMEWORK_SESSION_PREFIX . '/';
         // we use different for index / admin / @
         //--
         $uniquifier = SmartUtils::unique_auth_client_private_key() . SMART_APP_VISITOR_COOKIE;
         $the_dir = $dir . Smart::safe_varname(Smart::uuid_10_seq() . '_' . Smart::uuid_10_num() . '_' . SmartHashCrypto::sha1($uniquifier)) . '/';
         //--
         $tmp_uuid = Smart::uuid_45($uniquifier) . Smart::uuid_36($uniquifier);
         $file = $the_dir . '__document_' . SmartHashCrypto::sha256('@@PDF#File::Cache@@' . $tmp_uuid) . '.html';
         $logfile = $the_dir . '__headers_' . SmartHashCrypto::sha256('@@PDF#File::Cache@@' . $tmp_uuid) . '.log';
         //--
         if (is_dir($the_dir)) {
             SmartFileSystem::dir_delete($the_dir);
         }
         //end if
         //--
         if (!is_dir($the_dir)) {
             SmartFileSystem::dir_recursive_create($the_dir);
         }
         // end if
         //--
         SmartFileSystem::write_if_not_exists($protect_file, trim(SMART_FRAMEWORK_HTACCESS_FORBIDDEN) . "\n", 'yes');
         //-- process the code
         $y_html_content = (string) self::remove_between_tags((string) $y_html_content);
         $y_html_content = (string) self::safe_charset((string) $y_html_content);
         //-- extract images
         $htmlparser = new SmartHtmlParser((string) $y_html_content);
         $arr_imgs = $htmlparser->get_tags('img');
         $htmlparser = '';
         unset($htmlparser);
         //--
         $chk_duplicates_arr = array();
         //--
         for ($i = 0; $i < Smart::array_size($arr_imgs); $i++) {
             //--
             $tmp_img_src = trim((string) $arr_imgs[$i]['src']);
             //--
             if (strlen($chk_duplicates_arr[$tmp_img_src]) <= 0) {
                 //--
                 $tmp_url_img_src = '';
                 //--
                 if ((string) $y_runtime_script != '' and (string) $y_runtime_url != '') {
                     // replace relative paths
                     if (substr($tmp_img_src, 0, @strlen($y_runtime_script)) == (string) $y_runtime_script) {
                         $tmp_url_img_src = (string) $y_runtime_url . $tmp_img_src;
                         $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $tmp_url_img_src . '"', (string) $y_html_content);
                         $tmp_img_src = (string) $tmp_url_img_src;
                     }
                     //end if
                 }
                 //end if
                 //--
                 $tmp_img_ext = '.' . strtolower(SmartFileSysUtils::get_file_extension_from_path($tmp_img_src));
                 // [OK]
                 $tmp_img_cache = 'pdf_img_' . SmartHashCrypto::sha256('@@PDF#File::Cache::IMG@@' . '#' . $i . '@' . $tmp_img_src . '//' . $tmp_uuid);
                 //--
                 $tmp_arr = array();
                 //--
                 if (substr($tmp_img_src, 0, 7) == 'http://' or substr($tmp_img_src, 0, 8) == 'https://') {
                     //--
                     $tmp_img_ext = '';
                     // we clear the extension as we don't know yet (we will get it from headers)
                     $tmp_img_cache = 'pdf_url_img_' . SmartHashCrypto::sha256('@@PDF#File::Cache::URL::IMG@@' . '#' . $i . '@' . $tmp_img_src . '//' . $tmp_uuid);
                     //--
                 }
                 //end if
                 //--
                 if ($y_allow_send_credentials === true) {
                     $allow_set_credentials = 'yes';
                 } else {
                     $allow_set_credentials = 'no';
                 }
                 //end if else
                 //--
                 $tmp_arr = SmartUtils::load_url_or_file($tmp_img_src, SMART_FRAMEWORK_NETSOCKET_TIMEOUT, 'GET', '', '', '', $allow_set_credentials);
                 // [OK] :: allow set credentials
                 //--
                 $tmp_img_ext = '.noextension';
                 $tmp_where_we_guess = '';
                 //--
                 $guess_arr = array();
                 //--
                 $guess_arr = SmartUtils::guess_image_extension_by_url_head($tmp_arr['headers']);
                 $tmp_img_ext = (string) $guess_arr['extension'];
                 $tmp_where_we_guess = (string) $guess_arr['where-was-detected'];
                 $guess_arr = array();
                 if ((string) $tmp_img_ext == '') {
                     $tmp_img_ext = SmartUtils::guess_image_extension_by_first_bytes(substr($tmp_arr['content'], 0, 256));
                     if ((string) $tmp_img_ext != '') {
                         $tmp_where_we_guess = ' First Bytes ...';
                     }
                     //end if
                 }
                 //end if
                 //--
                 if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                     // if debug, append information to log
                     SmartFileSystem::write($logfile, '####################' . "\n" . '#################### [FILE # ' . $i . ' = \'' . $tmp_img_src . '\']' . "\n\n" . '==== [MODE] :: ' . $tmp_arr['mode'] . "\n" . '==== [LOG] :: ' . "\n" . $tmp_arr['log'] . "\n" . '==== [HEADERS] ::' . "\n" . $tmp_arr['headers'] . "\n" . '########' . "\n" . '==== [GUESS EXTENSION] :: ' . $tmp_where_we_guess . "\n\n" . '###################' . "\n\n\n\n", 'a');
                 }
                 //end if
                 //--
                 if ((string) $tmp_arr['result'] == '1' and (string) $tmp_arr['code'] == '200') {
                     //--
                     SmartFileSystem::write($the_dir . $tmp_img_cache . $tmp_img_ext, $tmp_arr['content']);
                     //-- if empty, it may be a file
                     if ((string) $tmp_img_ext == '' or (string) $tmp_img_ext == '.png' or (string) $tmp_img_ext == '.gif' or (string) $tmp_img_ext == '.jpg') {
                         $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $tmp_img_cache . $tmp_img_ext . '"', (string) $y_html_content);
                     } else {
                         // we want to avoid html code to be loaded as image by mistakes of http browser class or servers
                         $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $y_runtime_url . 'lib/framework/img/sign_warn.png"', (string) $y_html_content);
                     }
                     //end if else
                     //--
                 } else {
                     //--
                     $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $y_runtime_url . 'lib/framework/img/sign_error.png"', (string) $y_html_content);
                     //--
                 }
                 //end if
                 //--
             }
             //end if
             //--
             $chk_duplicates_arr[$tmp_img_src] = 'processed';
             //--
         }
         //end for
         //--
         $chk_duplicates_arr = array();
         unset($chk_duplicates_arr);
         $arr_imgs = array();
         unset($arr_imgs);
         //--
         SmartFileSystem::write($file, $orientation . "\n" . $y_html_content);
         //--
         if (is_file($file)) {
             //--
             ob_start();
             //--
             @passthru($htmldoc . ' ' . self::pdf_options($file));
             //--
             $pdfdata = ob_get_clean();
             //--
         } else {
             //--
             Smart::log_warning('ERROR: PDF Generator Failed to find the PDF Document: ' . $file . "\n" . $y_html_content);
             //--
         }
         //end if else
         //-- cleanup
         if ((string) SMART_FRAMEWORK_DEBUG_MODE != 'yes') {
             // if not debug, cleanup the dir
             if (is_dir($the_dir)) {
                 SmartFileSystem::dir_delete($the_dir);
             }
             //end if
         }
         //end if
         //--
     } else {
         //--
         Smart::log_notice('NOTICE: PDF Generator is INACTIVE ...');
         //--
     }
     //end if
     //--
     return (string) $pdfdata;
     //--
 }
Пример #11
0
 /**
  * Load/Save a cache file from Memory or from a URL
  *
  * @param STRING 	$y_cache_file_extension		:: File Extension (example: '.ext')
  * @param STRING 	$y_cache_prefix				:: prefix dir (at least 3 chars) ended by slash (Example: 'prefix/')
  * @param STRING 	$y_load_url					:: URL to Load (Ex: http(s)://some/test.txt ; memory://some.unique.key)
  * @param STRING	$y_content					:: just for memory:// ; contents of the file to be saved into cache - [set] mode ; if this is empty will just get
  * @param INT 		$y_cache_expire				:: 0=never ; (>0)=seconds
  * @param ENUM 		$y_encrypted				:: yes/no to encrypt the file content
  * @return MIXED								:: cached contents
  */
 public static function load_cached_content($y_cache_file_extension, $y_cache_prefix, $y_load_url, $y_content = '', $y_cache_expire = 0, $y_encrypted = 'no')
 {
     // v.150209
     //--
     $y_load_url = (string) $y_load_url;
     //--
     if ((string) $y_load_url == '') {
         Smart::log_warning('Utils // Load From Cache ... Empty URL ...');
         return '';
     }
     //end if
     //--
     //--
     $y_cache_file_extension = Smart::safe_validname($y_cache_file_extension);
     //--
     $y_cache_expire = Smart::format_number_int($y_cache_expire, '+');
     //--
     $y_cache_prefix = (string) $y_cache_prefix;
     //--
     if (strlen($y_cache_prefix) >= 3 and strlen($y_cache_prefix) <= 64) {
         //--
         $y_cache_prefix = SmartFileSysUtils::add_dir_last_slash($y_cache_prefix);
         // fix trailing slash
         //--
     } else {
         //--
         $y_cache_prefix = 'default/';
         //--
     }
     //end if
     //--
     //--
     $unique_id = (string) SmartHashCrypto::sha1('@@::SmartFramework::Content::Cache@@' . $y_load_url);
     //--
     $dir = 'tmp/cache/' . $y_cache_prefix . SmartFileSysUtils::prefixed_sha1_path($unique_id);
     SmartFileSysUtils::raise_error_if_unsafe_path($dir);
     //--
     $file = (string) $dir . $unique_id . $y_cache_file_extension;
     SmartFileSysUtils::raise_error_if_unsafe_path($file);
     //--
     //--
     if (!is_dir($dir)) {
         SmartFileSystem::dir_recursive_create($dir);
     }
     // end if
     //--
     $protect_file = $dir . 'index.html';
     if (!is_file($protect_file)) {
         SmartFileSystem::write($protect_file, '');
     }
     //end if
     //--
     //-- will go through this only if cache expired or no cache
     if (!is_file($file) or is_file($file) and $y_cache_expire > 0 and @filemtime($file) + $y_cache_expire < time()) {
         //-- read
         if (substr($y_load_url, 0, 9) == 'memory://' and (string) $y_content != '') {
             //-- set the content from memory
             $tmp_content = (string) $y_content;
             $tmp_result = '1';
             $tmp_code = '200';
             //--
         } elseif (substr($y_load_url, 0, 9) != 'memory://') {
             //--
             $arr = self::load_url_or_file($y_load_url);
             // [OK]
             $tmp_result = $arr['result'];
             $tmp_code = $arr['code'];
             $tmp_content = $arr['content'];
             $arr = array();
             //--
         }
         //end if else
         //-- if required, apply encryption
         if ((string) $y_encrypted == 'yes') {
             //--
             $tmp_content = self::crypto_blowfish_encrypt($tmp_content);
             //--
         }
         //end if
         //-- write to cache
         if ((string) $tmp_result == '1' and (string) $tmp_code == '200') {
             //--
             SmartFileSystem::write($file, $tmp_content);
             // save file to cache (safe write is controlled via locks)
             //--
         }
         //end if
         //--
         $tmp_content = '';
         //--
     }
     //end if
     //--
     //-- get from cache
     $out = SmartFileSystem::read($file);
     //--
     if ((string) $y_encrypted == 'yes') {
         $out = self::crypto_blowfish_decrypt($out);
     }
     //end if
     //--
     //--
     return $out;
     //--
 }
Пример #12
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
     //--
 }