public function text($y_textkey)
 {
     //--
     if ((string) $y_textkey == '') {
         Smart::log_warning('Empty Key for Text Context Translator - Area: ' . $this->area . ' ; SubArea: ' . $this->subarea);
         return '{Empty Translation Key}';
     }
     //end if
     //--
     $text = (string) SmartTextTranslations::getTranslationByKey($this->area, $this->subarea, $y_textkey);
     //--
     if ((string) $text == '') {
         Smart::log_warning('Undefined Key: [' . $y_textkey . '] for Text Context Translator - Area: ' . $this->area . ' ; SubArea: ' . $this->subarea);
         return '{Undefined Translation Key: ' . Smart::escape_html($y_textkey) . '}';
     }
     //end if
     //--
     return (string) $text;
     //--
 }
 public function setDayNames($y_day_names_arr)
 {
     //--
     if (!is_array($y_day_names_arr)) {
         Smart::log_warning(__CLASS__ . '::' . __FUNCTION__ . '() expect an array as parameter !');
         return;
     }
     //end if
     //--
     if (Smart::array_size($y_day_names_arr) != 7) {
         Smart::log_warning(__CLASS__ . '::' . __FUNCTION__ . '() expect the size of array to be 7 !');
         return;
     }
     //end if
     //--
     $this->wday_names = (array) $y_day_names_arr;
     //--
 }
 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";
     //--
 }
Esempio n. 4
0
 /**
  * Set the (in-memory) Auth Login Data
  * It can be used just once per execution (session) as it stores the data using constants,
  * and the data cannot be changed after a successful or failed authentication has set.
  *
  * @param 	STRING 	$y_user_id 				:: The user (login) ID used to authenticate the user ; Mandatory ; it can be the UserID from DB or if not using a DB must supply a unique ID to identify the user like username
  * @param 	STRING 	$y_user_alias			:: The user (login) Alias, used to display the logged in user ; Mandatory ; can be the same as the login ID or different (Ex: login ID can be 'myUserName' and this 'myUserName' ; or: login ID can be 5017 and this 'myUserName')
  * @param 	STRING 	$y_user_email 			:: *OPTIONAL* The user Email ; if email is used as login ID this may be redundant !
  * @param 	STRING 	$y_user_fullname 		:: *OPTIONAL* The user Full Name (First Name + Last Name)
  * @param 	ARRAY 	$y_user_privileges_list :: *OPTIONAL* The user Privileges List as array that list all the current user privileges
  * @param 	STRING 	$y_user_quota 			:: *OPTIONAL* The user (storage) Quota
  * @param 	ARRAY 	$y_user_metadata 		:: *OPTIONAL* The user metainfo, associative array key => value
  * @param 	STRING 	$y_realm 				:: *OPTIONAL* The user Authentication Realm(s)
  * @param 	ENUM 	$y_method 				:: *OPTIONAL* The authentication method used: HTTP-BASIC / HTTP-DIGEST / OTHER
  * @param 	STRING 	$y_pass					:: *OPTIONAL* The user login password (will be stored in memory as Blowfish encrypted to avoid exposure)
  *
  * @return 	BOOLEAN							:: TRUE if all data is OK, FALSE if not or try to reauthenticate under the same execution (which is not allowed ; must be just once per execution)
  */
 public static function set_login_data($y_user_id, $y_user_alias, $y_user_email = '', $y_user_fullname = '', $y_user_privileges_list = array('none', 'no-privilege'), $y_user_quota = -1, $y_user_metadata = array(), $y_realm = 'DEFAULT', $y_method = '', $y_pass = '')
 {
     //--
     if (self::$AuthCompleted !== false) {
         // avoid to re-auth
         Smart::log_warning('Re-Authentication is not allowed ...');
         return;
     }
     //end if
     self::$AuthCompleted = true;
     //--
     self::$AuthData = array();
     // reset the auth data
     //--
     $y_user_id = trim((string) $y_user_id);
     // user ID
     $y_user_alias = trim((string) $y_user_alias);
     // username (user alias ; can be the same as userID or different)
     $y_user_email = trim((string) $y_user_email);
     $y_user_fullname = trim((string) $y_user_fullname);
     //--
     if (is_array($y_user_privileges_list)) {
         $y_user_privileges_list = (string) strtolower((string) Smart::array_to_list((array) $y_user_privileges_list));
     } else {
         $y_user_privileges_list = (string) strtolower((string) trim((string) $y_user_privileges_list));
         // in this case can be provided a raw list of privileges (Example: '<none>, <no-privilege>')
     }
     //end if else
     //--
     $y_user_quota = Smart::format_number_int($y_user_quota);
     // can be also negative
     //--
     switch (strtoupper((string) $y_method)) {
         case 'HTTP-BASIC':
             $y_method = 'HTTP-BASIC';
             break;
         case 'HTTP-DIGEST':
             $y_method = 'HTTP-DIGEST';
             break;
         case 'OTHER':
         default:
             $y_method = 'OTHER';
     }
     //end switch
     //--
     $the_key = '#' . Smart::random_number(10000, 99999) . '#';
     $the_pass = '';
     if ((string) $y_pass != '') {
         $the_pass = SmartCipherCrypto::encrypt('hash/sha1', (string) $the_key, (string) $y_pass);
     }
     //end if
     //--
     if ((string) $y_user_id != '') {
         //--
         self::$AuthData['USER_ID'] = (string) $y_user_id;
         self::$AuthData['USER_EMAIL'] = (string) $y_user_email;
         self::$AuthData['USER_ALIAS'] = (string) $y_user_alias;
         self::$AuthData['USER_FULLNAME'] = (string) $y_user_fullname;
         self::$AuthData['USER_PRIVILEGES'] = (string) $y_user_privileges_list;
         self::$AuthData['USER_QUOTA'] = (int) $y_user_quota;
         self::$AuthData['USER_METADATA'] = (array) $y_user_metadata;
         self::$AuthData['USER_LOGIN_REALM'] = (string) $y_realm;
         self::$AuthData['USER_LOGIN_METHOD'] = (string) $y_method;
         self::$AuthData['USER_LOGIN_PASS'] = (string) $the_pass;
         self::$AuthData['KEY'] = (string) $the_key;
         //--
         return true;
         //--
     } else {
         //--
         return false;
         //--
     }
     //end if
     //--
 }
Esempio n. 5
0
 private function folder_iterator($recurring, $dir_name, $include_dot_files, $search_pattern = '', $search_prevent_file = '', $search_prevent_override = '')
 {
     //--
     $recurring = (bool) $recurring;
     $dir_name = (string) $dir_name;
     $include_dot_files = (bool) $include_dot_files;
     $search_pattern = (string) $search_pattern;
     $search_prevent_file = (string) $search_prevent_file;
     $search_prevent_override = (string) $search_prevent_override;
     //--
     if ((string) $dir_name == '') {
         Smart::log_warning('LibFileSys // ReadsFolderRecurring // Dir Name is Empty !');
         return;
         // this function does not return anything, but just stop here in this case
     }
     //end if
     //-- fix invalid path (must end with /)
     $dir_name = SmartFileSysUtils::add_dir_last_slash($dir_name);
     //-- protection
     SmartFileSysUtils::raise_error_if_unsafe_path($dir_name);
     //--
     @clearstatcache();
     //--
     $this->pattern_search_str = $search_pattern;
     $this->search_prevent_file = $search_prevent_file;
     $this->search_prevent_override = $search_prevent_override;
     //--
     if (SmartFileSystem::file_or_link_exists($dir_name) and !is_file($dir_name)) {
         // can be dir or link
         //list
         //--
         if ($handle = opendir($dir_name)) {
             //---------------------------------------
             while (false !== ($file = readdir($handle))) {
                 //--
                 if ((string) $file != '.' and (string) $file != '..') {
                     //--
                     if ($include_dot_files or !$include_dot_files and substr($file, 0, 1) != '.') {
                         //--
                         SmartFileSysUtils::raise_error_if_unsafe_path($dir_name . $file);
                         //-- params to see if counted or added to pattern matches
                         $tmp_allow_addition = 1;
                         $tmp_add_pattern = 0;
                         //-- this is for #private folders, will prevent searching in folders containing for example this file: .private-folder but can be overriden by the $search_prevent_override option exluding a particular path like folder/private/user1
                         if (strlen($search_prevent_file) > 0 and is_file($dir_name . $search_prevent_file)) {
                             if (strlen($search_prevent_override) <= 0 or strlen($search_prevent_override) > 0 and !is_file($dir_name . $search_prevent_override)) {
                                 $tmp_allow_addition = 0;
                             }
                             //end if
                         }
                         //end if
                         //-- this is a search pattern (search pattern does not apply to folders !!) ; if no empty will populate the pattern matches array with all files and folders matching ; to include all, use * or a particular search for the rest like myfile1
                         if ((string) $search_pattern == '' or is_dir($dir_name . $file)) {
                             if ($tmp_allow_addition) {
                                 if ($this->list_files_and_dirs) {
                                     $tmp_add_pattern = 1;
                                 }
                                 //end if
                             }
                             //end if
                         } else {
                             if ($this->limit_search_files <= 0 or Smart::array_size($this->pattern_file_matches) < $this->limit_search_files) {
                                 if ((string) $search_pattern == '*' or (string) $search_pattern == '[image]' and (substr($file, -4, 4) == '.png' or substr($file, -4, 4) == '.gif' or substr($file, -4, 4) == '.jpg' or substr($file, -5, 5) == '.jpeg') or (string) $search_pattern != '*' and (string) $search_pattern != '[image]' and stripos($file, $search_pattern) !== false) {
                                     if ($tmp_allow_addition) {
                                         if ($this->list_files_and_dirs) {
                                             $tmp_add_pattern = 1;
                                         }
                                         //end if
                                     }
                                     //end if
                                 } else {
                                     $tmp_allow_addition = 0;
                                 }
                                 //end if else
                             }
                             //end if
                         }
                         //end if
                         //--
                         if ($this->limit_search_files > 0) {
                             // the dir should not be taken in count here
                             if ($this->num_files + $this->num_links >= $this->limit_search_files) {
                                 break;
                             }
                             //end if
                         }
                         //end if
                         //--
                         if (!is_link($dir_name . $file)) {
                             //--
                             if (is_dir($dir_name . $file)) {
                                 //-- dir
                                 if ($tmp_allow_addition) {
                                     //--
                                     $tmp_fsize = Smart::format_number_int(@filesize($dir_name . $file), '+');
                                     //--
                                     $this->num_dirs++;
                                     $this->num_size += $tmp_fsize;
                                     $this->num_dirs_size += $tmp_fsize;
                                     //--
                                     $tmp_fsize = 0;
                                     //--
                                     if ($tmp_add_pattern) {
                                         if ($recurring) {
                                             // if recurring, add the full path
                                             $this->pattern_dir_matches[$dir_name . $file] = @filemtime($dir_name . $file);
                                         } else {
                                             // if not recurring, add just base path, without dirname prefix
                                             $this->pattern_dir_matches[$file] = @filemtime($dir_name . $file);
                                         }
                                         //end if else
                                     }
                                     //end if
                                     //--
                                 }
                                 //end if
                                 //--
                                 if ($recurring) {
                                     //-- we go search inside even if this folder name may not match the search pattern, it is a folder, except if dissalow addition from above
                                     $this->folder_iterator($recurring, SmartFileSysUtils::add_dir_last_slash($dir_name . $file), $include_dot_files, $search_pattern, $search_prevent_file, $search_prevent_override);
                                     //--
                                 }
                                 //end if
                                 //--
                             } else {
                                 //-- file
                                 if ($tmp_allow_addition) {
                                     //--
                                     $tmp_fsize = Smart::format_number_int(@filesize($dir_name . $file), '+');
                                     //--
                                     $this->num_files++;
                                     $this->num_size += $tmp_fsize;
                                     $this->num_files_size += $tmp_fsize;
                                     //--
                                     $tmp_fsize = 0;
                                     //--
                                     if ($tmp_add_pattern) {
                                         if ($recurring) {
                                             // if recurring, add the full path
                                             $this->pattern_file_matches[$dir_name . $file] = @filemtime($dir_name . $file);
                                         } else {
                                             // if not recurring, add just base path, without dirname prefix
                                             $this->pattern_file_matches[$file] = @filemtime($dir_name . $file);
                                         }
                                         //end if else
                                     }
                                     //end if
                                     //--
                                 }
                                 //end if
                                 //--
                             }
                             //end else
                             //--
                         } else {
                             //-- link
                             if ($tmp_allow_addition) {
                                 //--
                                 $link_result = SmartFileSystem::link_get_origin($dir_name . $file);
                                 //--
                                 if (empty($link_result) or (string) $link_result == '' or !SmartFileSystem::file_or_link_exists($link_result)) {
                                     //--
                                     // case of readlink error ..., not includding broken links, they are useless
                                     //--
                                 } else {
                                     //--
                                     $tmp_size_arr = array();
                                     $tmp_fsize = 0;
                                     //$tmp_size_arr = (array) @lstat($dir_name.$file);
                                     //$tmp_fsize = Smart::format_number_int($tmp_size_arr[7],'+'); // $tmp_size_arr[7] -> size, but may break compare if on a different file system or in distributed storage on various OS
                                     //--
                                     $this->num_links++;
                                     //--
                                     if (file_exists($dir_name . $file)) {
                                         // here file_exists must be tested because if broken link not stat on it (filemtime) to avoid log un-necessary errors
                                         //-- bugfix: not if broken link
                                         $this->num_size += $tmp_fsize;
                                         if ($tmp_add_pattern) {
                                             if (is_dir($dir_name . $file)) {
                                                 $this->num_dirs++;
                                                 $this->num_dirs_size += $tmp_fsize;
                                                 if ($recurring) {
                                                     // if recurring, add the full path
                                                     $this->pattern_dir_matches[$dir_name . $file] = @filemtime($dir_name . $file);
                                                 } else {
                                                     // if not recurring, add just base path, without dirname prefix
                                                     $this->pattern_dir_matches[$file] = @filemtime($dir_name . $file);
                                                 }
                                                 //end if else
                                             } else {
                                                 $this->num_files++;
                                                 $this->num_files_size += $tmp_fsize;
                                                 if ($recurring) {
                                                     // if recurring, add the full path
                                                     $this->pattern_file_matches[$dir_name . $file] = @filemtime($dir_name . $file);
                                                 } else {
                                                     // if not recurring, add just base path, without dirname prefix
                                                     $this->pattern_file_matches[$file] = @filemtime($dir_name . $file);
                                                 }
                                                 //end if else
                                             }
                                             //end if else
                                         }
                                         //end if
                                         //--
                                     }
                                     //end if
                                     //--
                                     $tmp_fsize = 0;
                                     $tmp_size_arr = array();
                                     //--
                                 }
                                 //end if else
                                 //--
                             }
                             //end if
                             //--
                         }
                         //end if else
                         //--
                     }
                     //end if
                     //--
                 }
                 //end if(. ..)
                 //--
             }
             //end while
             //---------------------------------------
             @closedir($handle);
             //---------------------------------------
         } else {
             //---------------------------------------
             $this->errors_arr[] = $dir_name;
             //---------------------------------------
         }
         //end else
         //--
     } else {
         //---------------------------------------
         // nothing ...
         //---------------------------------------
     }
     //end if else
     //--
 }
 private function solr_connect()
 {
     //--
     if (!is_object($this->instance)) {
         //--
         $options = array('hostname' => $this->host, 'port' => $this->port);
         //--
         $this->protocol = 'http://';
         if ((string) $this->ssl === true) {
             $options['secure'] = true;
             $this->protocol = 'https://';
         }
         //end if
         //--
         if ((string) $this->user != '') {
             $options['login'] = $this->user;
             $options['login'] = $this->password;
         }
         //end if
         //--
         $options['timeout'] = $this->timeout;
         //--
         $options['path'] = $this->db;
         //--
         $options['wt'] = $this->mode;
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             //--
             SmartFrameworkRegistry::setDebugMsg('db', 'solr|log', ['type' => 'open-close', 'data' => 'Solr DB :: Open Connection [' . $this->mode . '] to DB: ' . $this->db . ' :: ' . $this->description . ' @ HOST: ' . $this->protocol . $this->host . ':' . $this->port . ' # User: '******'Solr ERROR # Connect # ' . $e->getMessage());
             //--
         }
         //end try catch
         //--
         return false;
         //--
     } else {
         //--
         return true;
         //--
     }
     //end if else
     //--
 }
