/**
  * Check if Single-User Mode is Enabled
  *
  * @access 		private
  * @internal
  *
  * @return 0/1
  */
 public static function check_single_user()
 {
     //--
     $lock_file = (string) self::lock_file();
     //--
     $out = 0;
     //--
     if (SmartFileSystem::file_or_link_exists($lock_file)) {
         //--
         $lock_content = SmartFileSystem::read($lock_file);
         $chk_arr = explode("\n", trim($lock_content));
         $tmp_time = Smart::format_number_dec(($chk_arr[1] - time()) / 60, 0, '.', '');
         //--
         if ($tmp_time <= 0) {
             $out = 1;
             // TOTAL LOCKED (if greater or equal than ZERO it only warns) !
         }
         //end if
         //--
     }
     //end if
     //--
     return $out;
     //--
 }
 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_database($title, $db_log)
 {
     //--
     $log = '';
     //--
     $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_head"><font size="4"><b>' . Smart::escape_html($title) . ' :: DATABASE Queries</b></font></div>';
     //--
     $max = Smart::array_size($db_log['log']);
     if (is_array($db_log) and $max > 0) {
         $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_highlight" style="width:450px;">Total Queries Number: <b>' . Smart::escape_html(Smart::format_number_int($db_log['total-queries'], '+')) . '</b></div>';
         $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_highlight" style="width:450px;">Total Queries Time: <b>' . Smart::escape_html(Smart::format_number_dec($db_log['total-time'], 9, '.', '')) . ' sec.' . '</b></div>';
         $num = 0;
         for ($i = 0; $i < $max; $i++) {
             //--
             $tmp_arr = (array) $db_log['log'][$i];
             //--
             switch ((string) $tmp_arr['type']) {
                 case 'transaction':
                     //--
                     $num++;
                     //--
                     $tmp_color = '#003399';
                     //--
                     $log .= '<div class="smartframework_debugbar_inforow" style="font-size:12px; color:' . $tmp_color . ';">';
                     $log .= $num . '. ' . '<b>' . Smart::escape_html($tmp_arr['data']) . '</b>';
                     if ((string) $tmp_arr['connection'] != '') {
                         $log .= ' @ ' . Smart::escape_html($tmp_arr['connection']);
                     }
                     //end if
                     if ($tmp_arr['time'] > 0) {
                         $log .= '<br><span style="padding:1px;"><b>@Time: ' . Smart::format_number_dec($tmp_arr['time'], 9, '.', '') . ' sec.</b></span>';
                     }
                     //end if
                     if ((string) $tmp_arr['query'] != '') {
                         $log .= '<br><span class="smartframework_debugbar_status_highlight" style="padding:1px;"><b>' . Smart::escape_html($tmp_arr['query']) . '</b></span>';
                     }
                     //end if
                     $log .= '</div>';
                     //--
                     break;
                 case 'set':
                 case 'count':
                 case 'read':
                 case 'write':
                 case 'nosql':
                     //--
                     if ((string) $tmp_arr['skip-count'] != 'yes') {
                         $num++;
                     }
                     //end if
                     //--
                     if ((string) $tmp_arr['type'] == 'write') {
                         $tmp_color = '#666699';
                     } elseif ((string) $tmp_arr['type'] == 'read') {
                         $tmp_color = '#333333';
                     } elseif ((string) $tmp_arr['type'] == 'count') {
                         $tmp_color = '#339900';
                     } elseif ((string) $tmp_arr['type'] == 'set') {
                         $tmp_color = '#778899';
                     } else {
                         // nosql
                         $tmp_color = '#000000';
                     }
                     //end if else
                     //--
                     $log .= '<div class="smartframework_debugbar_inforow" style="font-size:11px; color:' . $tmp_color . ';">';
                     if ((string) $tmp_arr['skip-count'] != 'yes') {
                         $log .= $num . '. ';
                     }
                     //end if else
                     $log .= '<b>' . Smart::escape_html($tmp_arr['data']) . '</b>';
                     if ((string) $tmp_arr['connection'] != '') {
                         $log .= ' @ ' . Smart::escape_html($tmp_arr['connection']);
                     }
                     //end if
                     if ($tmp_arr['time'] > 0) {
                         if ($tmp_arr['time'] <= $db_log['slow-time']) {
                             $log .= '<br><span style="padding:1px;"><b>@Time: ' . Smart::format_number_dec($tmp_arr['time'], 9, '.', '') . ' sec.</b></span>';
                         } else {
                             $log .= '<br><span class="smartframework_debugbar_status_warn" style="padding:1px;" title="Slow-Time: ' . Smart::escape_html($db_log['slow-time']) . '"><b>@Time: ' . Smart::format_number_dec($tmp_arr['time'], 9, '.', '') . ' sec.' . '</b></span>';
                         }
                         //end if else
                     }
                     //end if
                     if ((string) $tmp_arr['query'] != '') {
                         $log .= '<br>' . Smart::escape_html($tmp_arr['query']);
                         if ((string) $tmp_arr['type'] == 'write') {
                             $log .= '<br>' . 'AFFECTED ROWS: #' . $tmp_arr['rows'];
                         }
                         //end if
                         if (Smart::array_size($tmp_arr['params']) > 0) {
                             $tmp_params = array();
                             foreach ($tmp_arr['params'] as $key => $val) {
                                 $tmp_params[] = Smart::escape_html('$' . ($key + 1) . ' => `' . $val . '`');
                             }
                             //end foreach
                             $log .= '<br>' . '@PARAMS:&nbsp;{ ' . implode(', ', $tmp_params) . ' }';
                             $tmp_params = array();
                         }
                         //end if
                     }
                     //end if
                     if (is_array($tmp_arr['command'])) {
                         $tmp_params = array();
                         foreach ($tmp_arr['command'] as $key => $val) {
                             $tmp_params[] = Smart::escape_html($key . ' => `' . self::print_value_by_type($val) . '`');
                         }
                         //end foreach
                         $log .= '<br>' . '@COMMAND-PARAMS:&nbsp;{ ' . implode(', ', $tmp_params) . ' }';
                         $tmp_params = array();
                     } elseif ((string) $tmp_arr['command'] != '') {
                         $log .= '<br>' . Smart::nl_2_br(Smart::escape_html(str_replace(array("\r\n", "\r", "\t"), array("\n", "\n", ' '), $tmp_arr['command'])));
                     }
                     //end if
                     $log .= '</div>';
                     //--
                     break;
                 case 'open-close':
                     //--
                     $tmp_color = '#4285F4';
                     //--
                     $log .= '<div class="smartframework_debugbar_inforow" style="font-size:12px; color:' . $tmp_color . ';">';
                     $log .= '<b>' . Smart::escape_html($tmp_arr['data']) . '</b>';
                     if ((string) $tmp_arr['connection'] != '') {
                         $log .= ' @ ' . Smart::escape_html($tmp_arr['connection']);
                     }
                     //end if
                     $log .= '</div>';
                     //--
                     break;
                 case 'metainfo':
                 default:
                     //--
                     $tmp_color = '#CCCCCC';
                     //--
                     $log .= '<div class="smartframework_debugbar_inforow" style="font-size:12px; color:' . $tmp_color . ';">';
                     $log .= '<b>' . Smart::escape_html($tmp_arr['data']) . '</b>';
                     if ((string) $tmp_arr['connection'] != '') {
                         $log .= ' @ ' . Smart::escape_html($tmp_arr['connection']);
                     }
                     //end if
                     $log .= '</div>';
                     //--
             }
             //end switch
             //--
         }
         //end for
         //--
     } else {
         //--
         $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_warn" style="width: 100px; text-align: center;"><font size="2"><b>N/A</b></font></div>';
         //--
     }
     //end if
     //--
     return $log;
     //--
 }
 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;
     //--
 }
 public function deleteDocument($id)
 {
     //--
     $connect = $this->solr_connect();
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'solr|total-queries', 1, '+');
         //--
         $time_start = microtime(true);
         //--
     }
     //end if
     //--
     if ((string) $id == '') {
         Smart::log_warning('Solr ERROR # deleteDocument # ' . 'Document ID is Empty');
         return -100;
     }
     //end if
     //--
     try {
         //--
         $updateResponse = $this->instance->deleteById((string) $id);
         $this->instance->commit();
         // save
         //--
     } catch (Exception $e) {
         //--
         Smart::log_warning('Solr ERROR # deleteDocument # EXCEPTION: ' . $e->getMessage() . "\n" . 'ID=' . $id);
         return -201;
         //--
     }
     //end try catch
     //--
     $response = $updateResponse->getResponse();
     // get answer message
     //print_r($response);
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         $time_end = (double) (microtime(true) - (double) $time_start);
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'solr|total-time', $time_end, '+');
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'solr|log', ['type' => 'nosql', 'data' => 'DELETE-QUERY', 'command' => array('ID' => (string) $id), 'time' => Smart::format_number_dec($time_end, 9, '.', '')]);
         //--
     }
     //end if
     //--
     if (is_object($response)) {
         if ($response instanceof SolrObject) {
             if (is_object($response['responseHeader'])) {
                 if ($response['responseHeader'] instanceof SolrObject) {
                     if ($response['responseHeader']->status === 0) {
                         // OK
                     } else {
                         Smart::log_warning('Solr ERROR # deleteDocument # Invalid Status (' . $response['responseHeader']->status . ') : ' . 'ID=' . $id);
                         return -206;
                     }
                     //end if else
                 } else {
                     Smart::log_warning('Solr ERROR # deleteDocument # Invalid responseHeader / Not instanceof SolrObject: ' . 'ID=' . $id);
                     return -205;
                 }
                 //end if else
             } else {
                 Smart::log_warning('Solr ERROR # deleteDocument # Invalid responseHeader / Invalid Object: ' . 'ID=' . $id);
                 return -204;
             }
             //end if else
         } else {
             Smart::log_warning('Solr ERROR # deleteDocument # Invalid Answer / Not instanceof SolrObject: ' . 'ID=' . $id);
             return -203;
         }
         //end if else
     } else {
         Smart::log_warning('Solr ERROR # deleteDocument # Not Object: ' . 'ID=' . $id);
         return -202;
     }
     //end if else
     //--
     return 0;
     // OK
     //--
 }
 public static function write_data($db, $query, $params_or_title = '')
 {
     //--
     self::check_connection($db);
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         $time_start = microtime(true);
         //--
     }
     //end if
     //--
     if (is_array($params_or_title)) {
         $query = self::prepare_param_query($db, $query, $params_or_title);
     }
     //end if
     //--
     $result = @$db->exec($query);
     //--
     if ($result) {
         $affected_rows = @$db->changes();
         // free result is not available for exec, but just for query
         $sqlite_error = '';
     } else {
         $affected_rows = 0;
         $sqlite_error = 'SQLite3-ERR:: ' . @$db->lastErrorMsg();
     }
     //end if
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'sqlite|total-queries', 1, '+');
         //--
         $time_end = (double) (microtime(true) - (double) $time_start);
         SmartFrameworkRegistry::setDebugMsg('db', 'sqlite|total-time', $time_end, '+');
         //--
         if (is_array($params_or_title)) {
             $the_query_title = '';
         } else {
             $the_query_title = (string) $params_or_title;
         }
         //end if else
         //--
         if (strtoupper(substr(trim($query), 0, 5)) == 'BEGIN' or strtoupper(substr(trim($query), 0, 6)) == 'COMMIT' or strtoupper(substr(trim($query), 0, 8)) == 'ROLLBACK') {
             SmartFrameworkRegistry::setDebugMsg('db', 'sqlite|log', ['type' => 'transaction', 'data' => 'TRANSACTION :: ' . $the_query_title, 'query' => $query, 'time' => Smart::format_number_dec($time_end, 9, '.', ''), 'connection' => (string) self::get_connection_id($db)]);
         } else {
             SmartFrameworkRegistry::setDebugMsg('db', 'sqlite|log', ['type' => 'write', 'data' => 'WRITE :: ' . $the_query_title, 'query' => $query, 'rows' => $affected_rows, 'time' => Smart::format_number_dec($time_end, 9, '.', ''), 'connection' => (string) self::get_connection_id($db)]);
         }
         //end if else
         //--
     }
     //end if
     //--
     if (strlen($sqlite_error) > 0) {
         $message = 'errorsqlwriteoperation: ' . $sqlite_error;
         self::error($db, 'WRITE-DATA', $sqlite_error, $query, $params_or_title);
         return array($message, 0);
     } else {
         $message = 'oksqlwriteoperation';
     }
     //end if
     //--
     return array($message, Smart::format_number_int($affected_rows, '+'));
     //--
 }
 /**
  * MySQL Query :: Write.
  * This function is intended to be used for write type queries: BEGIN (TRANSACTION) ; COMMIT ; ROLLBACK ; INSERT ; INSERT IGNORE ; REPLACE ; UPDATE ; CREATE SCHEMAS ; CALLING STORED PROCEDURES ...
  *
  * @param STRING $queryval						:: the query
  * @param STRING $params_or_title 				:: *optional* array of parameters or query title for easy debugging
  * @param RESOURCE $y_connection				:: the connection
  * @return ARRAY 								:: [0 => 'control-message', 1 => #affected-rows]
  */
 public static function write_data($queryval, $params_or_title = '', $y_connection = 'DEFAULT')
 {
     //==
     $y_connection = self::check_connection($y_connection, 'WRITE-DATA');
     //==
     //-- samples
     // $queryval = 'BEGIN'; // start transaction
     // $queryval = 'UPDATE `tablename` SET `field` = \'value\' WHERE (`id_field` = \'val1\')';
     // $queryval = 'INSERT INTO `tablename` (`desiredfield1`, `desiredfield2`) VALUES (\'val1\', \'val2\')';
     // $queryval = 'DELETE FROM `tablename` WHERE (`id_field` = \'val1\')';
     // $queryval = 'COMMIT'; // commit transaction (on success)
     // $queryval = 'ROLLBACK'; // rollback transaction (on error)
     //--
     //--
     $time_start = 0;
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         $time_start = microtime(true);
     }
     //end if
     //--
     //--
     $use_param_query = false;
     if (is_array($params_or_title)) {
         if (Smart::array_size($params_or_title) > 0) {
             $use_param_query = true;
         }
         //end if
     }
     //end if
     //--
     if ($use_param_query === true) {
         $the_query_title = '';
         $queryval = self::prepare_param_query($queryval, (array) $params_or_title, $y_connection);
     } else {
         $the_query_title = (string) $params_or_title;
     }
     //end if else
     //--
     $result = @mysqli_query($y_connection, $queryval, MYSQLI_STORE_RESULT);
     $chk = @mysqli_errno($y_connection);
     $err = @mysqli_error($y_connection);
     //--
     //--
     $error = '';
     $affected = 0;
     if ($chk !== 0) {
         $error = 'Query FAILED:' . "\n" . $err;
     } else {
         $affected = @mysqli_affected_rows($y_connection);
     }
     //end if else
     //--
     //--
     $time_end = 0;
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         $time_end = (double) (microtime(true) - (double) $time_start);
     }
     //end if
     //--
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'mysqli|total-queries', 1, '+');
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'mysqli|total-time', $time_end, '+');
         //--
         if (is_array($params_or_title)) {
             $dbg_query_params = (array) $params_or_title;
         } else {
             $dbg_query_params = '';
         }
         //end if else
         //--
         if (strtoupper(substr(trim($queryval), 0, 5)) == 'BEGIN' or strtoupper(substr(trim($queryval), 0, 6)) == 'COMMIT' or strtoupper(substr(trim($queryval), 0, 8)) == 'ROLLBACK') {
             SmartFrameworkRegistry::setDebugMsg('db', 'mysqli|log', ['type' => 'transaction', 'data' => 'TRANSACTION :: ' . $the_query_title, 'query' => $queryval, 'params' => '', 'time' => Smart::format_number_dec($time_end, 9, '.', ''), 'connection' => (string) self::get_connection_id($y_connection)]);
         } elseif (strtoupper(substr(trim($queryval), 0, 4)) == 'SET ') {
             SmartFrameworkRegistry::setDebugMsg('db', 'mysqli|log', ['type' => 'set', 'data' => 'SET :: ' . $the_query_title, 'query' => $queryval, 'params' => $dbg_query_params, 'time' => Smart::format_number_dec($time_end, 9, '.', ''), 'connection' => (string) self::get_connection_id($y_connection)]);
         } else {
             SmartFrameworkRegistry::setDebugMsg('db', 'mysqli|log', ['type' => 'write', 'data' => 'WRITE :: ' . $the_query_title, 'query' => $queryval, 'params' => $dbg_query_params, 'rows' => $affected, 'time' => Smart::format_number_dec($time_end, 9, '.', ''), 'connection' => (string) self::get_connection_id($y_connection)]);
         }
         //end if else
         //--
     }
     //end if
     //--
     //--
     if (strlen($error) > 0) {
         //--
         $message = 'errorsqlwriteoperation: ' . $error;
         //--
         self::error(self::get_connection_id($y_connection), 'WRITE-DATA', $error, $queryval, $params_or_title);
         return array($message, 0);
         //--
     } else {
         //--
         $message = 'oksqlwriteoperation';
         // this can be extended to detect extra notices
         //--
     }
     //end else
     //--
     //--
     if ($result instanceof mysqli_result) {
         @mysqli_free_result($result);
     }
     //end if
     //--
     //--
     return array($message, Smart::format_number_int($affected, '+'));
     //--
 }
 /**
  * Format Answer for getLanguageConfidence
  *
  * @param STRING 	$langid		Language ID ; Ex: en
  * @param INTEGER 	$score		Confidence Score
  * @param STRING 	$errmsg 	*OPTIONAL* Error Message
  * @return integer
  */
 private function formatLanguageConfidenceAnswer($langid, $score, $errmsg = '')
 {
     //--
     return (array) ['service-available' => (bool) $this->is_service_available, 'lang-id' => (string) substr((string) strtolower((string) trim((string) $langid)), 0, 2), 'confidence-score' => (string) Smart::format_number_dec((double) $score, 5, '.', ''), 'error-message' => (string) trim((string) $errmsg)];
     //--
 }
 /**
  * this is the Magic Call Method
  *
  * @access 		private
  * @internal
  *
  */
 public function __call($method, array $args)
 {
     //--
     $method = (string) $method;
     $args = (array) $args;
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         $time_start = microtime(true);
         //--
     }
     //end if
     //--
     $the_conns = $this->connect();
     //--
     try {
         if (is_object($this->mongodbclient)) {
             // mongoclient does not need this
         } elseif (is_object($this->mongoclient)) {
             $this->mongodb = $this->mongoclient->selectDB((string) $this->db);
             if (!is_object($this->mongodb)) {
                 $this->error((string) $the_conns[0]['hash'], 'MongoDB Object', 'Mongo DB is not an object', 'ERROR: Invalid MongoDB Object on: ' . $this->server . '@' . $this->db);
                 return null;
             }
             //end if
         } else {
             throw new Exception('ERROR: No Mongo Client Driver Available: select db');
         }
         //end if
     } catch (Exception $err) {
         $this->error((string) $the_conns[0]['hash'], 'MongoDB Select DB', 'Failed to select the DB: ' . $this->db . ' on ' . $this->server, 'ERROR: ' . $err->getMessage());
         return null;
     }
     //end try catch
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'mongodb|log', ['type' => 'set', 'data' => 'Selected Database: ' . $this->db, 'connection' => (string) $the_conns[0]['hash'], 'skip-count' => 'yes']);
         //--
     }
     //end if
     //--
     $opts = array();
     //--
     switch ((string) $method) {
         //-- collection methods
         case 'find':
             //--
             if (is_array($args[2])) {
                 $opts = (array) $args[2];
                 unset($args[2]);
             }
             //end if
             //--
             if (Smart::array_size($args[1]) <= 0) {
                 unset($args[1]);
             }
             //end if
             //--
             $collection = null;
             //--
             try {
                 if (is_object($this->mongodbclient)) {
                     // mongoclient does not need this
                 } elseif (is_object($this->mongoclient)) {
                     $collection = $this->mongodb->selectCollection($this->collection);
                 } else {
                     throw new Exception('ERROR: No Mongo Client Driver Available: select collection');
                 }
                 //end if
             } catch (Exception $err) {
                 $this->error((string) $the_conns[0]['hash'], 'MongoDB Select Collection', 'Failed to select the Collection: ' . $this->collection . ' on ' . $this->server . '@' . $this->db, 'ERROR: ' . $err->getMessage());
                 return null;
             }
             //end try catch
             if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                 //--
                 SmartFrameworkRegistry::setDebugMsg('db', 'mongodb|log', ['type' => 'set', 'data' => 'Selected Collection: ' . $this->collection, 'connection' => (string) $the_conns[0]['hash'], 'skip-count' => 'yes']);
                 //--
             }
             //end if
             //--
             $obj = array();
             //--
             if (is_object($this->mongodbclient)) {
                 //-- fix: select just particular fields
                 $opts['projection'] = array();
                 if (Smart::array_size($args[1]) > 0) {
                     for ($i = 0; $i < count($args[1]); $i++) {
                         $args[1][$i] = (string) trim((string) $args[1][$i]);
                         if ((string) $args[1][$i] != '') {
                             $opts['projection'][(string) $args[1][$i]] = 1;
                         }
                         //end if
                     }
                     //end for
                 }
                 //end if
                 //print_r($opts); die();
                 //--
                 $query = new \MongoDB\Driver\Query((array) $args[0], (array) $opts);
                 //print_r($query); die();
                 if (!is_object($query)) {
                     $this->error((string) $the_conns[0]['hash'], 'MongoDB Query', 'Mongo DB->Find() return no query', 'ERROR: ' . get_class($this) . '->' . __FUNCTION__ . '() :: ' . $this->server . '@' . $this->db);
                     return null;
                 }
                 //end if
                 //--
                 $cursor = $this->mongodbclient->executeQuery($this->db . '.' . $this->collection, $query);
                 if (!is_object($cursor)) {
                     $this->error((string) $the_conns[0]['hash'], 'MongoDB Cursor', 'Mongo DB->Find() return no cursor', 'ERROR: ' . get_class($this) . '->' . __FUNCTION__ . '() :: ' . $this->server . '@' . $this->db);
                     return null;
                 }
                 //end if
                 $cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);
                 //print_r($cursor); die();
                 if (is_object($cursor)) {
                     foreach ($cursor as $doc) {
                         $obj[] = (array) $doc;
                     }
                     //end foreach
                 }
                 //end foreach
                 //--
                 unset($cursor);
                 unset($query);
                 //--
             } elseif (is_object($this->mongoclient)) {
                 //--
                 $cursor = call_user_func_array(array($collection, $method), $args);
                 //--
                 if (!is_object($cursor)) {
                     $this->error((string) $the_conns[0]['hash'], 'MongoClient Cursor', 'Mongo DB->Find() return no cursor', 'ERROR: ' . get_class($this) . '->' . __FUNCTION__ . '() :: ' . $this->server . '@' . $this->db);
                     return null;
                 }
                 //end if
                 //--
                 if (Smart::array_size($opts) > 0) {
                     foreach ($opts as $key => $val) {
                         $cursor->{$key}($val);
                     }
                     //end foreach
                 }
                 //end if
                 //--
                 if (is_object($cursor)) {
                     foreach ($cursor as $doc) {
                         $obj[] = (array) $doc;
                     }
                     //end foreach
                 }
                 //end foreach
                 //--
                 unset($cursor);
                 //--
             } else {
                 //--
                 $this->error((string) $the_conns[0]['hash'], 'MongoDB Cursor', 'Mongo DB->Find() Invalid Client Driver', 'ERROR: ' . get_class($this) . '->' . __FUNCTION__ . '() :: ' . $this->server . '@' . $this->db);
                 return null;
                 //--
             }
             //end if else
             //--
             break;
             //--
         //--
         case 'findOne':
             //case 'findAndModify': // this is a special method not available in the new driver, thus is commented out
         //case 'findAndModify': // this is a special method not available in the new driver, thus is commented out
         case 'count':
         case 'insert':
         case 'update':
         case 'remove':
         case 'save':
         case 'distinct':
         case 'group':
         case 'getIndexInfo':
         case 'createIndex':
         case 'deleteIndex':
         case 'validate':
         case 'drop':
             // drops collection
             //--
             /*
             // Sample count with the new driver
             $cmd = new \MongoDB\Driver\Command( [ 'findOne' => $this->collection, 'query' => [] ] );
             $r = $this->mongodbclient->executeCommand( $this->db, $cmd );
             print_r($r);
             die();
             */
             //--
             try {
                 $collection = $this->mongodb->selectCollection($this->collection);
             } catch (Exception $err) {
                 $this->error((string) $the_conns[0]['hash'], 'MongoDB Select Collection', 'Failed to select the Collection: ' . $this->collection . ' on ' . $this->server . '@' . $this->db, 'ERROR: ' . $err->getMessage());
                 return null;
             }
             //end try catch
             if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                 //--
                 SmartFrameworkRegistry::setDebugMsg('db', 'mongodb|log', ['type' => 'set', 'data' => 'Selected Collection: ' . $this->collection, 'connection' => (string) $the_conns[0]['hash'], 'skip-count' => 'yes']);
                 //--
             }
             //end if
             //--
             $obj = call_user_func_array(array($collection, $method), $args);
             //--
             break;
             //--
         //--
         case 'dropDB':
             // drops DB
         // drops DB
         case 'listDBs':
         case 'getHosts':
         case 'killCursor':
             //-- mongo client methods
             $obj = call_user_func_array(array($this->mongodb, $method), $args);
             break;
         default:
             $this->error((string) $the_conns[0]['hash'], 'MongoDB Method', 'Mongo DB->' . $method . '() method is NOT implemented', 'ERROR: ' . get_class($this) . '->' . __FUNCTION__ . '() :: ' . $this->server . '@' . $this->db);
             return null;
     }
     //end switch
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'mongodb|total-queries', 1, '+');
         //--
         $time_end = (double) (microtime(true) - (double) $time_start);
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'mongodb|total-time', $time_end, '+');
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'mongodb|log', ['type' => 'nosql', 'data' => strtoupper($method), 'command' => array('Query' => $args, 'Options' => $opts), 'time' => Smart::format_number_dec($time_end, 9, '.', ''), 'connection' => (string) $the_conns[0]['hash']]);
         //--
     }
     //end if
     //--
     return $obj;
     // mixed
     //--
 }
 /**
  * Generate the ODS Document on the fly from an array of data
  *
  * @param STRING $y_table_name					:: The Table Name
  * @param STRING $y_arr_fields					:: Array of Header Fields
  * @param STRING $y_arr_data 					:: Array of Data
  *
  * @returns STRING 								:: The ODS Document Contents
  *
  */
 public function ODS_SpreadSheet($y_table_name, $y_arr_fields, $y_arr_data, $y_arr_process = array(), $y_arr_totals = array(), $y_arr_finals = array(), $y_arr_widths = array(), $y_arr_highlights = array())
 {
     // font-weight="bold"
     // fo:font-style="italic"
     // style:text-underline-type="single"
     //-- header
     $header = '' . '<?xml version="1.0" encoding="UTF-8"?' . '>' . "\n" . '<office:document-content ' . $this->open_document_ns . 'office:version="1.0">' . "\n" . $this->open_document_styles . '<office:body>' . "\n" . '<office:spreadsheet>' . "\n";
     //--
     //-- footer
     $footer = "\n" . '</office:spreadsheet>' . "\n" . '</office:body>' . "\n" . '</office:document-content>';
     //--
     //-- data
     $data = '';
     $data .= '<table:table table:style-name="ta1" table:print="true" table:name="' . Smart::escape_html($y_table_name) . '">' . "\n";
     //--
     //-- table headings
     $num_cols = Smart::array_size($y_arr_fields);
     $num_data = Smart::array_size($y_arr_data);
     //--
     $data .= '<table:table-row table:style-name="ro1">' . "\n";
     //--
     for ($i = 0; $i < $num_cols; $i++) {
         //--
         $data .= '<table:table-cell table:style-name="he1" office:value-type="string">';
         $data .= '<text:p>' . Smart::escape_html($y_arr_fields[$i]) . '</text:p>';
         $data .= '</table:table-cell>' . "\n";
         //--
     }
     //end for
     //--
     $data .= '</table:table-row>' . "\n";
     //--
     for ($n = 0; $n < $num_data; $n++) {
         //--
         $data .= '<table:table-row table:style-name="ro1">' . "\n";
         //--
         for ($i = 0; $i < $num_cols; $i++) {
             //--
             $kk = $i + $n;
             //--
             if ($i % $num_cols == 0 or $i % $num_cols == $num_cols - 1) {
                 $tmp_style = 'ce1';
                 // highlight first and last column
             } elseif ($i % 2) {
                 $tmp_style = 'ce3';
             } else {
                 $tmp_style = 'ce2';
             }
             //end if else
             //--
             if ((string) $y_arr_process[$i] == 'number' or (string) $y_arr_process[$i] == 'decimal2' or (string) $y_arr_process[$i] == 'decimal4') {
                 //--
                 if ((string) $y_arr_process[$i] == 'decimal2') {
                     $y_arr_data[$kk] = (string) Smart::format_number_dec($y_arr_data[$kk], 2, '.', '');
                 } elseif ((string) $y_arr_process[$i] == 'decimal4') {
                     $y_arr_data[$kk] = (string) Smart::format_number_dec($y_arr_data[$kk], 4, '.', '');
                 } else {
                     $y_arr_data[$kk] = (string) $y_arr_data[$kk];
                 }
                 //end if
                 //--
                 //$data .= '<table:table-cell table:style-name="'.$tmp_style.'" office:value-type="float" office:value="'.Smart::escape_html($y_arr_data[$kk]).'">';
                 $data .= '<table:table-cell table:style-name="' . $tmp_style . '" office:value-type="string">';
                 // preserve number as they are, force type string !!!
                 $data .= '<text:p>' . Smart::escape_html($y_arr_data[$kk]) . '</text:p>';
                 $data .= '</table:table-cell>' . "\n";
                 //--
             } else {
                 //--
                 $data .= '<table:table-cell table:style-name="' . $tmp_style . '" office:value-type="string">';
                 $data .= '<text:p>' . Smart::escape_html($y_arr_data[$kk]) . '</text:p>';
                 $data .= '</table:table-cell>' . "\n";
                 //--
             }
             //end if else
             //--
         }
         //end for
         //--
         $data .= '</table:table-row>' . "\n";
         //--
         $n += $num_cols - 1;
         // salt
         //--
     }
     //end for
     //--
     //-- totals row
     if (Smart::array_size($y_arr_totals) > 0) {
         //--
         $data .= '<table:table-row table:style-name="ro1">' . "\n";
         //--
         for ($i = 0; $i < $num_cols; $i++) {
             //--
             $data .= '<table:table-cell table:style-name="he2" office:value-type="string">';
             $data .= '<text:p>' . $y_arr_totals[$i] . '</text:p>';
             $data .= '</table:table-cell>' . "\n";
             //--
         }
         //end for
         //--
         $data .= '</table:table-row>' . "\n";
         //--
     }
     //end if
     //--
     //-- final row
     if (Smart::array_size($y_arr_finals) > 0) {
         //--
         $data .= '<table:table-row table:style-name="ro1">' . "\n";
         //--
         for ($i = 0; $i < $num_cols; $i++) {
             //--
             $data .= '<table:table-cell table:style-name="he3" office:value-type="string">';
             $data .= '<text:p>' . $y_arr_finals[$i] . '</text:p>';
             $data .= '</table:table-cell>' . "\n";
             //--
         }
         //end for
         //--
         $data .= '</table:table-row>' . "\n";
         //--
     }
     //end if
     //--
     //--
     $data .= '</table:table>' . "\n";
     //--
     //--
     return (string) $this->OpenDocument_Template((string) $this->mime_ods, $header . "\n" . $data . "\n" . $footer);
     //--
 }
 public static function calc_percent($number, $maxnumber)
 {
     //--
     $maxnumber = 0 + $maxnumber;
     //--
     if ($maxnumber <= 0) {
         $out = 0;
     } else {
         $out = (0 + $number) / $maxnumber * 100;
     }
     //end if else
     //--
     return Smart::format_number_dec($out, 2, '.', '');
     //--
 }
 /**
  * this is the Run Command
  *
  * @access 		private
  * @internal
  *
  */
 private function run_command($method, array $args)
 {
     //--
     if (!$this->socket) {
         $this->error(true, 'Redis Connection / Run', 'Connection Failed', 'Method: ' . $method);
         // fatal error
         return null;
     }
     //end if
     //--
     $method = (string) $method;
     $args = (array) $args;
     //--
     array_unshift($args, $method);
     $cmd = '*' . count($args) . "\r\n";
     // no. of arguments
     foreach ($args as $z => $item) {
         $cmd .= '$' . strlen($item) . "\r\n";
         // str length
         $cmd .= $item . "\r\n";
         // key contents
     }
     //end foreach
     //--
     if ((string) $cmd == '') {
         //--
         $this->error(true, 'Redis Run Command', 'Empty commands are not allowed ...', '');
         // fatal error
         return null;
         //--
     }
     //end if
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         $time_start = microtime(true);
         //--
     }
     //end if
     //--
     @fwrite($this->socket, $cmd);
     //--
     $response = $this->parse_response($method);
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'redis|total-queries', 1, '+');
         //--
         $time_end = (double) (microtime(true) - (double) $time_start);
         SmartFrameworkRegistry::setDebugMsg('db', 'redis|total-time', $time_end, '+');
         //--
         SmartFrameworkRegistry::setDebugMsg('db', 'redis|log', ['type' => 'nosql', 'data' => strtoupper($method) . ' :: ' . $this->description, 'command' => SmartParser::text_endpoints((string) $cmd, 1024, true, '[...data-longer-than-1024-bytes-is-not-logged-all-here...]'), 'time' => Smart::format_number_dec($time_end, 9, '.', ''), 'connection' => (string) $this->socket]);
         //--
     }
     //end if
     //--
     return $response;
     //--
 }
 private function number_preformated($number, $dec_size = 1)
 {
     //--
     return Smart::format_number_dec(round($number, $dec_size), $dec_size, '.', ',');
     //--
 }
 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
     //--
 }
    /**
     * PgSQL Query :: Write Ignore - Catch Duplicate Key Violation or Foreign Key Violation Errors (This is the equivalent of MySQL's INSERT IGNORE / UPDATE IGNORE / DELETE IGNORE, but it can catch UNIQUE violations on both: INSERT / UPDATE / DELETE statements and also can catch FOREIGN KEY violations).
     * This function is intended to be used only for write type queries like: INSERT / UPDATE / DELETE which can be ignored if unique violations or foreign key violations and will return the # of affected rows or zero if an exception raised.
     * The catch of PostgreSQL exceptions is handled completely by this function so there is no need for a catch errors outside.
     *
     * IMPORTANT:
     * This function needs the pgsql notice message tracking enabled in PHP (not ignored); This must be set in php.ini (pgsql.ignore_notice = 0).
     * The internal mechanism of this function to catch UNIQUE or FOREIGN KEYS violations is that the EXCEPTIONS are catch at the PostgreSQL level in a DO block.
     * This is the best approach to handle safe UPSERT or INSERT IGNORE / UPDATE IGNORE / DELETE IGNORE like queries in high load envionments or to avoid fatal errors when a INSERT / UPDATE / DELETE violates a unique key or a foreign key with PostgreSQL.
     * This function can be used inside transactions blocks but never use this function to execute statements as: BEGIN, START TRANSACTION, COMMIT, ROLLBACK or SET statements, as the context is incompatible.
     * HINTS:
     * On PostgreSQL 9.5/later there is an alternative which can be used directly with write_data() without the need of this function as the following statement: INSERT ... ON CONFLICT DO NOTHING/UPDATE ... (as the equivalent of INSERT IGNORE / UPSERT), but the following statements are still missing (not implemented): UPDATE ... ON CONFLICT DO NOTHING / DELETE ... ON CONFLICT DO NOTHING .
     * This function will remain in the future to offer backward compatibility with PostgreSQL 8.4 ... 9.5 even if PostgreSQL at some moment will have ON CONFLICT DO implemented for all 3 INSERT / UPDATE / DELETE.
     *
     * @param STRING $queryval						:: the query
     * @param STRING $params_or_title 				:: *optional* array of parameters ($1, $2, ... $n) or query title for easy debugging
     * @param RESOURCE $y_connection				:: the connection
     * @return ARRAY 								:: [0 => 'control-message', 1 => #affected-rows]
     */
    public static function write_igdata($queryval, $params_or_title = '', $y_connection = 'DEFAULT')
    {
        //==
        $y_connection = self::check_connection($y_connection, 'WRITE-IG-DATA');
        //==
        //-- samples
        // $queryval = 'UPDATE "tablename" SET "field" = \'value\' WHERE ("id_field" = \'val1\')';
        // $queryval = 'INSERT INTO "tablename" ("desiredfield1", "desiredfield2") VALUES (\'val1\', \'val2\')';
        //--
        // ##### 'pgsql.ignore_notice' must be set to 0 in PHP.INI (checked via connect) #####
        //--
        /* PRE-CHECK (DO NOT ALLOW IN TRANSACTION BLOCKS) - No More Necessary !!, now can be safe used also in transactions as the exceptions are catch in the DO block
        	$transact_status = @pg_transaction_status($y_connection);
        	if(($transact_status === PGSQL_TRANSACTION_INTRANS) OR ($transact_status === PGSQL_TRANSACTION_INERROR)) {
        		self::error($y_connection, 'WRITE-IG-DATA', 'ERROR: Write Ignore cannot be used inside Transaction Blocks ...', $queryval, '');
        		return array('errortransact: '.'Write Ignore cannot be used inside Transaction Blocks', 0);
        	} //end if
        	*/
        //--
        //--
        $time_start = 0;
        if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
            $time_start = microtime(true);
        }
        //end if
        //--
        //--
        $use_param_query = false;
        if (strpos((string) $queryval, '$') !== false and Smart::array_size($params_or_title) > 0) {
            $use_param_query = true;
        }
        //end if
        //--
        if ($use_param_query === true) {
            $the_query_title = '';
        } else {
            $the_query_title = (string) $params_or_title;
        }
        //end if else
        //--
        //--
        /* At the moment, in PgSQL 9.5 only works ON CONFLICT DO NOTHING for INSERT (for UPDATE statements fails ...)
        	if(version_compare(self::check_server_version($y_connection), '9.6') >= 0) {
        		//--
        		$xmode = 'affected';
        		$vmode = '[ON CONFLICT DO NOTHING]';
        		//--
        		$prep_query = (string) $queryval.' ON CONFLICT DO NOTHING'; // fix for PostgreSQL >= 9.5 :: RETURNING *
        		//--
        		if($use_param_query === true) {
        			$result = @pg_query_params($y_connection, $prep_query, $params_or_title); // NOTICE: parameters are only allowed in ONE command not combined statements
        		} else {
        			$result = @pg_query($y_connection, $prep_query);
        		} //end if else
        		//--
        	} else {
        	*/
        //--
        if ((string) ini_get('pgsql.ignore_notice') != '0') {
            // {{{SYNC-PGSQL-NOTIF-CHECK}}}
            self::error($y_connection, 'WRITE-IG-DATA', 'Check PgSQL PHP.INI Settings', 'SETTINGS: PostgreSQL Notifications need to be ENABLED in PHP.INI !', 'SET in PHP.INI this: pgsql.ignore_notice = 0');
            return array('errorinits: PostgreSQL Notifications need to be ENABLED in PHP.INI', 0);
        }
        //end if
        //--
        $xmode = 'notice';
        $vmode = '[Catch EXCEPTION on Violations for: Unique / Foreign Key]';
        //--
        if ($use_param_query === true) {
            $queryval = (string) self::prepare_param_query((string) $queryval, (array) $params_or_title, $y_connection);
        }
        //end if
        //--
        $unique_id = 'WrIgData_PgSQL_' . Smart::uuid_10_seq() . '_' . Smart::uuid_10_str() . '_' . Smart::uuid_10_num() . '_' . sha1(SmartUtils::client_ident_private_key()) . '_' . sha1(SmartUtils::get_visitor_tracking_uid() . ':' . Smart::uuid_36('pgsql-write-ig') . ':' . Smart::uuid_45('pgsql-write-ig')) . '_Func';
        // this must be a unique that cannot guess to avoid dollar escaping injections
        //--
        $prep_query = (string) '
	DO LANGUAGE plpgsql
	$' . $unique_id . '$
	DECLARE affected_rows BIGINT;
	BEGIN
		-- do the query an safe catch exceptions (unique key, foreign key)
			affected_rows := 0;
	' . "\t\t" . trim(rtrim($queryval, ';')) . ';' . '
			GET DIAGNOSTICS affected_rows = ROW_COUNT;
			RAISE NOTICE \'SMART-FRAMEWORK-PGSQL-NOTICE: AFFECTED ROWS #%\', affected_rows;
			RETURN;
		EXCEPTION
			WHEN unique_violation THEN RAISE NOTICE \'SMART-FRAMEWORK-PGSQL-NOTICE: AFFECTED ROWS #0\';
			WHEN foreign_key_violation THEN RAISE NOTICE \'SMART-FRAMEWORK-PGSQL-NOTICE: AFFECTED ROWS #0\'; -- this is a different behaviour than ON CONFLICT DO NOTHING in PgSQL 9.5 or later versions ...
	END
	$' . $unique_id . '$;
	';
        //--
        $result = @pg_query($y_connection, $prep_query);
        //--
        //} //end if else
        //--
        //--
        $error = '';
        $affected = 0;
        if (!$result) {
            $error = 'Query FAILED:' . "\n" . @pg_last_error($y_connection);
        } else {
            //if((string)$xmode == 'notice') {
            $affected = (int) self::get_notice_smart_affected_rows(@pg_last_notice($y_connection));
            // in this case we can only monitor affected rows via a custom notice (the only possible way to return something from anonymous pgsql functions ...)
            //} else { // affected
            //	$affected = @pg_affected_rows($result); // for PostgreSQL >= 9.5
            //} //end if else
        }
        //end if else
        //--
        //--
        $time_end = 0;
        if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
            $time_end = (double) (microtime(true) - (double) $time_start);
        }
        //end if
        //--
        //--
        if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
            //--
            SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|total-queries', 1, '+');
            //--
            SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|total-time', $time_end, '+');
            //--
            $dbg_query_params = '';
            //--
            if (strtoupper(substr(trim($queryval), 0, 5)) == 'BEGIN' or strtoupper(substr(trim($queryval), 0, 17)) == 'START TRANSACTION' or strtoupper(substr(trim($queryval), 0, 6)) == 'COMMIT' or strtoupper(substr(trim($queryval), 0, 8)) == 'ROLLBACK') {
                // ERROR
                self::error($y_connection, 'WRITE-IG-DATA ' . $vmode, 'ERROR: This function cannot handle TRANSACTION Specific Statements ...', $queryval, $the_query_title);
                return array('errorsqlstatement: ' . 'This function cannot handle TRANSACTION Specific Statements', 0);
            } elseif (strtoupper(substr(trim($queryval), 0, 4)) == 'SET ') {
                // ERROR
                self::error($y_connection, 'WRITE-IG-DATA ' . $vmode, 'ERROR: This function cannot handle SET Statements ...', $queryval, $the_query_title);
                return array('errorsqlstatement: ' . 'This function cannot handle SET Statements', 0);
            } else {
                SmartFrameworkRegistry::setDebugMsg('db', 'pgsql|log', ['type' => 'write', 'data' => 'WRITE / IGNORE ' . $vmode . ' :: ' . $the_query_title, 'query' => $queryval, 'params' => $dbg_query_params, 'rows' => $affected, 'time' => Smart::format_number_dec($time_end, 9, '.', ''), 'connection' => (string) $y_connection]);
            }
            //end if else
            //--
        }
        //end if
        //--
        //--
        if (strlen($error) > 0) {
            //--
            $message = 'errorsqlwriteoperation: ' . $error;
            //--
            self::error($y_connection, 'WRITE-IG-DATA ' . $vmode, $error, $queryval, $the_query_title);
            return array($message, 0);
            //--
        } else {
            //--
            $record = @pg_fetch_row($result);
            //--
            $message = 'oksqlwriteoperation';
            // this can be extended to detect extra notices
            //--
        }
        //end else
        //--
        //--
        if (is_resource($result)) {
            // check in case of error
            @pg_free_result($result);
        }
        //end if
        //--
        //--
        return array($message, Smart::format_number_int($affected, '+'));
        //--
    }