public static function Redirection_Monitor()
    {
        //--
        if (!defined('SMART_FRAMEWORK_VERSION')) {
            die('Smart Runtime // Redirection Monitor :: Requires SmartFramework to be loaded ...');
        }
        //end if
        //--
        if (self::$RedirectionMonitorStarted !== false) {
            return;
            // avoid run after it was used by runtime
        }
        //end if
        self::$RedirectionMonitorStarted = true;
        //--
        $url_redirect = '';
        //--
        $the_current_url = SmartUtils::get_server_current_url();
        $the_current_script = SmartUtils::get_server_current_script();
        //--
        if (SMART_SOFTWARE_FRONTEND_ENABLED === false and SMART_SOFTWARE_BACKEND_ENABLED === false) {
            // both frontend and backend are disabled
            die('FATAL ERROR: The FRONTEND but also the BACKEND of this application are DISABLED ! ...');
        }
        //end if
        if (SMART_SOFTWARE_FRONTEND_ENABLED === false and (string) $the_current_script == 'index.php') {
            $url_redirect = $the_current_url . 'admin.php';
        }
        //end if
        if (SMART_SOFTWARE_BACKEND_ENABLED === false and (string) $the_current_script == 'admin.php') {
            $url_redirect = $the_current_url . 'index.php';
        }
        //end if
        //--
        if ((string) $url_redirect == '' and isset($_SERVER['PATH_INFO'])) {
            //--
            if (strlen($_SERVER['PATH_INFO']) > 0) {
                //--
                if ((string) $the_current_script == 'index.php') {
                    $the_current_script = '';
                }
                //end if
                $url_redirect = $the_current_url . $the_current_script . '?' . $_SERVER['PATH_INFO'];
                //--
            }
            //end if
            //--
        }
        //end if
        //--
        $gopage = '
		<!DOCTYPE html>
		<!-- template :: RUNTIME REDIRECTION / PATH SUFFIX -->
		<html>
			<head>
				<meta charset="UTF-8">
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
				<meta http-equiv="refresh" content="3;URL=' . Smart::escape_html($url_redirect) . '">
			</head>
			<body>
				<h1>Redirecting to a valid URL ... wait ...</h1><br>
				<script type="text/javascript">setTimeout("self.location=\'' . Smart::escape_js($url_redirect) . '\'",1500);</script>
			</body>
		</html>
	';
        //--
        if (strlen($url_redirect) > 0) {
            @header('Location: ' . $url_redirect);
            die($gopage);
        }
        //end if
        //--
    }
 /**
  * Function: HTTP Error Message
  *
  * @access 		private
  * @internal
  *
  */
 public static function http_error_message($y_title, $y_message, $y_extra_message = '')
 {
     //--
     return (string) SmartMarkersTemplating::render_file_template('lib/core/templates/http-message-error.inc.htm', ['CHARSET' => SmartUtils::get_encoding_charset(), 'TITLE' => Smart::escape_html($y_title), 'SIGNATURE' => '<b>SmartFramework // Web :: ' . Smart::escape_html(SMART_FRAMEWORK_RELEASE_TAGVERSION . ' ' . SMART_FRAMEWORK_RELEASE_VERSION . ' # ' . SMART_SOFTWARE_APP_NAME . ' / ' . SMART_SOFTWARE_NAMESPACE) . '</b>' . '<br>' . Smart::escape_html(SmartUtils::get_server_current_url() . SmartUtils::get_server_current_script()), 'MESSAGE' => self::operation_error($y_message, '100%'), 'EXTMSG' => $y_extra_message], 'no');
     //--
 }
 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";
     //--
 }
 private static function print_log_runtime()
 {
     //--
     $log = '';
     //--
     $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_head"><font size="4"><b>Client / Server :: RUNTIME Log</b></font></div>';
     //--
     $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_highlight" style="width:450px;"><b>App Runtime - Powered by</b></div>';
     $log .= '<div class="smartframework_debugbar_inforow">' . SmartComponents::draw_powered_info('yes') . '</div>';
     //--
     if (SMART_FRAMEWORK_ADMIN_AREA === true) {
         $the_area = 'admin';
     } else {
         $the_area = 'index';
     }
     //end if else
     //--
     $arr = ['Server Runtime: Smart.Framework' => ['Smart.Framework Middleware Area' => $the_area, 'Smart.Framework Release / Tag / Branch' => SMART_FRAMEWORK_RELEASE_VERSION . ' / ' . SMART_FRAMEWORK_RELEASE_TAGVERSION . ' / ' . SMART_FRAMEWORK_VERSION, 'Smart.Framework Encoding: Internal / DB' => SMART_FRAMEWORK_CHARSET . ' / ' . SMART_FRAMEWORK_DBSQL_CHARSET], 'Server Runtime: PHP' => ['PHP OS' => (string) PHP_OS, 'PHP Version' => 'PHP ' . PHP_VERSION . ' / ' . @php_sapi_name(), 'PHP Locales: ' => (string) setlocale(LC_ALL, 0), 'PHP Encoding: Internal / MBString' => ini_get('default_charset') . ' / ' . @mb_internal_encoding(), 'PHP Memory' => (string) ini_get('memory_limit'), 'PHP Loaded Modules' => (string) strtolower(implode(', ', (array) @get_loaded_extensions()))], 'Server Domain Info' => ['Server Full URL' => SmartUtils::get_server_current_url(), 'Server Script' => SmartUtils::get_server_current_script(), 'Server IP' => SmartUtils::get_server_current_ip(), 'Server Port' => SmartUtils::get_server_current_port(), 'Server Protocol' => SmartUtils::get_server_current_protocol(), 'Server Path' => SmartUtils::get_server_current_path(), 'Server Domain' => SmartUtils::get_server_current_domain_name(), 'Server Base Domain' => SmartUtils::get_server_current_basedomain_name()], 'Client Runtime' => (string) $_SERVER['HTTP_USER_AGENT'] . ' # ' . SmartUtils::get_ip_client() . ' # ' . SmartUtils::get_ip_proxyclient()];
     //--
     foreach ($arr as $debug_key => $debug_val) {
         $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_highlight" style="width:450px;"><b>' . Smart::escape_html($debug_key) . '</b></div>';
         if (is_array($debug_val)) {
             $log .= '<table cellspacing="0" cellpadding="2" width="100%">';
             foreach ($debug_val as $key => $val) {
                 $log .= '<tr valign="top"><td width="295"><div class="smartframework_debugbar_inforow"><b>' . Smart::escape_html($key) . '</b></div></td><td><div class="smartframework_debugbar_inforow">' . Smart::escape_html(self::print_value_by_type($val)) . '</div></td></tr>';
             }
             //end foreach
             $log .= '</table>';
         } else {
             $log .= '<div class="smartframework_debugbar_inforow">' . Smart::escape_html((string) $debug_val) . '</div>';
         }
         //end if else
     }
     //end while
     //--
     return $log;
     //--
 }
    public static function movie_player($y_url, $y_title, $y_movie, $y_type, $y_width = '720', $y_height = '404')
    {
        //--
        $player_title = (string) Smart::escape_html($y_title);
        //--
        //--
        if ((string) $y_url == '') {
            $y_url = SmartUtils::get_server_current_url();
        }
        //end if
        //--
        $player_movie = (string) $y_url . $y_movie;
        //--
        $tmp_movie_id = 'smartframework_movie_player_' . sha1($player_movie);
        //--
        //--
        $tmp_div_width = $y_width + 5;
        //--
        $tmp_bgcolor = '#222222';
        $tmp_color = '#FFFFFF';
        //--
        //--
        if ((string) $y_type == 'ogv' or (string) $y_type == 'webm' or (string) $y_type == 'mp4') {
            // {{{SYNC-MOVIE-TYPE}}}
            //--
            if ((string) $y_type == 'webm') {
                $tmp_vtype = 'type="video/webm; codecs=&quot;vp8.0, vorbis&quot;"';
            } else {
                $tmp_vtype = 'type="video/ogg; codecs=&quot;theora, vorbis&quot;"';
            }
            //end if else
            //--
            $html = <<<HTML_CODE
<div align="center" style="padding-top:4px;">
<div style="z-index:1; background-color:{$tmp_bgcolor}; padding:2px; width:725px;">
<!-- start HTML5 Open-Media Player v.120415 -->
<video id="{$tmp_movie_id}" width="{$y_width}" height="{$y_height}" controls="controls" autoplay="autoplay">
\t<source src="{$player_movie}" {$tmp_vtype}>
\tWARNING: Your browser does not support the HTML5 Video Tag.
</video>
<br>
<h2 style="color:{$tmp_color}">{$player_title}</h2>
</div>
<!-- end HTML5 Open-Media Player -->
</div>
</div>
<br>
HTML_CODE;
        } else {
            $html = SmartComponents::operation_notice('Invalid Media Type / Video: ' . Smart::escape_html((string) $y_type), '725px');
        }
        //end if else
        //--
        return $html;
        //--
    }
 /**
  * Get A UNIQUE (SAFE) ID for DB Tables
  *
  * @param ENUM $y_mode 							:: mode: uid10str | uid10num | uid36 | uid45
  * @param STRING $y_field_name 					:: the field name
  * @param STRING $y_table_name 					:: the table name
  * @param RESOURCE $y_connection 				:: the connection to mysql server
  * @return STRING 								:: the generated Unique ID
  *
  */
 public static function new_safe_id($y_mode, $y_id_field, $y_table_name, $y_connection = 'DEFAULT')
 {
     //==
     $y_connection = self::check_connection($y_connection, 'NEW-SAFE-ID');
     //==
     //--
     if (!self::validate_table_and_fields_names($y_table_name)) {
         self::error(self::get_connection_id($y_connection), 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Table Name', $y_table_name);
         return '';
     }
     //end if
     if (!self::validate_table_and_fields_names($y_id_field)) {
         self::error(self::get_connection_id($y_connection), 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Field Name', $y_id_field . ' / [Table=' . $y_table_name . ']');
         return '';
     }
     //end if
     //--
     //--
     $tmp_result = 'NO-ID-INIT';
     //init (must be not empty)
     $counter = 0;
     // default is zero
     //--
     while ((string) $tmp_result != '') {
         // while we cannot find an unused ID
         //--
         $counter += 1;
         //--
         if ($counter > 7500) {
             // loop to max 7500
             self::error(self::get_connection_id($y_connection), 'NEW-SAFE-ID', 'Get New Safe ID', 'Could Not Assign a Unique ID', '(timeout / 7500) ... try again !');
             return '';
         }
         //end if
         //--
         if ($counter % 500 == 0) {
             sleep(1);
         }
         //end if
         //--
         $new_id = 'NO-ID-ALGO';
         switch ((string) $y_mode) {
             case 'uid45':
                 $new_id = (string) Smart::uuid_45(SMART_FRAMEWORK_NETSERVER_ID . SmartUtils::get_server_current_url());
                 // will use the server ID.Host as Prefix to ensure it is true unique in a cluster
                 break;
             case 'uid36':
                 $new_id = (string) Smart::uuid_36(SMART_FRAMEWORK_NETSERVER_ID . SmartUtils::get_server_current_url());
                 // will use the server ID.Host as Prefix to ensure it is true unique in a cluster
                 break;
                 //			case 'uid10seq': // sequences are not safe without a second registry allocation table as the chance to generate the same ID in the same time moment is just 1 in 999
                 //				$new_id = (string) Smart::uuid_10_seq();
                 //				break;
             //			case 'uid10seq': // sequences are not safe without a second registry allocation table as the chance to generate the same ID in the same time moment is just 1 in 999
             //				$new_id = (string) Smart::uuid_10_seq();
             //				break;
             case 'uid10num':
                 $new_id = (string) Smart::uuid_10_num();
                 break;
             case 'uid10str':
             default:
                 $new_id = (string) Smart::uuid_10_str();
         }
         //end switch
         //--
         $result_arr = array();
         $result_arr = self::read_data('SELECT `' . $y_id_field . '` FROM `' . $y_table_name . '` WHERE (`' . $y_id_field . '` = \'' . $this->quote($new_id) . '\') LIMIT 1 OFFSET 0', 'Checking if NEW ID Exists ...', $y_connection);
         $tmp_result = (string) trim((string) $result_arr[0]);
         $result_arr = array();
         //--
     }
     //end while
     //--
     //--
     return (string) $new_id;
     //--
 }
 /**
  * Send Email Mime Message from custom MailBox to a destination
  *
  * @param ARRAY			$y_server_settings	arr = [ server_name, server_port, server_sslmode, server_auth_user, server_auth_pass, send_from_addr, send_from_name, smtp_mxdomain ]
  * @param ENUM			$y_mode				'send' = do send | 'send-return' = do send + return | 'return' = return mime formated mail
  * @param STRING 		$to					To:
  * @param STRING 		$cc					Cc: | empty
  * @param STRING 		$subj				Subject:
  * @param STRING 		$message			Body/Message:
  * @param TRUE/FALSE 	$is_html			* Format: Html or Text/Plain
  * @param ARRAY 		$attachments		* $attachments = array('file1.txt'=>'This is the file 1 content', ...);
  * @param ENUM			$charset			* charset
  * @param ENUM			$priority			* 1=High ; 3=Normal ; 5=Low
  * @param STRING 		$inreplyto			'' | the ID of message that is replying to
  * @return ARRAY							OPERATION RESULT, ERROR, MIME MESSAGE
  */
 public static function send_extended_email($y_server_settings, $y_mode, $to, $cc, $subj, $message, $is_html, $attachments, $charset, $priority, $inreplyto, $bcc = '', $replytoaddr = '')
 {
     //-- SMTP Hello
     $server_helo = trim($y_server_settings['smtp_mxdomain']);
     //-- SMTP connection vars
     $server_name = trim($y_server_settings['server_name']);
     $server_port = trim($y_server_settings['server_port']);
     $server_sslmode = trim($y_server_settings['server_sslmode']);
     $server_user = trim($y_server_settings['server_auth_user']);
     $server_pass = trim($y_server_settings['server_auth_pass']);
     //-- SEND FROM
     $send_from_addr = trim($y_server_settings['send_from_addr']);
     $send_from_name = trim($y_server_settings['send_from_name']);
     //--
     //-- mail send class init
     $mail = new SmartMailerSend();
     $mail->usealways_b64 = true;
     //--
     if ((string) $server_name == '@mail') {
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             SmartFrameworkRegistry::setDebugMsg('mail', 'SEND', 'Send eMail Method Selected: [MAIL]');
         }
         //end if
         //-- mail method
         $mail->method = 'mail';
         //--
     } elseif (strlen($server_name) > 0) {
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             SmartFrameworkRegistry::setDebugMsg('mail', 'SEND', 'Send eMail Method Selected: [SMTP]');
         }
         //end if
         //-- smtp server method
         $mail->method = 'smtp';
         $mail->smtp_timeout = '30';
         //--
         $mail->smtp_helo = $server_helo;
         $mail->smtp_server = $server_name;
         $mail->smtp_port = $server_port;
         $mail->smtp_ssl = $server_sslmode;
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             $mail->debuglevel = 1;
             // default is 1
         } else {
             $mail->debuglevel = 0;
             // no debug
         }
         //end if else
         //--
         if ((string) $server_user == '' or (string) $server_pass == '') {
             $mail->smtp_login = false;
         } else {
             $mail->smtp_login = true;
             $mail->smtp_user = $server_user;
             $mail->smtp_password = $server_pass;
         }
         //end if
         //--
     } else {
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             SmartFrameworkRegistry::setDebugMsg('mail', 'SEND', 'Send eMail Method Selected: [NONE] !!!');
         }
         //end if
         //--
         $mail->method = 'skip';
         //--
     }
     //end if else
     //--
     //-- charset
     if ((string) $charset == '') {
         $charset = 'UTF-8';
         // default
     }
     //end if
     //--
     $mail->charset = (string) $charset;
     //--
     //--
     if ((string) $mail->charset != 'UTF-8') {
         // in this case (ISO-88591 / ISO-8859-2) we deaccent the things for maximum compatibility
         $send_from_name = SmartUnicode::deaccent_str($send_from_name);
         $subj = SmartUnicode::deaccent_str($subj);
         $message = SmartUnicode::deaccent_str($message);
     }
     //end if
     //--
     //--
     $tmp_explode_arr = (array) explode('@', (string) $send_from_addr);
     $tmp_name = trim($tmp_explode_arr[0]);
     // not used
     $tmp_domain = trim($tmp_explode_arr[1]);
     // used for message ID
     //--
     $tmp_my_uid = getmyuid();
     $tmp_my_gid = getmygid();
     //--
     //-- Extra Mail Headers
     $mail->headers = '';
     //-- Errors Reporting Header
     $mail->headers .= 'Errors-To: ' . $send_from_addr . "\r\n";
     //-- In-Reply-To Header
     if ((string) $inreplyto != '') {
         $mail->headers .= 'In-Reply-To: ' . $inreplyto . "\r\n";
     }
     //end if else
     //-- Reply-To Header
     if ((string) $replytoaddr != '') {
         $mail->headers .= 'Reply-To: ' . $replytoaddr . "\r\n";
     }
     //end if
     //-- antiSPAM Header
     $mail->headers .= 'X-AntiAbuse: This header was added to track abuse, please include it with any abuse report' . "\r\n";
     $mail->headers .= 'X-AntiAbuse: Primary Hostname - ' . $server_helo . "\r\n";
     $mail->headers .= 'X-AntiAbuse: Original Domain - ' . $server_helo . "\r\n";
     $mail->headers .= 'X-AntiAbuse: Originator/Caller UID/GID - [48880 48885] / [' . $tmp_my_uid . ' ' . $tmp_my_gid . ']' . "\r\n";
     $mail->headers .= 'X-AntiAbuse: Sender Address Domain - ' . $tmp_domain . "\r\n";
     //--
     //--
     $mail->priority = $priority;
     // high=1 | low=5 | normal=3
     //--
     //-- from
     $mail->from_return = $send_from_addr;
     $mail->from = $send_from_addr;
     $mail->namefrom = $send_from_name;
     //--
     //-- subject
     $mail->subject = $subj;
     //--
     //-- if message is html, include CID imgs as attachments
     if ((string) $y_mode != 'return' and $is_html) {
         //-- init
         $arr_links = array();
         //-- embedd all images
         $htmlparser = new SmartHtmlParser($message);
         $htmlparser->get_clean_html();
         // to be tested ...
         $arr_links = $htmlparser->get_tags('img');
         $htmlparser = '';
         unset($htmlparser);
         //--
         $chk_duplicates_arr = array();
         $uniq_id = 0;
         //--
         for ($i = 0; $i < Smart::array_size($arr_links); $i++) {
             //--
             $tmp_original_img_link = trim($arr_links[$i][src]);
             // trim any possible spaces
             //-- reverse the &amp; back to & (generated from JavaScript) ...
             $tmp_imglink = str_replace('&amp;', '&', (string) $tmp_original_img_link);
             //--
             $tmp_cid = 'img_' . sha1('SmartFramework eMail-Utils // CID Embedd // ' . '@' . $tmp_imglink . '#');
             // this should not vary by $i or others because if duplicate images are detected only the first is attached
             //--
             if (strlen($chk_duplicates_arr[$tmp_cid]) <= 0) {
                 // avoid browse twice the same image
                 //--
                 $tmp_original_lnk = (string) $tmp_imglink;
                 $tmp_eval_link = (string) $tmp_imglink;
                 $tmp_allow_credentials = 'no';
                 if (substr($tmp_original_lnk, 0, 10) == 'admin.php?') {
                     $tmp_original_lnk = (string) SmartUtils::get_server_current_url() . $tmp_imglink;
                     $tmp_allow_credentials = 'yes';
                     // in the case we have embedded pictures generated by admin.php who always need authentication to work, we have to send credentials too
                     $tmp_eval_link = '';
                     // we clear to re-eval
                 } elseif (SmartUnicode::sub_str($tmp_original_lnk, 0, SmartUnicode::str_len(SmartUtils::get_server_current_url() . 'admin.php?')) == SmartUtils::get_server_current_url() . 'admin.php?' and (substr($tmp_original_lnk, 0, 7) == 'http://' or substr($tmp_original_lnk, 0, 8) == 'https://')) {
                     $tmp_allow_credentials = 'yes';
                     // in the case we have embedded pictures generated by admin.php who always need authentication to work, we have to send credentials too
                     $tmp_eval_link = '';
                     // we clear to re-eval
                 } elseif (substr($tmp_original_lnk, 0, 10) == 'index.php?' or substr($tmp_original_lnk, 0, 1) == '?') {
                     $tmp_original_lnk = (string) SmartUtils::get_server_current_url() . $tmp_imglink;
                     $tmp_eval_link = '';
                     // we clear to re-eval
                 } elseif (SmartUnicode::sub_str($tmp_original_lnk, 0, SmartUnicode::str_len(SmartUtils::get_server_current_url() . 'index.php?')) == SmartUtils::get_server_current_url() . 'index.php?' and (substr($tmp_original_lnk, 0, 7) == 'http://' or substr($tmp_original_lnk, 0, 8) == 'https://')) {
                     $tmp_eval_link = '';
                     // we clear to re-eval
                 } elseif (SmartUnicode::sub_str($tmp_original_lnk, 0, SmartUnicode::str_len(SmartUtils::get_server_current_url() . '?')) == SmartUtils::get_server_current_url() . '?' and (substr($tmp_original_lnk, 0, 7) == 'http://' or substr($tmp_original_lnk, 0, 8) == 'https://')) {
                     $tmp_eval_link = '';
                     // we clear to re-eval
                 }
                 //end if
                 //--
                 $tmp_browse_arr = array();
                 $tmp_browse_arr = SmartUtils::load_url_or_file($tmp_original_lnk, SMART_FRAMEWORK_NETSOCKET_TIMEOUT, 'GET', '', '', '', $tmp_allow_credentials);
                 // [OK]
                 //Smart::log_notice(print_r($tmp_browse_arr,1));
                 //--
                 $guess_arr = array();
                 $guess_arr = SmartUtils::guess_image_extension_by_url_head($tmp_browse_arr['headers']);
                 $tmp_img_ext = (string) $guess_arr['extension'];
                 $tmp_where_we_guess = (string) $guess_arr['where-was-detected'];
                 //Smart::log_notice('Guess Ext by URL Head: '.$tmp_browse_arr['headers']."\n".'### '.print_r($guess_arr,1)."\n".'#');
                 if ((string) $tmp_img_ext == '') {
                     $tmp_img_ext = SmartUtils::guess_image_extension_by_first_bytes(substr($tmp_browse_arr['content'], 0, 256));
                     if ((string) $tmp_img_ext != '') {
                         $tmp_where_we_guess = ' First Bytes ...';
                     }
                     //end if
                 }
                 //end if
                 //Smart::log_notice('Guess Ext by First Bytes: '.$tmp_img_ext."\n".'#');
                 if ((string) $tmp_eval_link == '') {
                     $tmp_eval_link = 'file' . $tmp_img_ext;
                 }
                 //end if
                 //--
                 $tmp_fcontent = '';
                 if ((string) $tmp_browse_arr['result'] == '1' and (string) $tmp_browse_arr['code'] == '200') {
                     if ((string) $tmp_img_ext == '' or (string) $tmp_img_ext == '.png' or (string) $tmp_img_ext == '.gif' or (string) $tmp_img_ext == '.jpg') {
                         $tmp_fcontent = (string) $tmp_browse_arr['content'];
                     }
                     //end if
                 }
                 //end if else
                 //--
                 if (strlen($tmp_fcontent) > 0) {
                     //--
                     $tmp_arr_fmime = array();
                     $tmp_arr_fmime = SmartFileSysUtils::mime_eval($tmp_eval_link);
                     //--
                     $tmp_fmime = (string) $tmp_arr_fmime[0];
                     if ((string) $tmp_fmime == '' or (string) $tmp_fmime == 'application/octet-stream') {
                         $tmp_fmime = 'image';
                         // in the case of CIDS we already pre-validated the images
                     }
                     //end if
                     $tmp_fname = 'cid_' . $uniq_id . '__' . $tmp_cid . $tmp_img_ext;
                     //--
                     $mail->add_attachment($tmp_fcontent, $tmp_fname, $tmp_fmime, 'inline', $tmp_cid . $tmp_img_ext);
                     // attachment
                     $message = str_replace('src="' . $tmp_original_img_link . '"', 'src="cid:' . $tmp_cid . $tmp_img_ext . '"', $message);
                     //--
                     $uniq_id += 1;
                     //--
                 }
                 //end if
                 //--
                 $chk_duplicates_arr[$tmp_cid] = 'embedd';
                 //--
             }
             //end if
             //--
         }
         //end for
         //-- clean
         $chk_duplicates_arr = array();
         $uniq_id = 0;
         $tmp_original_img_link = '';
         $tmp_imglink = '';
         $tmp_cid = '';
         $tmp_browse_arr = array();
         $tmp_fcontent = '';
         $tmp_arr_fmime = array();
         $tmp_fmime = '';
         $tmp_fname = '';
         //--
     }
     //end if
     //--
     //-- message body
     $mail->is_html = $is_html;
     // false | true
     $mail->body = $message;
     //--
     $message = '';
     unset($message);
     //--
     //-- attachments
     if (is_array($attachments)) {
         if (Smart::array_size($attachments) > 0) {
             while (list($key, $val) = each($attachments)) {
                 //--
                 $tmp_arr_fmime = array();
                 $tmp_arr_fmime = SmartFileSysUtils::mime_eval($key);
                 //--
                 $mail->add_attachment($val, $key, (string) $tmp_arr_fmime[0], 'attachment', '', 'yes');
                 // force as real attachments
                 //--
             }
             //end while
         }
         //end if
     }
     //end if
     //--
     //--
     switch ((string) $y_mode) {
         case 'return':
             //--
             $mail->to = '[::!::]';
             $mail->cc = '';
             //-- only return mime formated message
             $mail->send('no');
             return array('result' => 1, 'error' => '', 'message' => $mail->mime_message);
             //--
             break;
         case 'send-return':
         case 'send':
         default:
             //--
             $out = 0;
             //--
             $arr_to = array();
             if (!is_array($to)) {
                 $arr_to[] = (string) $to;
                 $tmp_send_to = (string) $to;
             } else {
                 $arr_to = (array) $to;
                 if (Smart::array_size($arr_to) > 1) {
                     $tmp_send_to = '[::@::]';
                     // multi message
                 } else {
                     $tmp_send_to = (string) $arr_to[0];
                 }
                 //end if else
             }
             //end if else
             //--
             $tmp_send_log = '';
             $tmp_send_log .= '-----------------------------------------------------------------------' . "\n";
             $tmp_send_log .= 'Smart / eMail Send Log :: ' . $send_from_addr . ' [' . $send_from_name . ']' . "\n";
             $tmp_send_log .= $server_sslmode . '://' . $server_name . ':' . $server_port . ' # ' . $server_user . ' :: ' . $server_helo . "\n";
             $tmp_send_log .= '-----------------------------------------------------------------------' . "\n";
             //--
             $counter_sent = 0;
             for ($i = 0; $i < Smart::array_size($arr_to); $i++) {
                 //--
                 $arr_to[$i] = trim($arr_to[$i]);
                 //--
                 if (strlen($arr_to[$i]) > 0) {
                     //--
                     $mail->to = (string) $arr_to[$i];
                     //--
                     $mail->cc = $cc;
                     // can be string or array
                     //--
                     $mail->bcc = (string) $bcc;
                     //--
                     $tmp_send_log .= '#' . ($i + 1) . '. To: \'' . $arr_to[$i] . '\' :: ' . date('Y-m-d H:i:s O');
                     //-- real send
                     if ((string) $mail->method == 'mail' or (string) $mail->method == 'smtp') {
                         $err = $mail->send('yes');
                         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                             SmartFrameworkRegistry::setDebugMsg('mail', 'SEND', 'Send eMail Log #' . ($i + 1) . ': ' . $mail->log);
                         }
                         //end if
                     } else {
                         $err = 'WARNING: SMTP Server or Mail Method IS NOT SET in CONFIG. Send eMail - Operation ABORTED !';
                     }
                     //end if else
                     //--
                     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                         SmartFrameworkRegistry::setDebugMsg('mail', 'SEND', '========== SEND TO: ' . $arr_to[$i] . ' ==========' . "\n" . 'ERRORS: ' . $err . "\n" . '==========' . "\n" . $mail->log . "\n" . '========== # ==========');
                     }
                     //end if
                     //--
                     if (strlen($err) > 0) {
                         $tmp_send_log .= ' :: ERROR:' . "\n" . $arr_to[$i] . "\n" . $err . "\n";
                     } else {
                         $counter_sent += 1;
                         $tmp_send_log .= ' :: OK' . "\n";
                     }
                     //end if else
                     //--
                     if ($i > 10000) {
                         break;
                         // hard limit
                     }
                     //end if
                     //--
                 }
                 //end if
                 //--
             }
             //end for
             //--
             if ($counter_sent > 0) {
                 $out = 1;
             }
             //end if
             //--
             $tmp_send_log .= '-----------------------------------------------------------------------' . "\n\n";
             if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                 SmartFrameworkRegistry::setDebugMsg('mail', 'SEND', 'Send eMail Operations Log: ' . $tmp_send_log);
             }
             //end if
             //--
             if ((string) $y_mode == 'send-return') {
                 $mail->to = $tmp_send_to;
                 if (is_array($cc)) {
                     $mail->cc = (string) implode(', ', $cc);
                 } elseif ((string) $cc != '') {
                     $mail->cc = (string) $cc;
                 }
                 //end if else
                 $mail->add_attachment($tmp_send_log, 'smart-email-send.log', 'text/plain', 'inline');
                 $mail->send('no');
                 return array('result' => $out, 'error' => $err, 'log' => $tmp_send_log, 'message' => $mail->mime_message);
             } else {
                 return array('result' => $out, 'error' => $err, 'log' => $tmp_send_log, 'message' => '');
                 // skip returning the message
             }
             //end if else
             //--
     }
     //end switch
     //--
 }
 /**
  * Get A UNIQUE (SAFE) ID for DB Tables / Schema
  *
  * @param ENUM 		$y_mode 					:: mode: uid10str | uid10num | uid10seq | uid36 | uid45
  * @param STRING 	$y_field_name 				:: the field name
  * @param STRING 	$y_table_name 				:: the table name
  * @param STRING 	$y_schema 					:: the schema
  * @param RESOURCE 	$y_connection 				:: pgsql connection
  * @return STRING 								:: the generated Unique ID
  *
  */
 public static function new_safe_id($y_mode, $y_id_field, $y_table_name, $y_schema = 'public', $y_connection = 'DEFAULT')
 {
     //==
     $y_connection = self::check_connection($y_connection, 'NEW-SAFE-ID');
     //==
     //--
     if (!self::validate_table_and_fields_names($y_id_field)) {
         self::error($y_connection, 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Field Name', $y_id_field . ' / [Schema=' . $y_schema . ';Table=' . $y_table_name . ']');
         return '';
     }
     //end if
     if (!self::validate_table_and_fields_names($y_table_name)) {
         self::error($y_connection, 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Table Name', $y_table_name);
         return '';
     }
     //end if
     if (!self::validate_table_and_fields_names($y_schema)) {
         self::error($y_connection, 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Schema Name', $y_schema);
         return '';
     }
     //end if
     //--
     //--
     $use_safe_id_record = true;
     if (defined('SMART_SOFTWARE_DB_DISABLE_SAFE_IDS')) {
         if (SMART_SOFTWARE_DB_DISABLE_SAFE_IDS === true) {
             $use_safe_id_record = false;
         }
         //end if
     }
     //end if
     //--
     if ($use_safe_id_record === true) {
         //--
         if (self::check_if_table_exists('_safe_id_records', 'smart_runtime', $y_connection) !== 1) {
             if (self::check_if_schema_exists('smart_runtime', $y_connection) !== 1) {
                 self::write_data('CREATE SCHEMA "smart_runtime"', 'Initialize SafeID Schema', $y_connection);
             }
             //end if
             self::write_data((string) self::schema_safe_id_records_table(), 'Initialize SafeID Table', $y_connection);
         }
         //end if
         //--
         if ((int) Smart::random_number(0, 99) == 1) {
             // 1% chance to run it for cleanup records older than 24 hours
             self::write_data('DELETE FROM "smart_runtime"."_safe_id_records" WHERE ("date_time" < \'' . self::escape_str(date('Y-m-d H:i:s', @strtotime('-1 day')), 'no', $y_connection) . '\')', 'Safe ID Records Cleanup (OLDs)', $y_connection);
             // cleanup olds
         }
         //end if
         //--
     }
     //end if
     //--
     $tmp_result = 'NO-ID-INIT';
     //init (must be not empty)
     $counter = 0;
     $id_is_ok = false;
     //--
     while ($id_is_ok !== true) {
         // while we cannot find an unused ID
         //--
         $counter += 1;
         //--
         if ($counter > 7500) {
             // loop to max 7500
             self::error($y_connection, 'NEW-SAFE-ID', 'Get New Safe ID', 'Could Not Assign a Unique ID', '(timeout / 7500) ... try again !');
             return '';
         }
         //end if
         //--
         if ($counter % 500 == 0) {
             sleep(1);
         }
         //end if
         //--
         $new_id = 'NO-ID-ALGO';
         switch ((string) $y_mode) {
             case 'uid45':
                 $new_id = (string) Smart::uuid_45(SMART_FRAMEWORK_NETSERVER_ID . SmartUtils::get_server_current_url());
                 // will use the server ID.Host as Prefix to ensure it is true unique in a cluster
                 break;
             case 'uid36':
                 $new_id = (string) Smart::uuid_36(SMART_FRAMEWORK_NETSERVER_ID . SmartUtils::get_server_current_url());
                 // will use the server ID.Host as Prefix to ensure it is true unique in a cluster
                 break;
             case 'uid10seq':
                 if ($use_safe_id_record === true) {
                     // sequences are not safe without a second registry allocation table as the chance to generate the same ID in the same time moment is just 1 in 999
                     $new_id = (string) Smart::uuid_10_seq();
                 } else {
                     $new_id = (string) Smart::uuid_10_str();
                 }
                 //end if else
                 break;
             case 'uid10num':
                 $new_id = (string) Smart::uuid_10_num();
                 break;
             case 'uid10str':
             default:
                 $new_id = (string) Smart::uuid_10_str();
         }
         //end switch
         //--
         $result_arr = array();
         $chk_uniqueness = 'SELECT ' . self::escape_identifier($y_id_field, $y_connection) . ' FROM ' . self::escape_identifier($y_schema, $y_connection) . '.' . self::escape_identifier($y_table_name, $y_connection) . ' WHERE (' . self::escape_identifier($y_id_field, $y_connection) . ' = ' . self::escape_literal($new_id, 'no', $y_connection) . ') LIMIT 1 OFFSET 0';
         $result_arr = self::read_data($chk_uniqueness, 'Safe Check if NEW ID Exists into Table', $y_connection);
         $tmp_result = (string) trim((string) $result_arr[0]);
         $result_arr = array();
         //--
         if ((string) $tmp_result == '') {
             //--
             if ($use_safe_id_record === true) {
                 // with safety check against safe ID records table
                 //-- reserve this ID to bse sure will not be assigned to another instance
                 $uniqueness_mark = (string) $y_schema . '.' . $y_table_name . ':' . $y_id_field;
                 $write_res = self::write_igdata('INSERT INTO "smart_runtime"."_safe_id_records" ("id", "table_space", "date_time") ( SELECT \'' . self::escape_str($new_id, 'no', $y_connection) . '\', \'' . self::escape_str($uniqueness_mark, 'no', $y_connection) . '\', \'' . self::escape_str(date('Y-m-d H:i:s'), 'no', $y_connection) . '\' WHERE (NOT EXISTS ( SELECT 1 FROM "smart_runtime"."_safe_id_records" WHERE (("id" = \'' . self::escape_str($new_id, 'no', $y_connection) . '\') AND ("table_space" = \'' . self::escape_str($uniqueness_mark, 'no', $y_connection) . '\')) LIMIT 1 OFFSET 0 ) AND NOT EXISTS (' . $chk_uniqueness . ') ) )', 'Safe Record of NEW ID of Table into Zone Control', $y_connection);
                 //--
                 if ($write_res[1] === 1) {
                     $id_is_ok = true;
                 }
                 //end if
                 //--
             } else {
                 // default (not safe in very high load environments ...
                 //--
                 $id_is_ok = true;
                 //--
             }
             //end if else
             //--
         }
         //end if
         //--
     }
     //end while
     //--
     //--
     return (string) $new_id;
     //--
 }