Esempio n. 7
0
 /**
  * Decompress RAW LZS
  *
  * @access 		private
  * @internal
  *
  */
 public static function decompressRawLZS($compressed)
 {
     //--
     $unarch = trim(self::RawInflate((string) $compressed));
     //-- checksum verification
     $arr = explode('#CHECKSUM-SHA1#', $unarch);
     $unarch = trim($arr[0]);
     $checksum = trim($arr[1]);
     //--
     if ((string) SmartHashCrypto::sha1($unarch) != (string) $checksum) {
         Smart::log_warning('SmartArchiverLZS/decompressRawLZS: Checksum Failed');
         return '';
         // string is corrupted, avoid to return
     }
     //end if
     //--
     return @hex2bin(strtolower($unarch));
     //--
 }
 /**
  * Set a single value for settings into the current controller as PageView Settings (Cfgs)
  *
  * @param 	STRING 		$param			:: the parameter to be set
  * @param 	STRING 		$value			:: the value
  *
  * @return 	BOOL						:: TRUE if OK, FALSE if not
  */
 public final function PageViewSetCfg($param, $value)
 {
     //--
     if (is_array($param) or is_object($param) or is_array($value) or is_object($value)) {
         return false;
     }
     //end if
     //--
     $param = strtolower((string) $param);
     //--
     if ((string) $param != '') {
         if (is_bool($value)) {
             // fix for bool
             if ($value === true) {
                 $value = 'yes';
                 // true
             } elseif ($value === false) {
                 $value = '';
                 // false
             }
             //end if else
         }
         //end if
         if (in_array((string) $param, (array) $this->availsettings)) {
             $this->pagesettings[(string) $param] = (string) $value;
         } else {
             Smart::log_warning('SmartAbstractAppController / PageViewSetCfg: Invalid Parameter: ' . $param);
         }
         //end if else
     }
     //end if
     //--
     return true;
     //--
 }
 /**
  * Displays the Redis Errors and HALT EXECUTION (This have to be a FATAL ERROR as it occur when a FATAL Redis ERROR happens or when Data Exchange fails)
  * PRIVATE
  *
  * @param BOOL $is_fatal :: TRUE / FALSE if the Error is Fatal or Not
  * @param STRING $y_area :: The Area
  * @param STRING $y_error_message :: The Error Message to Display
  * @param STRING $y_query :: The query
  * @param STRING $y_warning :: The Warning Title
  *
  * @return :: HALT EXECUTION WITH ERROR MESSAGE
  *
  */
 private function error($is_fatal, $y_area, $y_error_message, $y_query = '', $y_warning = '')
 {
     //--
     $this->err = true;
     // required, to halt driver
     //--
     $is_fatal = (bool) $is_fatal;
     //--
     if ($is_fatal !== false) {
         // FATAL ERROR
         //--
         $def_warn = 'Execution Halted !';
         $y_warning = (string) trim((string) $y_warning);
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             $width = 750;
             $the_area = (string) $y_area;
             if ((string) $y_warning == '') {
                 $y_warning = (string) $def_warn;
             }
             //end if
             $the_error_message = 'Operation FAILED: ' . $def_warn . "\n" . $y_error_message;
             $the_params = '- ' . $this->description . ' -';
             $the_query_info = (string) $y_query;
             if ((string) $the_query_info == '') {
                 $the_query_info = '-';
                 // query cannot e empty in this case (templating enforcement)
             }
             //end if
         } else {
             $width = 550;
             $the_area = '';
             $the_error_message = 'Operation FAILED: ' . $def_warn;
             $the_params = '';
             $the_query_info = '';
             // do not display query if not in debug mode ... this a security issue if displayed to public ;)
         }
         //end if else
         //--
         $out = SmartComponents::db_error_message('Redis Client', 'Redis', 'Caching', 'Server', 'lib/core/img/db/redis_logo_trans.png', $width, $the_area, $the_error_message, $the_params, $the_query_info);
         //--
         Smart::raise_error('#REDIS@' . $this->socket . '# :: Q# // Redis Client :: ERROR :: ' . $y_area . "\n" . '*** Error-Message: ' . $y_error_message . "\n" . '*** Command:' . "\n" . $y_query, $out);
         die('');
         // just in case
         //--
     } else {
         // SILENT WARNING
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             //--
             SmartFrameworkRegistry::setDebugMsg('db', 'redis|log', ['type' => 'metainfo', 'data' => 'Redis SILENT WARNING: ' . $y_area . "\n" . $y_query . "\n" . 'Error-Message: ' . $y_error_message . "\n" . 'The settings for this Redis instance allow just silent warnings on connection fail.' . "\n" . 'All next method calls to this Redis instance will be discarded silently ...']);
             //--
         }
         //end if
         //--
         Smart::log_warning('#REDIS@' . $this->socket . '# :: Q# // Redis :: WARNING :: ' . $y_area . "\n" . '*** Error-Message: ' . $y_error_message . "\n" . '*** Command:' . "\n" . $y_query);
         //--
     }
     //end if else
     //--
 }
Esempio n. 10
0
 private function create_from_array($y_array)
 {
     //--
     if (!is_array($y_array)) {
         Smart::log_warning('SmartXmlComposer / create_from_array expects an Array as parameter ...');
         return '<error>XML Writer requires an Array as parameter</error>';
     }
     //end if
     //--
     //--
     $out = '';
     //--
     $arrtype = Smart::array_type_test($y_array);
     // 0: not an array ; 1: non-associative ; 2: associative
     //--
     foreach ($y_array as $key => $val) {
         //--
         if ($arrtype === 2) {
             // fix keys for associative array
             if (is_numeric($key) or (string) $key == '') {
                 $key = (string) '_' . $key;
                 // numeric or empty keys are not allowed: _#
             }
             //end if
         }
         //end if
         //--
         if (is_array($val)) {
             if (is_numeric($key)) {
                 // this can happen only if non-associative array as for associative arrays the numeric key is fixed above as _#
                 $out .= $this->create_from_array($val);
             } else {
                 $out .= '<' . Smart::escape_html($key) . '>' . "\n" . $this->create_from_array($val) . '</' . Smart::escape_html($key) . '>' . "\n";
             }
             //end if else
         } elseif ((string) $val != '') {
             $out .= '<' . Smart::escape_html($key) . '>' . Smart::escape_html($val) . '</' . Smart::escape_html($key) . '>' . "\n";
         } else {
             $out .= '<' . Smart::escape_html($key) . ' />' . "\n";
         }
         //end if else
         //--
     }
     //end foreach
     //--
     //--
     return (string) $out;
     //--
 }
Esempio n. 11
0
 public function __construct($y_type, $y_title, $y_arr_data, $y_format = 'png', $y_display_graph2 = true, $y_display_graph_depths = true)
 {
     //--
     if (!function_exists('imagecreatetruecolor')) {
         Smart::log_warning('"[ERROR] :: SmartImgGfxCharts :: PHP-GD TrueColor extension is missing ...');
         return;
     }
     //end if
     //--
     switch ((string) $y_type) {
         case 'vbars':
             $this->type = 1;
             break;
         case 'hbars':
             $this->type = 2;
             break;
         case 'dots':
             $this->type = 3;
             break;
         case 'lines':
             $this->type = 4;
             break;
         case 'pie':
             $this->type = 5;
             break;
         case 'donut':
             $this->type = 6;
             break;
         default:
             Smart::log_warning('"[ERROR] :: SmartImgBizCharts :: Invalid Chart Type: ' . $y_type . ' ...');
             return;
     }
     //end if
     //--
     $this->title = (string) SmartUnicode::deaccent_str((string) $y_title);
     //--
     if ((string) $y_format == 'gif') {
         $this->format = 'gif';
     } else {
         $this->format = 'png';
     }
     //end if else
     //--
     $this->skin = 1;
     // by now only this color schema !
     //--
     if (!is_array($y_arr_data)) {
         $y_arr_data = array();
     }
     //end if else
     //--
     $y_display_graph2 = (bool) $y_display_graph2;
     $y_display_graph_depths = (bool) $y_display_graph_depths;
     $this->x = $this->y = $this->z = $this->w = $this->v = array();
     //--
     for ($i = 0; $i < count($y_arr_data); $i++) {
         //--
         $tmp_arr = (array) $y_arr_data[$i];
         //--
         $this->x[$i] = (string) $tmp_arr['x'];
         // label
         $this->y[$i] = (double) $tmp_arr['y'];
         // 1st series
         if ($y_display_graph2 !== false) {
             $this->z[$i] = (double) $tmp_arr['z'];
             // 2nd series
         }
         //end if
         if ($y_display_graph_depths !== false) {
             $this->w[$i] = (int) $tmp_arr['w'];
             // buble size
         }
         //end if
         $this->v[$i] = (string) $tmp_arr['v'];
         // custom color
         //--
     }
     //end for
     //--
 }
 public function browse_url($url, $method = 'GET', $ssl_version = '', $user = '', $pwd = '', $proxy = array())
 {
     //-- reset
     $this->reset();
     //--
     //--
     if ($this->debug) {
         $run_time = microtime(true);
     }
     //end if
     //--
     //--
     $this->connect_timeout = (int) $this->connect_timeout;
     if ($this->connect_timeout < 1) {
         $this->connect_timeout = 1;
     }
     //end if
     if ($this->connect_timeout > 120) {
         $this->connect_timeout = 120;
     }
     //end if
     //--
     $this->exec_timeout = (int) $this->exec_timeout;
     if ($this->exec_timeout > 0) {
         if ($this->exec_timeout < 30) {
             $this->exec_timeout = 30;
         }
         //end if
         if ($this->exec_timeout > 300) {
             $this->exec_timeout = 300;
         }
         //end if
     } else {
         $this->exec_timeout = 0;
     }
     //end if else
     //--
     //--
     $this->status = 999;
     //--
     //-- log action
     if ($this->debug) {
         $this->log .= '[INF] CURL HTTP(S)/FTP Robot Browser :: Browse :: url \'' . $url . '\' @ Auth-User: '******' // Auth-Pass-Length: (' . strlen($pwd) . ') // Method: ' . $method . ' // SSLVersion: ' . $ssl_version . "\n";
         $this->log .= '[INF] CURL Protocol: ' . $this->protocol . "\n";
         $this->log .= '[INF] Connection TimeOut: ' . $this->connect_timeout . "\n";
         $this->log .= '[INF] Execution TimeOut: ' . $this->exec_timeout . "\n";
     }
     //end if
     //--
     //-- method
     $this->method = (string) strtoupper(trim((string) $method));
     //--
     //-- separations
     $this->url_parts = (array) Smart::separe_url_parts($url);
     $protocol = (string) $this->url_parts['protocol'];
     $server = (string) $this->url_parts['server'];
     $port = (string) $this->url_parts['port'];
     $path = (string) $this->url_parts['path'];
     //--
     if ($this->debug) {
         $this->log .= '[INF] Analize of the URL: ' . @print_r($this->url_parts, 1) . "\n";
     }
     //end if
     //--
     $is_ftp = false;
     $use_ssl_tls = false;
     switch ((string) $protocol) {
         case 'http://':
             break;
         case 'https://':
             $use_ssl_tls = true;
             break;
         case 'ftp://':
             $is_ftp = true;
             break;
         case 'ftps://':
             $is_ftp = true;
             $use_ssl_tls = true;
             break;
         default:
             //--
             if ($this->debug) {
                 $this->log .= '[ERR] Unsupported URL Type: [' . $protocol . '] for URL: ' . $url . "\n";
             }
             //end if
             //--
             Smart::log_warning('LibCurlHttp(s)Ftp // GetFromURL () // Unsupported URL Type: [' . $protocol . '] for URL: ' . $url);
             //--
             return (array) $this->answer(0, $url, $ssl_version, $user);
             //--
     }
     //end switch
     //--
     //--
     if (!function_exists('curl_init')) {
         //--
         if ($this->debug) {
             $this->log .= '[ERR] PHP CURL Extension is missing' . "\n";
         }
         //end if
         //--
         Smart::log_warning('LibCurlHttp(s)Ftp // GetFromURL () // CURL Extension is missing ...');
         //--
         return (array) $this->answer(0, $url, $ssl_version, $user);
         //--
     }
     //end if
     //--
     //--
     $this->curl = @curl_init();
     // Initialise a cURL handle
     //--
     if (!$this->curl) {
         //--
         if ($this->debug) {
             $this->log .= '[ERR] PHP CURL Init Failed' . "\n";
         }
         //end if
         //--
         Smart::log_warning('LibCurlHttp(s)Ftp // GetFromURL () // CURL Init Failed ...');
         //--
         return (array) $this->answer(0, $url, $ssl_version, $user);
         //--
     }
     //end if
     //--
     if (Smart::array_size($this->rawheaders) > 0) {
         foreach ($this->rawheaders as $key => $val) {
             $this->raw_headers[] = (string) $key . ': ' . $val;
         }
         //end foreach
     }
     //end if
     //-- set allowed protocols: HTTP / HTTPS / FTP / FTPS
     @curl_setopt($this->curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | CURLPROTO_FTPS);
     //--
     //-- set user agent
     @curl_setopt($this->curl, CURLOPT_USERAGENT, (string) $this->useragent);
     //--
     //-- timeouts
     @curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, (int) $this->connect_timeout);
     if ($this->exec_timeout > 0) {
         @curl_setopt($this->curl, CURLOPT_TIMEOUT, (int) $this->exec_timeout);
     }
     //end if
     //--
     //-- protocol
     if ((string) $this->protocol == '1.1') {
         $this->raw_headers[] = (string) 'Connection: close';
         @curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
     } else {
         // 1.0
         @curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
     }
     //end if else
     //--
     //-- proxy
     $is_using_proxy = false;
     if (Smart::array_size($proxy) > 0) {
         // If the $proxy variable is set, then use: $proxy['ip:port'] ; $proxy['type'] ; $proxy['auth-user'] ; $proxy['auth-pass']
         //--
         if ((string) $proxy['ip:port'] != '') {
             //--
             $pxy_type = '';
             switch ((string) strtoupper(trim((string) $proxy['type']))) {
                 case 'SOCKS4':
                     $is_using_proxy = true;
                     $pxy_type = CURLPROXY_SOCKS4;
                     break;
                 case 'SOCKS4A':
                     $is_using_proxy = true;
                     $pxy_type = CURLPROXY_SOCKS4A;
                     break;
                 case 'SOCKS5':
                     $is_using_proxy = true;
                     $pxy_type = CURLPROXY_SOCKS5;
                     break;
                 case 'SOCKS5H':
                     $is_using_proxy = true;
                     $pxy_type = CURLPROXY_SOCKS5_HOSTNAME;
                     break;
                 case 'HTTP':
                 default:
                     if ($is_ftp) {
                         $proxy['type'] = 'N/A';
                     } else {
                         $is_using_proxy = true;
                         $proxy['type'] = 'HTTP';
                     }
                     //end if
                     $pxy_type = CURLPROXY_HTTP;
             }
             //end switch
             //--
             if ($is_using_proxy) {
                 //--
                 if ($this->debug) {
                     $this->log .= '[INF] Using Proxy: ' . $proxy['ip:port'] . ' [Type: ' . $proxy['type'] . ']' . "\n";
                 }
                 //end if
                 //--
                 $this->cproxy = (array) $proxy;
                 if ((string) $this->cproxy['auth-pass'] != '') {
                     $this->cproxy['auth-pass'] = '******' . strlen($proxy['auth-pass']) . ') *****';
                 }
                 //end if
                 //--
                 @curl_setopt($this->curl, CURLOPT_PROXY, (string) $proxy['ip:port']);
                 @curl_setopt($this->curl, CURLOPT_PROXYTYPE, $pxy_type);
                 //--
                 if ((string) $proxy['auth-user'] != '') {
                     //--
                     if ($this->debug) {
                         $this->log .= '[INF] Proxy Authentication will be attempted for USERNAME = \'' . $proxy['auth-user'] . '\' ; PASSWORD(' . strlen($proxy['auth-pass']) . ') *****' . "\n";
                     }
                     //end if
                     //--
                     @curl_setopt($this->curl, CURLOPT_PROXYUSERPWD, (string) $proxy['auth-user'] . ':' . $proxy['auth-pass']);
                     //@curl_setopt($this->curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); // this does not work at all, thus let CURL choose ...: CURLAUTH_BASIC | CURLAUTH_DIGEST
                     //--
                 }
                 //end if
                 //--
             }
             //end if
             //--
         }
         //end if
         //--
     }
     //end if
     //--
     //-- auth
     if ((string) $user != '') {
         //--
         if ($this->debug) {
             $this->log .= '[INF] Authentication will be attempted for USERNAME = \'' . $user . '\' ; PASSWORD(' . strlen($pwd) . ') *****' . "\n";
         }
         //end if
         //-- $this->raw_headers[] = 'Authorization: Basic '.base64_encode($user.':'.$pwd); // it is better to use as below as it can handle more auth types :-)
         @curl_setopt($this->curl, CURLOPT_USERPWD, (string) $user . ':' . $pwd);
         //@curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); // this does not work at all, thus let CURL choose ...: CURLAUTH_BASIC | CURLAUTH_DIGEST
         //--
     }
     //end if
     //--
     //-- SSL/TLS Options
     $browser_protocol = '';
     //--
     if ($use_ssl_tls) {
         //--
         if (!function_exists('openssl_open')) {
             //--
             if ($this->debug) {
                 $this->log .= '[ERR] PHP OpenSSL Extension is required to perform SSL requests' . "\n";
             }
             //end if
             //--
             Smart::log_warning('LibCurlHttp(s)Ftp // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // PHP OpenSSL Extension not installed ...');
             //--
             return (array) $this->answer(0, $url, $ssl_version, $user);
             //--
         }
         //end if
         //--
         switch (strtolower((string) $ssl_version)) {
             case 'ssl':
                 $browser_protocol = CURL_SSLVERSION_DEFAULT;
                 // default SSL
                 break;
             case 'sslv3':
                 $browser_protocol = CURL_SSLVERSION_SSLv3;
                 // SSLv3
                 break;
             case 'tls':
             default:
                 $browser_protocol = CURL_SSLVERSION_TLSv1;
                 // TLSv1.x
         }
         //end switch
         //--
         @curl_setopt($this->curl, CURLOPT_SSLVERSION, $browser_protocol);
         //--
         if (defined('SMART_FRAMEWORK_SSL_CA_PATH')) {
             if ((string) SMART_FRAMEWORK_SSL_CA_PATH != '') {
                 @curl_setopt($this->curl, CURLOPT_CAPATH, Smart::real_path((string) SMART_FRAMEWORK_SSL_CA_PATH));
             }
             //end if
         }
         //end if
         @curl_setopt($this->curl, CURLOPT_SSL_CIPHER_LIST, (string) SMART_FRAMEWORK_SSL_CIPHERS);
         @curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, (bool) SMART_FRAMEWORK_SSL_VFY_PEER_NAME);
         // FIX: use vfy peer name instead of SMART_FRAMEWORK_SSL_VFY_HOST as there is no fine tunning here ...
         @curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, (bool) SMART_FRAMEWORK_SSL_VFY_PEER);
         // (bool)SMART_FRAMEWORK_SSL_VFY_PEER_NAME 		:: CURL is missing the option to specific allow/dissalow the peer name (allow also wildcard names *)
         // (bool)SMART_FRAMEWORK_SSL_ALLOW_SELF_SIGNED 	:: CURL is missing the option to specific allow/disallow self-signed certificates but verified above
         // (bool)SMART_FRAMEWORK_SSL_DISABLE_COMPRESS 	:: CURL is missing the option to disable SSL/TLS compression (help mitigate the CRIME attack vector)
         //--
     }
     //end if
     //--
     //-- other cURL options that are required
     @curl_setopt($this->curl, CURLOPT_HEADER, true);
     @curl_setopt($this->curl, CURLOPT_COOKIESESSION, true);
     @curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
     @curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
     //--
     //--
     if (Smart::array_size($this->cookies) > 0) {
         $send_cookies = '';
         foreach ($this->cookies as $key => $value) {
             if ((string) $key != '') {
                 if ((string) $value != '') {
                     $send_cookies .= (string) SmartHttpUtils::encode_var_cookie($key, $value);
                 }
                 //end if
             }
             //end if
         }
         //end foreach
         if ((string) $send_cookies != '') {
             $this->raw_headers[] = (string) 'Cookie: ' . $send_cookies;
         }
         //end if
         $send_cookies = '';
     }
     //end if
     //--
     $have_post_vars = false;
     if (Smart::array_size($this->postvars) > 0) {
         $post_string = '';
         foreach ((array) $this->postvars as $key => $val) {
             $post_string .= (string) SmartHttpUtils::encode_var_post($key, $val);
         }
         //end foreach
         if ((string) $post_string != '') {
             if ((string) $this->method == 'GET') {
                 $this->method = 'POST';
             }
             //end if
             $have_post_vars = true;
             @curl_setopt($this->curl, CURLOPT_POSTFIELDS, (string) $post_string);
         }
         //end if
         $post_string = '';
     } elseif ((string) $this->poststring != '') {
         if ((string) $this->method == 'GET') {
             $this->method = 'POST';
         }
         //end if
         $have_post_vars = true;
         @curl_setopt($this->curl, CURLOPT_POSTFIELDS, (string) $this->poststring);
     } elseif ((string) $this->jsonrequest != '') {
         $this->raw_headers[] = 'Content-Type: application/json';
         $this->raw_headers[] = 'Content-Length: ' . strlen($this->jsonrequest);
     } elseif ((string) $this->xmlrequest != '') {
         $this->raw_headers[] = 'Content-Type: application/xml';
         $this->raw_headers[] = 'Content-Length: ' . strlen($this->xmlrequest);
     }
     //end if else
     //--
     switch ((string) $this->method) {
         case 'GET':
             break;
         case 'POST':
             if ($have_post_vars) {
                 @curl_setopt($this->curl, CURLOPT_POST, true);
             }
             //end if
             break;
         case 'HEAD':
         case 'PUT':
         case 'DELETE':
         default:
             if ($have_post_vars) {
                 @curl_setopt($this->curl, CURLOPT_POST, true);
             }
             //end if
             @curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, (string) $this->method);
     }
     //end switch
     //--
     if (Smart::array_size($this->raw_headers) > 0) {
         // request headers are constructed above
         @curl_setopt($this->curl, CURLOPT_HTTPHEADER, (array) $this->raw_headers);
     }
     //end if
     //--
     //-- Execute a Curl request
     @curl_setopt($this->curl, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
     @curl_setopt($this->curl, CURLOPT_FRESH_CONNECT, true);
     @curl_setopt($this->curl, CURLOPT_FORBID_REUSE, true);
     @curl_setopt($this->curl, CURLOPT_URL, (string) $url);
     //--
     if (!$this->curl) {
         //--
         if ($this->debug) {
             $this->log .= '[ERR] CURL Aborted before Execution' . "\n";
         }
         //end if
         //--
         Smart::log_warning('LibCurlHttp(s)Ftp // GetFromURL () // CURL Aborted before Execution ...');
         //--
         return (array) $this->answer(0, $url, $ssl_version, $user);
         //--
     }
     //end if
     //--
     $results = @curl_exec($this->curl);
     $error = @curl_errno($this->curl);
     //--
     //-- eval results
     $bw_info = array();
     $is_ok = 0;
     //--
     if ($results) {
         //--
         $is_ok = 1;
         //--
         $bw_info = (array) @curl_getinfo($this->curl);
         //--
         if ($is_ftp) {
             //--
             $this->header = 'CURL Browser :: FTP(s) have no headers ...';
             $this->body = (string) $results;
             //--
         } else {
             // http
             //--
             $hd_len = (int) $bw_info['header_size'];
             // get header length
             //--
             if ($hd_len > 0) {
                 //--
                 $this->header = (string) substr((string) $results, 0, $hd_len);
                 $this->body = (string) substr((string) $results, $hd_len);
                 //--
             } else {
                 //--
                 $this->header = (string) $results;
                 $this->body = '';
                 //--
                 $is_ok = 0;
                 //--
                 if ($this->debug) {
                     Smart::log_notice('LibCurlHttp(s)Ftp // GetFromURL () // CURL Execution Failed to Separe HTTP Header from Body. Reported (invalid) Header size is: [' . $hd_len . ']');
                     $this->log .= '[ERR] CURL Execution Failed to Separe HTTP Header from Body. Invalid Header size: [' . $hd_len . ']' . "\n";
                 }
                 //end if
                 //--
             }
             //end if else
             //--
         }
         //end if else
         //--
         $results = '';
         // free memory
         //--
         $is_unauth = false;
         if ((string) $bw_info['http_code'] == '401') {
             //--
             $is_unauth = true;
             //--
             if ($this->debug) {
                 if ((string) $user != '') {
                     $this->log .= '[ERR] HTTP Authentication Failed for URL: [User='******']: ' . $url . "\n";
                     Smart::log_notice('LibCurlHttp(s)Ftp // GetFromURL // HTTP Authentication Failed for URL: [User='******']: ' . $url);
                 } else {
                     $this->log .= '[ERR] HTTP Authentication is Required for URL: ' . $url . "\n";
                     Smart::log_notice('LibCurlHttp(s)Ftp // GetFromURL // HTTP Authentication is Required for URL: ' . $url);
                 }
                 //end if
             }
             //end if
             //--
         }
         //end if
         //--
         if ($is_unauth and $this->no_content_stop_if_unauth) {
             //--
             $this->body = '';
             // in this case (by settings) no content (response body) should be returned
             //--
         }
         //end if
         //--
         if ($error) {
             //--
             $is_ok = 0;
             //--
             if ($this->debug) {
                 $this->log .= '[ERR] CURL Execution Reported some Errors. ErrorCode: [' . $error . ']' . "\n";
                 Smart::log_notice('LibCurlHttp(s)Ftp // GetFromURL () // CURL Execution Reported some Errors. ErrorCode: [' . $error . ']');
             }
             //end if
             //--
         }
         //end if
         //--
         $this->status = (int) $bw_info['http_code'];
         //--
     } else {
         //--
         $is_ok = 0;
         //--
         $this->log .= '[ERR] CURL Returned No Results. ErrorCode: [' . $error . ']' . "\n";
         //--
     }
     //end if
     //--
     if ($is_unauth) {
         //--
         $is_ok = 0;
         //--
     }
     //end if
     //--
     //--
     $this->close_connection();
     //--
     //--
     if ($this->debug) {
         $run_time = microtime(true) - $run_time;
         $this->log .= '[INF] Total Time: ' . $run_time . ' sec.' . "\n";
     }
     //end if
     //--
     //--
     return (array) $this->answer($is_ok, $url, $ssl_version, $user, $bw_info);
     //--
 }
 /**
  * Unset a Key into the persistent Cache
  *
  * @param STRING 	$y_realm	The Cache Realm
  * @param STRING 	$y_key		The Cache Key ; Use * for All Keys in that Realm
  *
  * @return BOOLEAN	Returns True if the key(s) was/were unset or false if not
  */
 public static function unsetKey($y_realm, $y_key)
 {
     //--
     if (!self::isActive()) {
         return false;
     }
     //end if
     //--
     if (!self::validateRealm((string) $y_realm)) {
         Smart::log_warning('Persistent Cache / Invalid Realm: ' . $y_realm);
         return false;
     }
     //end if
     if ((string) $y_key != '*') {
         if (!self::validateKey((string) $y_key)) {
             Smart::log_warning('Persistent Cache / Invalid Key: ' . $y_key);
             return false;
         }
         //end if
     }
     //end if
     //--
     self::initCacheManager();
     //--
     if ((string) $y_realm == '') {
         return (bool) self::$redis->del((string) $y_key);
     } else {
         if ((string) $y_key != '*') {
             return (bool) self::$redis->del((string) $y_realm . ':' . $y_key);
         } else {
             $rarr = (array) self::$redis->keys((string) $y_realm . ':*');
             $err = 0;
             if (Smart::array_size($rarr) > 0) {
                 foreach ($rarr as $key => $rark) {
                     if ((string) $rark != '') {
                         $del = self::$redis->del((string) $rark);
                         if ($del <= 0) {
                             $err++;
                         }
                         //end if
                     }
                     //end if
                 }
                 //end foreach
             }
             //end if
             if ($err > 0) {
                 return false;
             } else {
                 return true;
             }
             //end if else
         }
         //end if
     }
     //end if else
     //--
 }
 public static function decode_mime_fileurl($y_enc_msg_file, $y_ctrl_key)
 {
     //--
     $y_enc_msg_file = (string) trim((string) $y_enc_msg_file);
     if ((string) $y_enc_msg_file == '') {
         Smart::log_warning('Mail-Utils / Decode Mime File URL: Empty Message File Path has been provided. This means the URL link will be unavaliable (empty) to assure security protection.');
         return '';
     }
     //end if
     if (!SmartFileSysUtils::check_file_or_dir_name($y_enc_msg_file)) {
         Smart::log_warning('Mail-Utils / Decode Mime File URL: Invalid Message File Path has been provided. This means the URL link will be unavaliable (empty) to assure security protection. Message File: ' . $y_enc_msg_file);
         return '';
     }
     //end if
     //--
     $y_ctrl_key = (string) trim((string) $y_ctrl_key);
     if ((string) $y_ctrl_key == '') {
         Smart::log_warning('Mail-Utils / Decode Mime File URL: Empty Controller Key has been provided. This means the URL link will be unavaliable (empty) to assure security protection.');
         return '';
     }
     //end if
     if (SMART_FRAMEWORK_ADMIN_AREA === true) {
         // {{{SYNC-ENCMIMEURL-CTRL-PREFIX}}}
         $y_ctrl_key = (string) 'AdminMailUtilArea/' . $y_ctrl_key;
     } else {
         $y_ctrl_key = (string) 'IndexMailUtilArea/' . $y_ctrl_key;
     }
     //end if
     //--
     $the_sep_arr = (array) self::mime_separe_part_link($y_enc_msg_file);
     $y_enc_msg_file = (string) $the_sep_arr['msg'];
     $the_msg_part = (string) $the_sep_arr['part'];
     unset($the_sep_arr);
     //--
     $arr = array();
     // {{{SYNC-MIME-ENCRYPT-ARR}}}
     $arr['error'] = '';
     // by default, no error
     //--
     if ((string) SMART_APP_VISITOR_COOKIE == '') {
         $arr['error'] = 'WARNING: Access Forbidden ... No Visitor ID set ...!';
         return (array) $arr;
     }
     //end if
     //--
     if ((string) $the_msg_part != '') {
         $the_msg_part = strtolower(trim((string) SmartUtils::url_hex_decode((string) $the_msg_part)));
     }
     //end if
     //--
     $decoded_link = trim((string) SmartUtils::crypto_decrypt((string) $y_enc_msg_file, 'SmartFramework//MimeLink' . SMART_FRAMEWORK_SECURITY_KEY));
     $dec_arr = (array) explode("\n", trim((string) $decoded_link));
     //print_r($dec_arr);
     //--
     $arr['creation-time'] = trim((string) $dec_arr[0]);
     $arr['message-file'] = trim((string) $dec_arr[1]);
     $arr['message-part'] = trim((string) $the_msg_part);
     $arr['access-key'] = trim((string) $dec_arr[2]);
     $arr['bw-unique-key'] = trim((string) $dec_arr[3]);
     $arr['sf-robot-key'] = trim((string) $dec_arr[4]);
     //-- check if file path is valid
     if ((string) $arr['message-file'] == '') {
         $arr = array();
         $arr['error'] = 'ERROR: Empty Message Path ...';
         return (array) $arr;
     }
     //end if
     if (!SmartFileSysUtils::check_file_or_dir_name($arr['message-file'])) {
         $arr = array();
         $arr['error'] = 'ERROR: Unsafe Message Path Access ...';
         return (array) $arr;
     }
     //end if
     //--
     $browser_os_ip_identification = SmartUtils::get_os_browser_ip();
     // get browser and os identification
     //-- re-compose the access key
     $crrtime = (int) $arr['creation-time'];
     $access_key = sha1('MimeLink:' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . SMART_APP_VISITOR_COOKIE . ':' . $arr['message-file'] . '>' . $y_ctrl_key);
     $uniq_key = sha1('Time=' . $crrtime . '#' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . $access_key . '-' . SmartUtils::unique_auth_client_private_key() . ':' . $arr['message-file'] . '>' . $y_ctrl_key);
     $self_robot_key = sha1('Time=' . $crrtime . '#' . SmartAuth::get_login_id() . '*' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . trim($browser_os_ip_identification['signature']) . '$' . $access_key . ':' . $arr['message-file'] . '>' . $y_ctrl_key);
     //-- check access key
     if ((string) $arr['error'] == '') {
         if ((string) $access_key != (string) $arr['access-key']) {
             $arr = array();
             $arr['error'] = 'ERROR: Access Forbidden ... Invalid ACCESS KEY ...';
         }
         //end if
     }
     //end if
     //-- check the client key
     if ((string) $arr['error'] == '') {
         //--
         $ok_client_key = false;
         //--
         if ((string) $the_msg_part == '' and (string) $arr['bw-unique-key'] == (string) $uniq_key) {
             // no message part, allow only client browser
             $ok_client_key = true;
         } elseif ((string) $the_msg_part != '' and ((string) $arr['bw-unique-key'] == (string) $uniq_key or (string) $browser_os_ip_identification['bw'] == '@s#' and (string) $arr['sf-robot-key'] == (string) $self_robot_key)) {
             $ok_client_key = true;
         } else {
             $ok_client_key = false;
         }
         //end if else
         //--
         if ($ok_client_key != true) {
             $arr = array();
             $arr['error'] = 'ERROR: Access Forbidden ... Invalid CLIENT KEY ...';
         }
         //end if
         //--
     }
     //end if
     //--
     return (array) $arr;
     //--
 }
 /**
  * Displays the MySQL Errors and HALT EXECUTION (This have to be a FATAL ERROR as it occur when a FATAL MySQLi ERROR happens or when a Query Syntax is malformed)
  * PRIVATE
  *
  * @return :: HALT EXECUTION WITH ERROR MESSAGE
  *
  */
 private static function error($y_connection_id, $y_area, $y_error_message, $y_query, $y_params_or_title, $y_warning = '')
 {
     //--
     $err_log = $y_area . "\n" . '*** Error-Message: ' . $y_error_message . "\n" . '*** Params / Title:' . "\n" . print_r($y_params_or_title, 1) . "\n" . '*** Query:' . "\n" . $y_query;
     //--
     if (defined('SMART_SOFTWARE_SQLDB_FATAL_ERR') and SMART_SOFTWARE_SQLDB_FATAL_ERR === false) {
         Smart::log_warning('#MYSQL-DB@' . $y_connection_id . '# :: Q# // MySQL :: WARNING :: ' . $err_log);
         throw new Exception('#MYSQL-DB@' . $y_connection_id . '# :: Q# // MySQL :: EXCEPTION :: ' . $y_area . "\n" . $y_error_message);
         return;
     }
     //end if
     //--
     $def_warn = 'Execution Halted !';
     $y_warning = (string) trim((string) $y_warning);
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         $width = 750;
         $the_area = (string) $y_area;
         if ((string) $y_warning == '') {
             $y_warning = (string) $def_warn;
         }
         //end if
         $the_error_message = 'Operation FAILED: ' . $def_warn . "\n" . $y_error_message;
         if (is_array($y_params_or_title)) {
             $the_params = '*** Params ***' . "\n" . print_r($y_params_or_title, 1);
         } elseif ((string) $y_params_or_title != '') {
             $the_params = '[ Reference Title ]: ' . $y_params_or_title;
         } else {
             $the_params = '- No Params or Reference Title -';
         }
         //end if
         $the_query_info = (string) trim((string) $y_query);
         if ((string) $the_query_info == '') {
             $the_query_info = '-';
             // query cannot e empty in this case (templating enforcement)
         }
         //end if
     } else {
         $width = 550;
         $the_area = '';
         $the_error_message = 'Operation FAILED: ' . $def_warn;
         $the_params = '';
         $the_query_info = '';
         // do not display query if not in debug mode ... this a security issue if displayed to public ;)
     }
     //end if else
     //--
     $out = SmartComponents::db_error_message('MySQLi Client', 'MySQL', 'SQL/DB', 'Server', 'modules/smart-extra-libs/img/mysql_logo_trans.png', $width, $the_area, $the_error_message, $the_params, $the_query_info);
     //--
     Smart::raise_error('#MYSQL-DB@' . $y_connection_id . '# :: Q# // MySQL :: ERROR :: ' . $err_log, $out);
     die('');
     // just in case
     //--
 }
Esempio n. 16
0
 /**
  * Load/Save a cache file from Memory or from a URL
  *
  * @param STRING 	$y_cache_file_extension		:: File Extension (example: '.ext')
  * @param STRING 	$y_cache_prefix				:: prefix dir (at least 3 chars) ended by slash (Example: 'prefix/')
  * @param STRING 	$y_load_url					:: URL to Load (Ex: http(s)://some/test.txt ; memory://some.unique.key)
  * @param STRING	$y_content					:: just for memory:// ; contents of the file to be saved into cache - [set] mode ; if this is empty will just get
  * @param INT 		$y_cache_expire				:: 0=never ; (>0)=seconds
  * @param ENUM 		$y_encrypted				:: yes/no to encrypt the file content
  * @return MIXED								:: cached contents
  */
 public static function load_cached_content($y_cache_file_extension, $y_cache_prefix, $y_load_url, $y_content = '', $y_cache_expire = 0, $y_encrypted = 'no')
 {
     // v.150209
     //--
     $y_load_url = (string) $y_load_url;
     //--
     if ((string) $y_load_url == '') {
         Smart::log_warning('Utils // Load From Cache ... Empty URL ...');
         return '';
     }
     //end if
     //--
     //--
     $y_cache_file_extension = Smart::safe_validname($y_cache_file_extension);
     //--
     $y_cache_expire = Smart::format_number_int($y_cache_expire, '+');
     //--
     $y_cache_prefix = (string) $y_cache_prefix;
     //--
     if (strlen($y_cache_prefix) >= 3 and strlen($y_cache_prefix) <= 64) {
         //--
         $y_cache_prefix = SmartFileSysUtils::add_dir_last_slash($y_cache_prefix);
         // fix trailing slash
         //--
     } else {
         //--
         $y_cache_prefix = 'default/';
         //--
     }
     //end if
     //--
     //--
     $unique_id = (string) SmartHashCrypto::sha1('@@::SmartFramework::Content::Cache@@' . $y_load_url);
     //--
     $dir = 'tmp/cache/' . $y_cache_prefix . SmartFileSysUtils::prefixed_sha1_path($unique_id);
     SmartFileSysUtils::raise_error_if_unsafe_path($dir);
     //--
     $file = (string) $dir . $unique_id . $y_cache_file_extension;
     SmartFileSysUtils::raise_error_if_unsafe_path($file);
     //--
     //--
     if (!is_dir($dir)) {
         SmartFileSystem::dir_recursive_create($dir);
     }
     // end if
     //--
     $protect_file = $dir . 'index.html';
     if (!is_file($protect_file)) {
         SmartFileSystem::write($protect_file, '');
     }
     //end if
     //--
     //-- will go through this only if cache expired or no cache
     if (!is_file($file) or is_file($file) and $y_cache_expire > 0 and @filemtime($file) + $y_cache_expire < time()) {
         //-- read
         if (substr($y_load_url, 0, 9) == 'memory://' and (string) $y_content != '') {
             //-- set the content from memory
             $tmp_content = (string) $y_content;
             $tmp_result = '1';
             $tmp_code = '200';
             //--
         } elseif (substr($y_load_url, 0, 9) != 'memory://') {
             //--
             $arr = self::load_url_or_file($y_load_url);
             // [OK]
             $tmp_result = $arr['result'];
             $tmp_code = $arr['code'];
             $tmp_content = $arr['content'];
             $arr = array();
             //--
         }
         //end if else
         //-- if required, apply encryption
         if ((string) $y_encrypted == 'yes') {
             //--
             $tmp_content = self::crypto_blowfish_encrypt($tmp_content);
             //--
         }
         //end if
         //-- write to cache
         if ((string) $tmp_result == '1' and (string) $tmp_code == '200') {
             //--
             SmartFileSystem::write($file, $tmp_content);
             // save file to cache (safe write is controlled via locks)
             //--
         }
         //end if
         //--
         $tmp_content = '';
         //--
     }
     //end if
     //--
     //-- get from cache
     $out = SmartFileSystem::read($file);
     //--
     if ((string) $y_encrypted == 'yes') {
         $out = self::crypto_blowfish_decrypt($out);
     }
     //end if
     //--
     //--
     return $out;
     //--
 }
Esempio n. 17
0
 private function referenceContentsByAlias($alias)
 {
     //--
     do {
         //-
         if (!isset($this->yaml_arr_saved_groups[$alias])) {
             Smart::log_warning('YAML // Bad group name: ' . $alias);
             break;
             // just in case
         }
         //end if
         //--
         $groupPath = $this->yaml_arr_saved_groups[$alias];
         $value = $this->result;
         //--
         foreach ($groupPath as $z => $k) {
             $value = $value[$k];
         }
         //end foreach
         //--
     } while (false);
     //--
     return $value;
     //--
 }
Esempio n. 18
0
 /**
  * Start the Session on request
  *
  */
 public static function start()
 {
     //=====
     //--
     if (self::$started !== false) {
         return;
         // avoid start session if already started ...
     }
     //end if
     self::$started = true;
     // avoid run start again
     //--
     //=====
     //--
     $browser_os_ip_identification = SmartUtils::get_os_browser_ip();
     // get browser and os identification
     //--
     if ((string) $browser_os_ip_identification['bw'] == '@s#' or (string) $browser_os_ip_identification['bw'] == 'bot') {
         return;
         // in this case start no session for robots or the self browser (as they do not need to share info between many visits) ; if the self browser fail to identify will be at least identified as robot in the worst case
     }
     //end if
     //--
     //=====
     //-- no log as the cookies can be dissalowed by the browser
     if ((string) SMART_APP_VISITOR_COOKIE == '') {
         return;
         // session need cookies
     }
     //end if
     //--
     //=====
     //--
     $sf_sess_mode = 'files';
     $sf_sess_area = 'default-sess';
     $sf_sess_ns = 'unknown';
     $sf_sess_dir = 'tmp/sess';
     //--
     //=====
     if (!defined('SMART_FRAMEWORK_SESSION_PREFIX')) {
         Smart::log_warning('FATAL ERROR: Invalid Session Prefix :: SMART_FRAMEWORK_SESSION_PREFIX');
         return;
     }
     //end if
     if (strlen(SMART_FRAMEWORK_SESSION_PREFIX) < 3 or strlen(SMART_FRAMEWORK_SESSION_PREFIX) > 9) {
         Smart::log_warning('WARNING: Session Prefix must have a length between 3 and 9 characters :: SMART_FRAMEWORK_SESSION_PREFIX');
         return;
     }
     //end if
     if (!preg_match('/^[a-z\\-]+$/', (string) SMART_FRAMEWORK_SESSION_PREFIX)) {
         Smart::log_warning('WARNING: Session Prefix contains invalid characters :: SMART_FRAMEWORK_SESSION_PREFIX');
         return;
     }
     //end if
     //--
     if (!defined('SMART_FRAMEWORK_SESSION_NAME')) {
         Smart::log_warning('FATAL ERROR: Invalid Session Name :: SMART_FRAMEWORK_SESSION_NAME');
         return;
     }
     //end if
     if (strlen(SMART_FRAMEWORK_SESSION_NAME) < 10 or strlen(SMART_FRAMEWORK_SESSION_NAME) > 25) {
         Smart::log_warning('WARNING: Session Name must have a length between 10 and 25 characters :: SMART_FRAMEWORK_SESSION_NAME');
         return;
     }
     //end if
     if (!preg_match('/^[_A-Za-z0-9]+$/', (string) SMART_FRAMEWORK_SESSION_NAME)) {
         Smart::log_warning('WARNING: Session Name contains invalid characters :: SMART_FRAMEWORK_SESSION_NAME');
         return;
     }
     //end if
     if (!SmartFrameworkSecurity::ValidateVariableName(strtolower(SMART_FRAMEWORK_SESSION_NAME))) {
         Smart::log_warning('WARNING: Session Name have an invalid value :: SMART_FRAMEWORK_SESSION_NAME');
         return;
     }
     //end if
     //--
     if (!defined('SMART_FRAMEWORK_SESSION_LIFETIME')) {
         Smart::log_warning('FATAL ERROR: Invalid Session GC Lifetime :: SMART_FRAMEWORK_SESSION_LIFETIME');
         return;
     }
     //end if
     if (!is_int(SMART_FRAMEWORK_SESSION_LIFETIME)) {
         Smart::log_warning('Invalid INIT constant value for SMART_FRAMEWORK_SESSION_LIFETIME');
         return;
     }
     //end if
     //--
     if (!is_dir('tmp/sessions/')) {
         Smart::log_warning('FATAL ERROR: The Folder \'tmp/sessions/\' does not exists for use with Session !');
         return;
     }
     //end if
     //--
     $detected_session_mode = (string) ini_get('session.save_handler');
     if ((string) $detected_session_mode === 'files') {
         if ((string) SMART_FRAMEWORK_SESSION_HANDLER !== 'files') {
             Smart::log_warning('FATAL ERROR: The value set for SMART_FRAMEWORK_SESSION_HANDLER is not set to: files / but the value found in session.save_handler is: ' . $detected_session_mode);
             return;
         }
         //end if
     } elseif ((string) $detected_session_mode === 'user') {
         if ((string) SMART_FRAMEWORK_SESSION_HANDLER === 'files') {
             Smart::log_warning('FATAL ERROR: The value set for SMART_FRAMEWORK_SESSION_HANDLER is set to: files / but the value found in session.save_handler is: ' . $detected_session_mode);
             return;
         }
         //end if
     } else {
         Smart::log_warning('FATAL ERROR: The value set for session.save_handler must be set to one of these modes: files or user');
         return;
     }
     //end if
     //--
     //=====
     //--  generate a the client private key based on it's IP and Browser
     $the_sess_client_uuid = SmartUtils::unique_client_private_key();
     // SHA512 key to protect session data agains forgers
     //-- a very secure approach based on a chain, derived with a secret salt from the framework security key:
     // (1) an almost unique client private key lock based on it's IP and Browser
     // (2) an entropy derived from the client random cookie combined with the (1)
     // (3) a unique session name suffix derived from (1) and (2)
     // (4) a unique session id composed from (1) and (2)
     //-- thus the correlation between the random public client cookie, the session name suffix and the session id makes impossible to forge it as it locks to IP+Browser, using a public entropy cookie all encrypted with a secret key and derived and related, finally composed.
     $the_sess_client_lock = SmartHashCrypto::sha1(SMART_FRAMEWORK_SECURITY_KEY . '#' . $the_sess_client_uuid);
     $the_sess_client_entropy = SmartHashCrypto::sha1(SMART_APP_VISITOR_COOKIE . '*' . $the_sess_client_uuid . '%' . SMART_FRAMEWORK_SECURITY_KEY);
     $the_sess_nsuffix = SmartHashCrypto::sha1($the_sess_client_uuid . ':' . SMART_FRAMEWORK_SECURITY_KEY . '^' . $the_sess_client_entropy . '+' . $the_sess_client_lock . '$' . SMART_APP_VISITOR_COOKIE);
     $the_sess_id = $the_sess_client_entropy . '-' . $the_sess_client_lock;
     // session ID combines the secret client key based on it's IP / Browser and the Client Entropy Cookie
     //--
     $sf_sess_area = Smart::safe_filename((string) SMART_FRAMEWORK_SESSION_PREFIX);
     $sf_sess_dpfx = substr($the_sess_client_entropy, 0, 1) . '-' . substr($the_sess_client_lock, 0, 1);
     // this come from hexa so 3 chars are 16x16x16=4096 dirs
     //--
     if ((string) $browser_os_ip_identification['bw'] == '@s#') {
         $sf_sess_ns = '@sr-' . $sf_sess_dpfx;
     } elseif ((string) $browser_os_ip_identification['bw'] == 'bot') {
         $sf_sess_ns = 'r0-' . $sf_sess_dpfx;
         // we just need a short prefix for robots (on disk is costly for GC to keep separate folders, but of course, not so safe)
     } else {
         $sf_sess_ns = 'c-' . substr($browser_os_ip_identification['bw'], 0, 3) . '-' . $sf_sess_dpfx;
         // we just need a short prefix for clients (on disk is costly for GC to keep separate folders, but of course, not so safe)
     }
     //end if else
     $sf_sess_ns = Smart::safe_filename($sf_sess_ns);
     //-- by default set for files
     $sf_sess_mode = 'files';
     $sf_sess_dir = 'tmp/sessions/' . $sf_sess_area . '/' . $sf_sess_ns . '/';
     if ((string) $detected_session_mode === 'user') {
         if (class_exists('SmartCustomSession')) {
             if ((string) get_parent_class('SmartCustomSession') == 'SmartAbstractCustomSession') {
                 $sf_sess_mode = 'user-custom';
                 $sf_sess_dir = 'tmp/sessions/' . $sf_sess_area . '/';
                 // here the NS is saved in DB so we do not need to complicate paths
             } else {
                 Smart::log_warning('SESSION INIT ERROR: Invalid Custom Session Handler. The class SmartCustomSession must be extended from class SmartAbstractCustomSession ...');
                 return;
             }
             //end if else
         } else {
             Smart::log_warning('SESSION INIT ERROR: Custom Session Handler requires the class SmartCustomSession ...');
             return;
         }
         //end if
     }
     //end if
     $sf_sess_dir = Smart::safe_pathname($sf_sess_dir);
     //--
     if (!is_dir($sf_sess_dir)) {
         SmartFileSystem::dir_recursive_create($sf_sess_dir);
     }
     //end if
     SmartFileSystem::write_if_not_exists('tmp/sessions/' . $sf_sess_area . '/' . 'index.html', '');
     //=====
     //--
     @session_save_path($sf_sess_dir);
     @session_cache_limiter('nocache');
     //--
     $the_name_of_session = (string) SMART_FRAMEWORK_SESSION_NAME . '__Key_' . $the_sess_nsuffix;
     // protect session name data agains forgers
     //--
     @session_id((string) $the_sess_id);
     @session_name((string) $the_name_of_session);
     //--
     $tmp_exp_seconds = Smart::format_number_int(SMART_FRAMEWORK_SESSION_LIFETIME, '+');
     if ($tmp_exp_seconds > 0) {
         @session_set_cookie_params((int) $tmp_exp_seconds, '/');
         // session cookie expire and the path
     }
     // end if
     //-- be sure that session_write_close() is executed at the end of script if script if die('') premature and before pgsql shutdown register in the case of DB sessions
     register_shutdown_function('session_write_close');
     //-- handle custom session handler
     if ((string) $sf_sess_mode === 'user-custom') {
         //--
         $sess_obj = new SmartCustomSession();
         $sess_obj->sess_area = (string) $sf_sess_area;
         $sess_obj->sess_ns = (string) $sf_sess_ns;
         $sess_obj->sess_expire = (int) $tmp_exp_seconds;
         //--
         session_set_save_handler(array($sess_obj, 'open'), array($sess_obj, 'close'), array($sess_obj, 'read'), array($sess_obj, 'write'), array($sess_obj, 'destroy'), array($sess_obj, 'gc'));
         //--
     }
     //end if else
     //-- start session
     @session_start();
     //--
     if ((string) $_SESSION['SoftwareFramework_VERSION'] != (string) SMART_FRAMEWORK_VERSION or (string) $_SESSION['website_ID'] != (string) SMART_SOFTWARE_NAMESPACE or strlen($_SESSION['session_ID']) < 32) {
         //--
         $_SESSION['SoftwareFramework_VERSION'] = (string) SMART_FRAMEWORK_VERSION;
         // software version
         $_SESSION['SoftwareFramework_SessionMode'] = (string) $sf_sess_mode;
         // session mode
         $_SESSION['website_ID'] = (string) SMART_SOFTWARE_NAMESPACE;
         // the website ID
         $_SESSION['uniqbrowser_ID'] = (string) $the_sess_client_uuid;
         // a true unique browser ID (this is a protection against sessionID forgers)
         $_SESSION['session_ID'] = (string) @session_id();
         // read current session ID
         $_SESSION['session_STARTED'] = (string) date('Y-m-d H:i:s O');
         // read current session ID
         //--
     }
     //end if
     //--
     if (!isset($_SESSION['visit_COUNTER'])) {
         $_SESSION['visit_COUNTER'] = 1;
     } else {
         $_SESSION['visit_COUNTER'] += 1;
     }
     //end if else
     //--
     $_SESSION['SmartFramework__Browser__Identification__Data'] = (array) $browser_os_ip_identification;
     //--
     if ((string) $_SESSION['uniqbrowser_ID'] != (string) $the_sess_client_uuid) {
         // we need at least a md5 session
         //-- log, then unset old session (these are not well tested ...)
         Smart::log_notice('Session Security Breakpoint :: Session-BrowserUniqueID = ' . $_SESSION['uniqbrowser_ID'] . "\n" . 'SessionSecurityUniqueID = ' . $the_sess_client_uuid . "\n" . 'Browser Ident = ' . $browser_os_ip_identification['bw'] . "\n" . 'Cookies = ' . print_r($_COOKIE, 1) . "\n" . 'SessID = ' . $_SESSION['session_ID'] . "\n" . 'ClientIP = ' . SmartUtils::get_ip_client() . ' @ ' . $_SERVER['REMOTE_ADDR'] . "\n" . 'UserAgent = ' . $_SERVER['HTTP_USER_AGENT']);
         $_SESSION = array();
         // reset it
         //-- unset the cookie (from this below is tested)
         @setcookie($the_name_of_session, 'EXPIRED', 1, '/');
         //-- stop execution with message
         Smart::raise_error('SESSION // SECURITY BREAK POINT: Possible Session Forgery Detected ...', 'SESSION // SECURITY BREAK POINT: Possible Session Forgery Detected ! Please refresh the page ... A new session will be assigned ! If you are not trying to forge another user\' session this situation can occur also if you are behind a proxy and some of your navigation parameters has been changed ! If this problem persist try to restart your browser or use other browser. If still persist, contact the website administrator');
         die('');
         // just in case
         return;
         // or is better to silent discard it ?
         //--
     }
     //end if
     //--
     self::$active = time();
     // successfuly started
     //--
 }
 public static function apply_watermark($imagePath, $watermarkPath, $quality, $gravity)
 {
     //-- check for required extension
     self::check_gd_truecolor();
     //--
     //--
     SmartFileSysUtils::raise_error_if_unsafe_path($imagePath);
     SmartFileSysUtils::raise_error_if_unsafe_path($watermarkPath);
     //--
     //--
     $imagePath = (string) $imagePath;
     $watermarkPath = (string) $watermarkPath;
     //--
     //--
     if (is_file($imagePath) and is_file($watermarkPath)) {
         //--
         $arr_imgsize = (array) @getimagesize($watermarkPath);
         $wtmW = (int) $arr_imgsize[0];
         $wtmH = (int) $arr_imgsize[1];
         $t_wtm = (int) $arr_imgsize[2];
         // OK
         unset($arr_imgsize);
         //--
         if ($t_wtm <= 0) {
             Smart::log_notice('Media Gallery // SmartGdImageProcess // Watermark :: Unknown Type [W]: ' . $watermarkPath);
             return 1;
             // not ok (unknown type)
         }
         //end if
         $t_wtm = (string) @image_type_to_mime_type((int) $t_wtm);
         // OK
         //--
         switch ((string) $t_wtm) {
             case 'image/png':
             case 'image/x-png':
                 $watermark = @imagecreatefrompng($watermarkPath);
                 break;
             case 'image/gif':
                 $watermark = @imagecreatefromgif($watermarkPath);
                 break;
             case 'image/pjpeg':
             case 'image/jpeg':
             case 'image/jpg':
                 $watermark = @imagecreatefromjpeg($watermarkPath);
                 break;
             default:
                 Smart::log_notice('Media Gallery // SmartGdImageProcess // Watermark :: Unsupported Type [W] (not PNG/GIF/JPEG ; Type=' . $t_wtm . '): ' . $watermarkPath);
                 return 1;
                 // not ok (invalid type)
         }
         //end switch
         //--
         if (!is_resource($watermark)) {
             // if the immage is corrupt or invalid ...
             Smart::log_warning('Media Gallery // SmartGdImageProcess // Watermark :: Source Watermark Image Failure: ' . $watermarkPath);
             return 2;
             // not ok (there was an error reading the image / have no privileges / or may be an invalid image type)
         }
         //end if
         //--
         //--
         $arr_imgsize = (array) @getimagesize($imagePath);
         $imgW = (int) $arr_imgsize[0];
         $imgH = (int) $arr_imgsize[1];
         $t_img = (int) $arr_imgsize[2];
         // OK
         unset($arr_imgsize);
         //--
         if ($t_img <= 0) {
             Smart::log_notice('Media Gallery // SmartGdImageProcess // Watermark :: Unknown Type [I]: ' . $imagePath);
             return 3;
             // not ok (unknown type)
         }
         //end if
         $t_img = (string) @image_type_to_mime_type((int) $t_img);
         // OK
         //--
         switch ((string) $t_img) {
             case 'image/png':
             case 'image/x-png':
                 $the_type = 'png';
                 $source = @imagecreatefrompng($imagePath);
                 break;
             case 'image/gif':
                 $the_type = 'gif';
                 $source = @imagecreatefromgif($imagePath);
                 break;
             case 'image/pjpeg':
             case 'image/jpeg':
             case 'image/jpg':
                 $the_type = 'jpg';
                 $source = @imagecreatefromjpeg($imagePath);
                 break;
             default:
                 Smart::log_notice('Media Gallery // SmartGdImageProcess // Watermark :: Unsupported Type [I] (not PNG/GIF/JPEG ; Type=' . $t_img . '): ' . $imagePath);
                 return 3;
                 // not ok (invalid type)
         }
         //end switch
         //--
         if (!is_resource($source)) {
             // if the immage is corrupt or invalid ...
             Smart::log_warning('Media Gallery // SmartGdImageProcess // Watermark :: Source Image Failure: ' . $watermarkPath);
             return 4;
             // not ok (there was an error reading the image / have no privileges / or may be an invalid image type)
         }
         //end if
         //--
         //-- apply watermark
         switch ((string) $gravity) {
             // {{{SYNC-GRAVITY}}}
             case 'northwest':
                 $gravityX = 0;
                 $gravityY = 0;
                 break;
             case 'northeast':
                 $gravityX = ceil($imgW - $wtmW);
                 $gravityY = 0;
                 break;
             case 'southwest':
                 $gravityX = 0;
                 $gravityY = ceil($imgH - $wtmH);
                 break;
             case 'southeast':
                 $gravityX = ceil($imgW - $wtmW);
                 $gravityY = ceil($imgH - $wtmH);
                 break;
             case 'center':
             default:
                 $gravityX = ceil($imgW / 2 - $wtmW / 2);
                 $gravityY = ceil($imgH / 2 - $wtmH / 2);
         }
         //end switch
         //--
         @imagecopy($source, $watermark, $gravityX, $gravityY, 0, 0, $wtmW, $wtmH);
         //--
         //-- saving new image
         switch ((string) $the_type) {
             case 'png':
                 @imagepng($source, $imagePath);
                 break;
             case 'gif':
                 @imagegif($source, $imagePath);
                 break;
             case 'jpg':
                 @imagejpeg($source, $imagePath, $quality);
                 // preserve 100% quality for jpeg
                 break;
             default:
                 // this should not happen, it is catched above
         }
         //end switch
         //--
         //--
         @imagedestroy($source);
         @imagedestroy($watermark);
         //--
         //--
         return 0;
         // OK
         //--
     }
     //end if else
     //--
     //--
     return -1;
     // not ok, files do not exists / not files / invalid paths provided
     //--
 }
 /**
  * Generate a PDF Document on the fly from a piece of HTML code.
  *
  * Notice: this is using a secured cache folder, unique per visitor ID
  *
  * @param STRING $y_html_content				:: The HTML Code
  * @param ENUM $y_orientation					:: Page Orientation: 'normal' | 'wide'
  * @param STRING $y_runtime_script 				:: The allowed Runtime Script to allow send credentials for sub-downloads. Ex: admin.php
  * @param STRING $y_runtime_url					:: The allowed Runtime URL ended by '/' to allow send credentials for sub-downloads. Ex: http(s)://some-server/some_path/ ; normally this should be set in config to enforce https:// and a single URL only
  * @param BOOLEAN $y_allow_send_credentials 	:: Set to TRUE to allow or set to FALSE to dissalow sending the auth credentials for sub-downloads: in the case there are embedded pictures generated by admin.php which may need authentication before to work, the credentials need to be set automatically in this case
  *
  * @returns STRING 							:: The PDF Document Contents
  *
  */
 public static function generate($y_html_content, $y_orientation = 'normal', $y_runtime_script = '', $y_runtime_url = '', $y_allow_send_credentials = false)
 {
     //--
     $pdfdata = '';
     //--
     $htmldoc = self::is_active();
     //--
     if ((string) $htmldoc != '') {
         //--
         if ((string) $y_orientation == 'wide') {
             $orientation = self::tag_page_wide();
         } else {
             $orientation = self::tag_page_normal();
         }
         //end if else
         //--
         $tmp_prefix_dir = 'tmp/cache/pdf/';
         $protect_file = $tmp_prefix_dir . '.htaccess';
         $dir = $tmp_prefix_dir . SMART_FRAMEWORK_SESSION_PREFIX . '/';
         // we use different for index / admin / @
         //--
         $uniquifier = SmartUtils::unique_auth_client_private_key() . SMART_APP_VISITOR_COOKIE;
         $the_dir = $dir . Smart::safe_varname(Smart::uuid_10_seq() . '_' . Smart::uuid_10_num() . '_' . SmartHashCrypto::sha1($uniquifier)) . '/';
         //--
         $tmp_uuid = Smart::uuid_45($uniquifier) . Smart::uuid_36($uniquifier);
         $file = $the_dir . '__document_' . SmartHashCrypto::sha256('@@PDF#File::Cache@@' . $tmp_uuid) . '.html';
         $logfile = $the_dir . '__headers_' . SmartHashCrypto::sha256('@@PDF#File::Cache@@' . $tmp_uuid) . '.log';
         //--
         if (is_dir($the_dir)) {
             SmartFileSystem::dir_delete($the_dir);
         }
         //end if
         //--
         if (!is_dir($the_dir)) {
             SmartFileSystem::dir_recursive_create($the_dir);
         }
         // end if
         //--
         SmartFileSystem::write_if_not_exists($protect_file, trim(SMART_FRAMEWORK_HTACCESS_FORBIDDEN) . "\n", 'yes');
         //-- process the code
         $y_html_content = (string) self::remove_between_tags((string) $y_html_content);
         $y_html_content = (string) self::safe_charset((string) $y_html_content);
         //-- extract images
         $htmlparser = new SmartHtmlParser((string) $y_html_content);
         $arr_imgs = $htmlparser->get_tags('img');
         $htmlparser = '';
         unset($htmlparser);
         //--
         $chk_duplicates_arr = array();
         //--
         for ($i = 0; $i < Smart::array_size($arr_imgs); $i++) {
             //--
             $tmp_img_src = trim((string) $arr_imgs[$i]['src']);
             //--
             if (strlen($chk_duplicates_arr[$tmp_img_src]) <= 0) {
                 //--
                 $tmp_url_img_src = '';
                 //--
                 if ((string) $y_runtime_script != '' and (string) $y_runtime_url != '') {
                     // replace relative paths
                     if (substr($tmp_img_src, 0, @strlen($y_runtime_script)) == (string) $y_runtime_script) {
                         $tmp_url_img_src = (string) $y_runtime_url . $tmp_img_src;
                         $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $tmp_url_img_src . '"', (string) $y_html_content);
                         $tmp_img_src = (string) $tmp_url_img_src;
                     }
                     //end if
                 }
                 //end if
                 //--
                 $tmp_img_ext = '.' . strtolower(SmartFileSysUtils::get_file_extension_from_path($tmp_img_src));
                 // [OK]
                 $tmp_img_cache = 'pdf_img_' . SmartHashCrypto::sha256('@@PDF#File::Cache::IMG@@' . '#' . $i . '@' . $tmp_img_src . '//' . $tmp_uuid);
                 //--
                 $tmp_arr = array();
                 //--
                 if (substr($tmp_img_src, 0, 7) == 'http://' or substr($tmp_img_src, 0, 8) == 'https://') {
                     //--
                     $tmp_img_ext = '';
                     // we clear the extension as we don't know yet (we will get it from headers)
                     $tmp_img_cache = 'pdf_url_img_' . SmartHashCrypto::sha256('@@PDF#File::Cache::URL::IMG@@' . '#' . $i . '@' . $tmp_img_src . '//' . $tmp_uuid);
                     //--
                 }
                 //end if
                 //--
                 if ($y_allow_send_credentials === true) {
                     $allow_set_credentials = 'yes';
                 } else {
                     $allow_set_credentials = 'no';
                 }
                 //end if else
                 //--
                 $tmp_arr = SmartUtils::load_url_or_file($tmp_img_src, SMART_FRAMEWORK_NETSOCKET_TIMEOUT, 'GET', '', '', '', $allow_set_credentials);
                 // [OK] :: allow set credentials
                 //--
                 $tmp_img_ext = '.noextension';
                 $tmp_where_we_guess = '';
                 //--
                 $guess_arr = array();
                 //--
                 $guess_arr = SmartUtils::guess_image_extension_by_url_head($tmp_arr['headers']);
                 $tmp_img_ext = (string) $guess_arr['extension'];
                 $tmp_where_we_guess = (string) $guess_arr['where-was-detected'];
                 $guess_arr = array();
                 if ((string) $tmp_img_ext == '') {
                     $tmp_img_ext = SmartUtils::guess_image_extension_by_first_bytes(substr($tmp_arr['content'], 0, 256));
                     if ((string) $tmp_img_ext != '') {
                         $tmp_where_we_guess = ' First Bytes ...';
                     }
                     //end if
                 }
                 //end if
                 //--
                 if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
                     // if debug, append information to log
                     SmartFileSystem::write($logfile, '####################' . "\n" . '#################### [FILE # ' . $i . ' = \'' . $tmp_img_src . '\']' . "\n\n" . '==== [MODE] :: ' . $tmp_arr['mode'] . "\n" . '==== [LOG] :: ' . "\n" . $tmp_arr['log'] . "\n" . '==== [HEADERS] ::' . "\n" . $tmp_arr['headers'] . "\n" . '########' . "\n" . '==== [GUESS EXTENSION] :: ' . $tmp_where_we_guess . "\n\n" . '###################' . "\n\n\n\n", 'a');
                 }
                 //end if
                 //--
                 if ((string) $tmp_arr['result'] == '1' and (string) $tmp_arr['code'] == '200') {
                     //--
                     SmartFileSystem::write($the_dir . $tmp_img_cache . $tmp_img_ext, $tmp_arr['content']);
                     //-- if empty, it may be a file
                     if ((string) $tmp_img_ext == '' or (string) $tmp_img_ext == '.png' or (string) $tmp_img_ext == '.gif' or (string) $tmp_img_ext == '.jpg') {
                         $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $tmp_img_cache . $tmp_img_ext . '"', (string) $y_html_content);
                     } else {
                         // we want to avoid html code to be loaded as image by mistakes of http browser class or servers
                         $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $y_runtime_url . 'lib/framework/img/sign_warn.png"', (string) $y_html_content);
                     }
                     //end if else
                     //--
                 } else {
                     //--
                     $y_html_content = (string) @str_replace('src="' . $tmp_img_src . '"', 'src="' . $y_runtime_url . 'lib/framework/img/sign_error.png"', (string) $y_html_content);
                     //--
                 }
                 //end if
                 //--
             }
             //end if
             //--
             $chk_duplicates_arr[$tmp_img_src] = 'processed';
             //--
         }
         //end for
         //--
         $chk_duplicates_arr = array();
         unset($chk_duplicates_arr);
         $arr_imgs = array();
         unset($arr_imgs);
         //--
         SmartFileSystem::write($file, $orientation . "\n" . $y_html_content);
         //--
         if (is_file($file)) {
             //--
             ob_start();
             //--
             @passthru($htmldoc . ' ' . self::pdf_options($file));
             //--
             $pdfdata = ob_get_clean();
             //--
         } else {
             //--
             Smart::log_warning('ERROR: PDF Generator Failed to find the PDF Document: ' . $file . "\n" . $y_html_content);
             //--
         }
         //end if else
         //-- cleanup
         if ((string) SMART_FRAMEWORK_DEBUG_MODE != 'yes') {
             // if not debug, cleanup the dir
             if (is_dir($the_dir)) {
                 SmartFileSystem::dir_delete($the_dir);
             }
             //end if
         }
         //end if
         //--
     } else {
         //--
         Smart::log_notice('NOTICE: PDF Generator is INACTIVE ...');
         //--
     }
     //end if
     //--
     return (string) $pdfdata;
     //--
 }
Esempio n. 21
0
 public function draw_image($y_form)
 {
     //--
     $y_form = trim((string) $y_form);
     //--
     //--
     $out = '';
     //--
     ob_start();
     //--
     if ((string) $this->mode == 'hashed') {
         $captcha_arr = (array) $this->generate_captcha_hashed();
     } else {
         // 'dotted'
         $captcha_arr = (array) $this->generate_captcha_dotted();
     }
     //end if else
     //--
     $captcha_image = $captcha_arr['rawimage'];
     $captcha_word = $captcha_arr['word'];
     $captcha_arr = array();
     //--
     $err = ob_get_contents();
     ob_end_clean();
     //--
     if ((string) $err != '') {
         // trigger errors
         Smart::log_warning('#Captcha / Draw Image [' . $intext . '] Errors/Output: ' . $err);
     }
     //end if
     //--
     ob_start();
     //-
     switch (@strtolower($this->format)) {
         case "png":
             //header: "Content-type: image/png"
             imagepng($captcha_image);
             break;
         case "gif":
             //header: "Content-type: image/gif"
             imagegif($captcha_image);
             break;
         case "jpg":
         case "jpeg":
         default:
             //header: "Content-type: image/jpeg"
             imagejpeg($captcha_image, '', $this->quality);
     }
     //end switch
     //-
     $out = ob_get_contents();
     //-
     ob_end_clean();
     //-
     @imagedestroy($captcha_image);
     // free resources
     //--
     //--
     @setcookie(SmartCaptchaFormCheck::chkcookiename($y_form), sha1($y_form . SMART_FRAMEWORK_SECURITY_KEY), 0, '/');
     //--
     if (SmartCaptchaFormCheck::validate_form_name($y_form) === 1) {
         if ((string) $this->store == 'session') {
             SmartSession::set(SmartCaptchaFormCheck::cookiename($y_form), SmartCaptchaFormCheck::checksum($captcha_word));
         } else {
             @setcookie(SmartCaptchaFormCheck::cookiename($y_form), SmartCaptchaFormCheck::checksum($captcha_word), 0, '/');
         }
         //end if else
     }
     //end if
     //--
     //--
     return $out;
     //--
 }
 /**
  * Function: Generate a 1D Barcode: 128 B, 93 E+, 39 E, KIX
  *
  * @param STRING 	$y_code 			The code for the BarCode Generator
  * @param ENUM 		$y_type				The BarCode Type: 128 / 93 / 39 / KIX
  * @param ENUM 		$y_format			The Barcode format: html, html-png, png, html-svg, svg
  * @param INTEGER+ 	$y_size				The Scale-Size for Barcode (1..4)
  * @param INTEGER+	$y_height			The Height in pixels for the Barcode
  * @param HEXCOLOR	$y_color			The Hexadecimal Color for the Barcode Bars ; default is Black = #000000
  * @param BOOLEAN	$y_display_text		If TRUE will display the Code below of BarCode Bars ; default is FALSE
  * @param YES/NO	$y_cache			If YES will cache the Barcode to avoid on-the-fly generation ; default is set to NO
  *
  * @return MIXED	By Type Selection: 	HTML Code / PNG Image / SVG Code
  *
  */
 public static function getBarcode($y_code, $y_type, $y_format, $y_size, $y_height, $y_color = '#000000', $y_display_text = false, $y_cache = 'no')
 {
     //--
     switch ((string) $y_type) {
         case '128':
             // 128 B (Extended)
             $barcode_type = '128B';
             break;
         case '93':
             // 93 Extended +Checksum
             $barcode_type = '93E+';
             break;
         case '39':
             // 39 Extended
             $barcode_type = '39E';
             break;
         case 'KIX':
             // RMS KIX Variant (Extended) :: max 11 chars :: This needs a height that divides by 3
             $barcode_type = 'KIX';
             break;
         default:
             $barcode_type = '???';
             Smart::log_warning('ERROR: BarCodes1D - Invalid Type Selected for getBarcode');
             return '';
     }
     //end switch
     //--
     switch ((string) $y_format) {
         case 'html':
             $barcode_format = '.htm';
             break;
         case 'html-png':
             $barcode_format = '.png.htm';
             break;
         case 'png':
             $barcode_format = '.png';
             break;
         case 'html-svg':
             $barcode_format = '.svg.htm';
             break;
         case 'svg':
             $barcode_format = '.svg';
             break;
         default:
             $barcode_format = '.unknown';
             Smart::log_warning('ERROR: BarCodes1D - Invalid Mode Selected for getBarcode');
             return '';
     }
     //end switch
     //--
     //--
     if ($y_display_text) {
         $barcode_show_text = 'TX';
     } else {
         $barcode_show_text = 'XX';
     }
     //end if else
     //--
     //--
     $memory_cache_url = 'memory://barcode-1d/' . $barcode_type . '/' . $barcode_format . '/' . $y_size . '/' . $y_height . '/' . $y_color . '/' . $barcode_show_text . '/' . $y_code;
     $realm = 'barcode-1d/';
     //--
     //--
     if ((string) $y_cache == 'yes') {
         //--
         $out = SmartUtils::load_cached_content($barcode_format, $realm, $memory_cache_url, '');
         // (try to) get from cache
         //--
         if ((string) $out != '') {
             return $out;
             // if found in cache return it
         }
         //end if
         //--
     }
     //end if
     //--
     //--
     switch ((string) $barcode_type) {
         case '128B':
             $arr_barcode = (new SmartBarcode1D_128($y_code, 'B'))->getBarcodeArray();
             break;
         case '93E+':
             $arr_barcode = (new SmartBarcode1D_93($y_code, true, true))->getBarcodeArray();
             break;
         case '39E':
             $arr_barcode = (new SmartBarcode1D_39($y_code, true, false))->getBarcodeArray();
             break;
         case 'KIX':
             $arr_barcode = (new SmartBarcode1D_RMS4CC($y_code, 'KIX'))->getBarcodeArray();
             break;
         default:
             $arr_barcode = '';
             // not to be an array for error detection
     }
     //end switch
     //--
     switch ((string) $y_format) {
         case 'html':
             $out = '<!-- ' . Smart::escape_html(strtoupper($barcode_type) . ' (' . $y_size . '/' . $y_height . '/' . $y_color . '/' . $barcode_show_text . ') :: ' . date('YmdHis')) . ' -->' . '<div title="' . Smart::escape_html($y_code) . '">' . self::getBarcodeHTML($arr_barcode, $y_size, $y_height, $y_color, $y_display_text) . '</div>' . '<!-- #END :: ' . Smart::escape_html(strtoupper($barcode_type)) . ' -->';
             break;
         case 'html-png':
             // html img embedded png
             $out = '<!-- ' . Smart::escape_html(strtoupper($barcode_type) . ' (' . $y_size . '/' . $y_height . '/' . $y_color . '/' . $barcode_show_text . ') :: ' . date('YmdHis')) . ' -->' . '<div title="' . Smart::escape_html($y_code) . '">' . self::getBarcodeEmbeddedHTMLPNG($arr_barcode, $y_size, $y_height, $y_color, $y_display_text) . '</div>' . '<!-- #END :: ' . Smart::escape_html(strtoupper($barcode_type)) . ' -->';
             break;
         case 'png':
             // raw png
             $out = self::getBarcodePNG($arr_barcode, $y_size, $y_height, $y_color, $y_display_text);
             // needs header image/png on output
             break;
         case 'html-svg':
             $out = '<!-- ' . Smart::escape_html(strtoupper($barcode_type) . ' (' . $y_size . '/' . $y_height . '/' . $y_color . '/' . $barcode_show_text . ') :: ' . date('YmdHis')) . ' -->' . '<div title="' . Smart::escape_html($y_code) . '">' . self::getBarcodeEmbeddedHTMLSVG($arr_barcode, $y_size, $y_height, $y_color, $y_display_text) . '</div>' . '<!-- #END :: ' . Smart::escape_html(strtoupper($barcode_type)) . ' -->';
             break;
         case 'svg':
             $out = self::getBarcodeSVG($arr_barcode, $y_size, $y_height, $y_color, $y_display_text);
             // needs header image/svg on output
             break;
         default:
             $out = '';
     }
     //end switch
     //--
     //--
     if ((string) $y_cache == 'yes') {
         //--
         $out = SmartUtils::load_cached_content($barcode_format, $realm, $memory_cache_url, $out);
         // set + get from cache
         //--
     }
     //end if
     //--
     //--
     return $out;
     //--
 }
 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;
     //--
 }
Esempio n. 24
0
 public static final function Raise504Error($y_msg)
 {
     //--
     if (!headers_sent()) {
         http_response_code(504);
     } else {
         Smart::log_warning('Headers Already Sent before 504 ...');
     }
     //end if else
     die(SmartComponents::http_message_504_gatewaytimeout(Smart::escape_html((string) $y_msg)));
     //--
 }
 /**
  * Function: Generate a 2D Barcode: QRCode, DataMatrix (SemaCode), PDF417
  *
  * @param STRING 	$y_code 			The code for the BarCode Generator
  * @param ENUM 		$y_type				The BarCode Type: qrcode / semacode / pdf417
  * @param ENUM 		$y_format			The Barcode format: html, html-png, png, html-svg, svg
  * @param INTEGER+ 	$y_size				The Scale-Size for Barcode (1..4)
  * @param HEXCOLOR	$y_color			The Hexadecimal Color for the Barcode Pixels ; default is Black = #000000
  * @param MIXED		$y_extraoptions		Extra Options: for QRCode = Quality [L, M, Q, H] L as default ; for PDF417 a Ratio Integer between 1 and 17
  * @param YES/NO	$y_cache			If YES will cache the Barcode to avoid on-the-fly generation ; default is set to NO
  *
  * @return MIXED	By Type Selection: 	HTML Code / PNG Image / SVG Code
  *
  */
 public static function getBarcode($y_code, $y_type, $y_format, $y_size, $y_color = '#000000', $y_extraoptions = '', $y_cache = 'no')
 {
     //--
     switch ((string) $y_type) {
         case 'qrcode':
             switch ((string) $y_extraoptions) {
                 case 'H':
                     $y_extraoptions = 'H';
                     break;
                 case 'Q':
                     $y_extraoptions = 'Q';
                     break;
                 case 'M':
                     $y_extraoptions = 'M';
                     break;
                 case 'L':
                 default:
                     $y_extraoptions = 'L';
             }
             //end switch
             $barcode_type = 'qrcode';
             break;
         case 'semacode':
             $y_extraoptions = '';
             $barcode_type = 'semacode';
             break;
         case 'pdf417':
             $y_extraoptions = (int) (0 + $y_extraoptions);
             if ($y_extraoptions <= 0) {
                 $y_extraoptions = 1;
             }
             //end if
             if ($y_extraoptions > 17) {
                 $y_extraoptions = 17;
             }
             //end if
             $barcode_type = 'pdf417';
             break;
         default:
             $barcode_type = '???';
             Smart::log_warning('ERROR: BarCodes2D - Invalid Type Selected for getBarcode');
             return '';
     }
     //end switch
     //--
     switch ((string) $y_format) {
         case 'html':
             $barcode_format = '.htm';
             break;
         case 'html-png':
             $barcode_format = '.png.htm';
             break;
         case 'png':
             $barcode_format = '.png';
             break;
         case 'html-svg':
             $barcode_format = '.svg.htm';
             break;
         case 'svg':
             $barcode_format = '.svg';
             break;
         default:
             $barcode_format = '.unknown';
             Smart::log_warning('ERROR: BarCodes2D - Invalid Mode Selected for getBarcode');
             return '';
     }
     //end switch
     //--
     //--
     $memory_cache_url = 'memory://barcode-2d/' . $barcode_type . '/' . $barcode_format . '/' . $y_size . '/' . $y_color . '/' . $y_extraoptions . '/' . $y_code;
     $realm = 'barcode-2d/';
     //--
     //--
     if ((string) $y_cache == 'yes') {
         //--
         $out = SmartUtils::load_cached_content($barcode_format, $realm, $memory_cache_url, '');
         // (try to) get from cache
         //--
         if ((string) $out != '') {
             return $out;
             // if found in cache return it
         }
         //end if
         //--
     }
     //end if
     //--
     //--
     switch ((string) $barcode_type) {
         case 'qrcode':
             $arr_barcode = (new SmartBarcode2D_QRcode($y_code, $y_extraoptions))->getBarcodeArray();
             break;
         case 'semacode':
             $arr_barcode = (new SmartBarcode2D_DataMatrix($y_code))->getBarcodeArray();
             break;
         case 'pdf417':
             $arr_barcode = (new SmartBarcode2D_Pdf417($y_code, $y_extraoptions, -1))->getBarcodeArray();
             break;
         default:
             $arr_barcode = '';
             // not to be an array for error detection
     }
     //end switch
     //--
     switch ((string) $y_format) {
         case 'html':
             $out = '<!-- ' . Smart::escape_html(strtoupper($barcode_type) . ' (' . $y_size . '/' . $y_color . ') [' . $y_extraoptions . ']' . ' :: ' . date('YmdHis')) . ' -->' . '<div title="' . Smart::escape_html($y_code) . '">' . self::getBarcodeHTML($arr_barcode, $y_size, $y_color) . '</div>' . '<!-- #END :: ' . Smart::escape_html(strtoupper($barcode_type)) . ' -->';
             break;
         case 'html-png':
             // html img embedded png
             $out = '<!-- ' . Smart::escape_html(strtoupper($barcode_type) . ' (' . $y_size . '/' . $y_color . ') [' . $y_extraoptions . ']' . ' :: ' . date('YmdHis')) . ' -->' . '<div title="' . Smart::escape_html($y_code) . '">' . self::getBarcodeEmbeddedHTMLPNG($arr_barcode, $y_size, $y_color) . '</div>' . '<!-- #END :: ' . Smart::escape_html(strtoupper($barcode_type)) . ' -->';
             break;
         case 'png':
             // raw png
             $out = self::getBarcodePNG($arr_barcode, $y_size, $y_color);
             // needs header image/png on output
             break;
         case 'html-svg':
             $out = '<!-- ' . Smart::escape_html(strtoupper($barcode_type) . ' (' . $y_size . '/' . $y_color . ') [' . $y_extraoptions . ']' . ' :: ' . date('YmdHis')) . ' -->' . '<div title="' . Smart::escape_html($y_code) . '">' . self::getBarcodeEmbeddedHTMLSVG($arr_barcode, $y_size, $y_color) . '</div>' . '<!-- #END :: ' . Smart::escape_html(strtoupper($barcode_type)) . ' -->';
             break;
         case 'svg':
             $out = self::getBarcodeSVG($arr_barcode, $y_size, $y_color);
             // needs header image/svg on output
             break;
         default:
             $out = '';
     }
     //end switch
     //--
     //--
     if ((string) $y_cache == 'yes') {
         //--
         $out = SmartUtils::load_cached_content($barcode_format, $realm, $memory_cache_url, $out);
         // set + get from cache
         //--
     }
     //end if
     //--
     //--
     return $out;
     //--
 }
 private static function pack_test_archive($y_exclusions_arr = '')
 {
     //--
     $testsrcfile = (string) SmartFileSystem::read('lib/core/lib_smart_test_suite.php');
     $out = '';
     if ((string) $testsrcfile != '') {
         //--
         $testsrcfile = (string) base64_encode((string) $testsrcfile);
         $vlen = Smart::random_number(100000, 900000);
         //--
         while (strlen((string) $out) < 8388608 + $vlen) {
             $randomizer = (string) '#' . Smart::random_number() . '#' . "\n";
             $testfile = SmartUtils::data_archive((string) $randomizer . $testsrcfile);
             if (sha1((string) SmartUtils::data_unarchive((string) $testfile)) !== sha1((string) $randomizer . $testsrcfile)) {
                 Smart::log_warning('Data Unarchive Failed for Pack Test Archive ...');
                 return 'Data Unarchive Failed for Pack Test Archive !';
             }
             //end if
             $out .= (string) $testfile;
         }
         //end if
         //--
     } else {
         //--
         Smart::log_warning('Failed to read the test file: lib/core/lib_smart_test_suite.php');
         return 'ERROR: Cannot Get File Read for this test !';
         //--
     }
     //end if
     //--
     return (string) $out;
     //--
 }
Esempio n. 27
0
 private function send_request($url, $user = '', $pwd = '', $method = 'GET', $ssl_version = '')
 {
     //--
     $this->method = (string) strtoupper(trim((string) $method));
     //--
     //--
     $this->connect_timeout = (int) $this->connect_timeout;
     if ($this->connect_timeout < 1) {
         $this->connect_timeout = 1;
     }
     //end if
     if ($this->connect_timeout > 120) {
         $this->connect_timeout = 120;
     }
     //end if
     //--
     //-- log action
     if ($this->debug) {
         $this->log .= '[INF] Get From URL :: is starting ...' . "\n";
     }
     //end if
     //--
     //-- separations
     $this->url_parts = (array) Smart::separe_url_parts($url);
     $protocol = (string) $this->url_parts['protocol'];
     $server = (string) $this->url_parts['server'];
     $port = (string) $this->url_parts['port'];
     $path = (string) $this->url_parts['path'];
     //--
     if ($this->debug) {
         $this->log .= '[INF] Analize of the URL: ' . @print_r($this->url_parts, 1) . "\n";
     }
     //end if
     //--
     //--
     if ((string) $server == '') {
         if ($this->debug) {
             $this->log .= '[ERR] Invalid Server to Browse' . "\n";
         }
         //end if
         Smart::log_warning('LibHTTP // GetFromURL () // Invalid (empty) Server to Browse ...');
         return 0;
     }
     //end if
     //--
     //--
     $browser_protocol = '';
     //--
     if ((string) $protocol == 'https://') {
         //--
         switch (strtolower((string) $ssl_version)) {
             case 'ssl':
                 $browser_protocol = 'ssl://';
                 break;
             case 'sslv3':
                 $browser_protocol = 'sslv3://';
                 break;
             case 'tls':
             default:
                 $browser_protocol = 'tls://';
         }
         //end switch
         //--
         if (!function_exists('openssl_open')) {
             if ($this->debug) {
                 $this->log .= '[ERR] PHP OpenSSL Extension is required to perform SSL requests' . "\n";
             }
             //end if
             Smart::log_warning('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // PHP OpenSSL Extension not installed ...');
             return 0;
         }
         //end if
         //--
     }
     //end if else
     //--
     //--
     $have_cookies = false;
     if (is_array($this->cookies)) {
         if (count($this->cookies) > 0) {
             $have_cookies = true;
         }
         //end if
     }
     //end if
     //--
     $have_post_vars = false;
     if ((string) $this->poststring != '') {
         $have_post_vars = true;
     } elseif (is_array($this->postvars)) {
         if (count($this->postvars) > 0) {
             $have_post_vars = true;
         }
         //end if
     }
     //end if
     //--
     //-- navigate
     if ($this->debug) {
         $this->log .= 'Opening HTTP(S) Browser Connection to: ' . $protocol . $server . ':' . $port . $path . ' using socket protocol: [' . $browser_protocol . ']' . "\n";
         $this->log .= '[INF] HTTP Protocol: ' . $this->protocol . "\n";
         $this->log .= '[INF] Connection TimeOut: ' . $this->connect_timeout . "\n";
     }
     //end if
     //--
     $stream_context = @stream_context_create();
     if ((string) $browser_protocol != '') {
         if (defined('SMART_FRAMEWORK_SSL_CA_PATH')) {
             if ((string) SMART_FRAMEWORK_SSL_CA_PATH != '') {
                 @stream_context_set_option($stream_context, 'ssl', 'capath', Smart::real_path((string) SMART_FRAMEWORK_SSL_CA_PATH));
             }
             //end if
         }
         //end if
         @stream_context_set_option($stream_context, 'ssl', 'ciphers', (string) SMART_FRAMEWORK_SSL_CIPHERS);
         // allow only high ciphers
         @stream_context_set_option($stream_context, 'ssl', 'verify_host', (bool) SMART_FRAMEWORK_SSL_VFY_HOST);
         // allways must be set to true !
         @stream_context_set_option($stream_context, 'ssl', 'verify_peer', (bool) SMART_FRAMEWORK_SSL_VFY_PEER);
         // this may fail with some CAs
         @stream_context_set_option($stream_context, 'ssl', 'verify_peer_name', (bool) SMART_FRAMEWORK_SSL_VFY_PEER_NAME);
         // allow also wildcard names *
         @stream_context_set_option($stream_context, 'ssl', 'allow_self_signed', (bool) SMART_FRAMEWORK_SSL_ALLOW_SELF_SIGNED);
         // must allow self-signed certificates but verified above
         @stream_context_set_option($stream_context, 'ssl', 'disable_compression', (bool) SMART_FRAMEWORK_SSL_DISABLE_COMPRESS);
         // help mitigate the CRIME attack vector
     }
     //end if else
     $this->socket = @stream_socket_client($browser_protocol . $server . ':' . $port, $errno, $errstr, $this->connect_timeout, STREAM_CLIENT_CONNECT, $stream_context);
     //--
     if (!is_resource($this->socket)) {
         if ($this->debug) {
             $this->log .= '[ERR] Could not open connection. Error : ' . $errno . ': ' . $errstr . "\n";
             Smart::log_notice('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // Could not open connection. Error : ' . $errno . ': ' . $errstr . ' #');
         }
         //end if
         return 0;
     }
     //end if
     //--
     if ($this->debug) {
         $this->log .= '[INF] Socket Resource ID: ' . $this->socket . "\n";
     }
     //end if
     //--
     @stream_set_timeout($this->socket, (int) SMART_FRAMEWORK_NETSOCKET_TIMEOUT);
     if ($this->debug) {
         $this->log .= '[INF] Set Socket Stream TimeOut to: ' . SMART_FRAMEWORK_NETSOCKET_TIMEOUT . "\n";
     }
     //end if
     //--
     //-- avoid connect normally if SSL/TLS was explicit required
     $chk_crypto = (array) @stream_get_meta_data($this->socket);
     if ((string) $browser_protocol != '') {
         if (stripos($chk_crypto['stream_type'], '/ssl') === false) {
             // will return something like: tcp_socket/ssl
             if ($this->debug) {
                 $this->log .= '[ERR] Connection CRYPTO CHECK Failed ...' . "\n";
                 Smart::log_notice('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // Connection CRYPTO CHECK Failed ...');
             }
             //end if
             return 0;
         }
         //end if
     }
     //end if
     //--
     //--
     $this->raw_headers['Host'] = $server . ':' . $port;
     //--
     //-- auth
     if ((string) $user != '' and (string) $pwd != '') {
         //--
         if ($this->debug) {
             $this->log .= '[INF] Authentication will be attempted for USERNAME = \'' . $user . '\' ; PASSWORD(' . strlen($pwd) . ') *****' . "\n";
         }
         //end if
         //--
         $this->raw_headers['Authorization'] = 'Basic ' . base64_encode($user . ':' . $pwd);
         //--
     }
     //end if
     //--
     //-- cookies
     $send_cookies = '';
     //--
     if ($have_cookies) {
         //--
         foreach ($this->cookies as $key => $value) {
             if ((string) $key != '') {
                 if ((string) $value != '') {
                     $send_cookies .= (string) SmartHttpUtils::encode_var_cookie($key, $value);
                 }
                 //end if
             }
             //end if
         }
         //end foreach
         //--
         if ((string) $send_cookies != '') {
             $this->raw_headers['Cookie'] = $send_cookies;
             if ($this->debug) {
                 $this->log .= '[INF] Cookies will be SET: ' . $send_cookies . "\n";
             }
             //end if
         }
         //end if
         //--
     }
     //end if
     //--
     //-- request
     if ((string) $this->jsonrequest != '') {
         // json request
         //--
         if ($this->debug) {
             $this->log .= '[INF] JSON Request will be sent to server via: ' . $this->method . "\n";
         }
         //end if
         //--
         $request = $this->method . ' ' . $path . ' HTTP/' . $this->protocol . "\r\n";
         $this->raw_headers['Content-Type'] = 'application/json';
         $this->raw_headers['Content-Length'] = strlen($this->jsonrequest);
         //--
     } elseif ((string) $this->xmlrequest != '') {
         // xml request
         //--
         if ($this->debug) {
             $this->log .= '[INF] XML Request will be sent to server via: ' . $this->method . "\n";
         }
         //end if
         //--
         $request = $this->method . ' ' . $path . ' HTTP/' . $this->protocol . "\r\n";
         $this->raw_headers['Content-Type'] = 'application/xml';
         // may be also: text/xml
         $this->raw_headers['Content-Length'] = strlen($this->xmlrequest);
         //--
     } elseif ($have_post_vars) {
         // post vars
         //--
         if ((string) $this->method == 'GET') {
             $this->method = 'POST';
             // FIX: if GET Method is using PostVars, then set method to POST ; this should not be fixed for other methods like: HEAD, PUT, DELETE ...
         }
         //end if
         //--
         if ($this->debug) {
             $this->log .= '[INF] Variables will be sent to server using POST method' . "\n";
         }
         //end if
         //--
         $post_string = '';
         if ((string) $this->poststring != '') {
             $post_string = (string) $this->poststring;
         } elseif (is_array($this->postvars)) {
             foreach ($this->postvars as $key => $value) {
                 $post_string .= (string) SmartHttpUtils::encode_var_post($key, $value);
             }
             //end foreach
         }
         //end if else
         //--
         $request = $this->method . ' ' . $path . ' HTTP/' . $this->protocol . "\r\n";
         $this->raw_headers['Content-Type'] = 'application/x-www-form-urlencoded';
         $this->raw_headers['Content-Length'] = strlen($post_string);
         //--
     } else {
         // simple request
         //--
         if ($this->debug) {
             $this->log .= '[INF] Simple Request via: ' . $this->method . "\n";
         }
         //end if
         //--
         $request = $this->method . ' ' . $path . ' HTTP/' . $this->protocol . "\r\n";
         //--
     }
     //end if else
     //--
     //-- check
     if (!$this->socket) {
         //--
         if ($this->debug) {
             $this->log .= '[ERR] Premature connection end (1.1)' . "\n";
             Smart::log_notice('LibHTTP // GetFromURL // Premature connection end (1.1) ... ' . $url);
         }
         //end if
         return 0;
         //--
     }
     //end if
     //--
     //--
     if (@fwrite($this->socket, $request) === false) {
         if ($this->debug) {
             $this->log .= '[ERR] Error writing Request type to socket' . "\n";
             Smart::log_notice('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // Error writing Request type to socket ...');
         }
         //end if
         return 0;
     }
     //end if
     //--
     //-- raw headers
     if (!$this->socket) {
         //--
         if ($this->debug) {
             $this->log .= '[ERR] Premature connection end (1.2)' . "\n";
             Smart::log_notice('LibHTTP // GetFromURL // Premature connection end (1.2) ... ' . $url);
         }
         //end if
         return 0;
         //--
     }
     //end if
     //--
     foreach ($this->raw_headers as $key => $value) {
         if (@fwrite($this->socket, $key . ": " . $value . "\r\n") === false) {
             if ($this->debug) {
                 $this->log .= '[ERR] Error writing Raw-Headers to socket' . "\n";
                 Smart::log_notice('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // Error writing Raw-Headers to socket ...');
             }
             //end if
             return 0;
         }
         //end if
     }
     //end foreach
     //--
     //-- end-line or blank line before post / cookies
     if (!$this->socket) {
         //--
         if ($this->debug) {
             $this->log .= '[ERR] Premature connection end (1.3)' . "\n";
             Smart::log_notice('LibHTTP // GetFromURL // Premature connection end (1.3) ... ' . $url);
         }
         //end if
         return 0;
         //--
     }
     //end if
     //--
     if (@fwrite($this->socket, "\r\n") === false) {
         if ($this->debug) {
             $this->log .= '[ERR] Error writing End-Of-Line to socket' . "\n";
             Smart::log_notice('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // Error writing End-Of-Line to socket ...');
         }
         //end if
         return 0;
     }
     //end if
     //--
     //--
     if ((string) $this->jsonrequest != '') {
         // json request
         //--
         if (!$this->socket) {
             //--
             if ($this->debug) {
                 $this->log .= '[ERR] Premature connection end (1.4)' . "\n";
                 Smart::log_notice('LibHTTP // GetFromURL // Premature connection end (1.4) ... ' . $url);
             }
             //end if
             return 0;
             //--
         }
         //end if
         //--
         if (@fwrite($this->socket, $this->jsonrequest . "\r\n") === false) {
             if ($this->debug) {
                 $this->log .= '[ERR] Error writing JSON Request data to socket' . "\n";
                 Smart::log_notice('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // Error writing JSON Request data to socket ...');
             }
             //end if
             return 0;
         }
         //end if
         //--
     } elseif ((string) $this->xmlrequest != '') {
         // xml request
         //--
         if (!$this->socket) {
             //--
             if ($this->debug) {
                 $this->log .= '[ERR] Premature connection end (1.5)' . "\n";
                 Smart::log_notice('LibHTTP // GetFromURL // Premature connection end (1.5) ... ' . $url);
             }
             //end if
             return 0;
             //--
         }
         //end if
         //--
         if (@fwrite($this->socket, $this->xmlrequest . "\r\n") === false) {
             if ($this->debug) {
                 $this->log .= '[ERR] Error writing XML Request data to socket' . "\n";
                 Smart::log_notice('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // Error writing XML Request data to socket ...');
             }
             //end if
             return 0;
         }
         //end if
         //--
     } elseif ($have_post_vars) {
         //--
         if (!$this->socket) {
             //--
             if ($this->debug) {
                 $this->log .= '[ERR] Premature connection end (1.6)' . "\n";
                 Smart::log_notice('LibHTTP // GetFromURL // Premature connection end (1.6) ... ' . $url);
             }
             //end if
             return 0;
             //--
         }
         //end if
         //--
         if (@fwrite($this->socket, $post_string . "\r\n") === false) {
             if ($this->debug) {
                 $this->log .= '[ERR] Error writing POST data to socket' . "\n";
                 Smart::log_notice('LibHTTP // GetFromURL (' . $browser_protocol . $server . ':' . $port . $path . ') // Error writing POST data to socket ...');
             }
             //end if
             return 0;
         }
         //end if
         //--
     }
     //end if else
     //--
     //-- NOTICE: is this necessary ??? appears that not (it was tested a long time without and appear to be faster) ...
     //if(@fwrite($this->socket, "\r\n") === false) {
     //	if($this->debug) {
     //		$this->log .= '[ERR] Error writing EOL to socket'."\n";
     //		Smart::log_notice('LibHTTP // GetFromURL ('.$conex_info.') // Error writing EOL ...'); // FIX: the final \r\n
     //	} //end if
     //} //end if
     //--
     //--
     return 1;
     //--
 }
 public static function getTranslationsFromSource($the_lang, $y_area, $y_subarea)
 {
     //--
     if (substr((string) $y_area, 0, 1) == '@') {
         if ((string) $the_lang == 'en') {
             $fdb_dir = 'lib/app/translations/';
         } else {
             // default is: modules/app/translations/
             $fdb_dir = (string) SMART_FRAMEWORK_LANGUAGES_CACHE_DIR;
         }
         //end if else
         $fdb_template = strtolower($y_area . '/' . $y_subarea . '-' . $the_lang);
     } else {
         // $y_area can be: apps, mod-something, ...
         $fdb_dir = (string) Smart::safe_pathname('modules/' . $y_area . '/translations/');
         $fdb_template = strtolower($y_subarea . '-' . $the_lang);
     }
     //end if else
     //--
     $fdb_file = (string) $fdb_dir . $fdb_template . '.yaml';
     SmartFileSysUtils::raise_error_if_unsafe_path($fdb_file);
     //--
     if (!is_dir($fdb_dir)) {
         Smart::raise_error('Invalid Language Dir: ' . $fdb_dir . ' :: for: ' . $y_area . '@' . $y_subarea, 'Invalid Language Dir for: ' . $y_area . '@' . $y_subarea);
         return array();
     }
     //end if
     //--
     if (!is_file($fdb_file)) {
         //--
         Smart::raise_error('Invalid Language File: ' . $fdb_file, 'Invalid Language File: ' . $fdb_template);
         return array();
         //--
     }
     //end if
     //--
     $fcontent = SmartFileSystem::staticread($fdb_file);
     $arr = (new SmartYamlConverter())->parse((string) $fcontent);
     //--
     if (!is_array($arr)) {
         Smart::raise_error('Parse Error / TRANSLATIONS :: Language File: ' . $fdb_file, 'Parse Error / TRANSLATIONS :: Language File: ' . $fdb_template);
         return array();
     }
     //end if
     //--
     if (!is_array($arr['TRANSLATIONS'])) {
         Smart::raise_error('Parse Error / TRANSLATIONS :: Language File: ' . $fdb_file, 'Parse Error / TRANSLATIONS :: Language File: ' . $fdb_template);
         return array();
     }
     //end if
     if (Smart::array_size($arr['TRANSLATIONS'][(string) $y_subarea]) <= 0) {
         Smart::log_warning('Parse Error / TRANSLATIONS.' . $y_subarea . ' :: Language File: ' . $fdb_template);
         return array();
     }
     //end if
     //--
     return (array) $arr['TRANSLATIONS'][(string) $y_subarea];
     //--
 }
 public function destroy($id)
 {
     //--
     $key = (string) $this->sess_area . ':' . str_replace(':', '-', $id . '-' . $this->sess_ns);
     //--
     $ok = $this->redis->del((string) $key);
     //--
     if ($ok <= 0) {
         Smart::log_warning('Redis Custom Session: Failed to destroy ...');
         return false;
     }
     //end if
     //--
     return true;
     //--
 }
Esempio n. 30
0
 private function _hash($string)
 {
     // force use sha1() encryption (unixman)
     //$result = sha1($string);
     //$out ='';
     // Convert hexadecimal hash value to binary string
     //for($c=0;$c<strlen($result);$c+=2) {
     //	$out .= chr(hexdec($result[$c].$result[$c+1]));
     //} //end for
     //return $out;
     switch ((string) $this->mode) {
         // enhancement by unixman
         case 'md5':
             $result = SmartHashCrypto::md5($string);
             break;
         case 'sha1':
             $result = SmartHashCrypto::sha1($string);
             break;
         case 'sha256':
             $result = SmartHashCrypto::sha256($string);
             break;
         case 'sha384':
             $result = SmartHashCrypto::sha384($string);
             break;
         case 'sha512':
             $result = SmartHashCrypto::sha512($string);
             break;
         default:
             Smart::log_warning('ERROR: Invalid mode for: SmartCryptoCipherHash / _hash: ' . $this->mode . ' ; Using sha1()');
             $result = sha1($string);
     }
     //end switch
     return (string) @hex2bin((string) $result);
     // convert hexadecimal hash value to binary string
 }