/**
  * Function: Draw Powered Info
  *
  * @access 		private
  * @internal
  *
  */
 public static function draw_powered_info($y_show_versions, $y_software_name = '', $y_software_powered_logo = '')
 {
     //--
     global $configs;
     //--
     $os_pict = self::get_os_pict(SmartUtils::get_server_os(), 'Server Powered by ');
     //--
     if ((string) $y_software_name == '' or (string) $y_software_powered_logo == '') {
         $y_software_name = 'Smart.Framework';
         $y_software_powered_logo = 'lib/framework/img/powered_by_smart_framework.png';
     }
     //end if
     //--
     $tmp_arr_web_server = SmartUtils::get_webserver_version();
     $name_webserver = Smart::escape_html($tmp_arr_web_server['name']);
     //--
     if ((string) $y_show_versions == 'yes') {
         // expose versions (not recommended in web area, except for auth admins)
         //--
         $y_software_name .= ' :: ' . SMART_SOFTWARE_APP_NAME;
         //--
         $version_webserver = ' :: ' . Smart::escape_html($tmp_arr_web_server['version']);
         $version_php = ' :: ' . Smart::escape_html(PHP_VERSION);
         //--
     } else {
         // avoid expose versions
         //--
         $version_webserver = '';
         $version_php = '';
         //--
     }
     //end if else
     //--
     if (trim(strtolower($name_webserver)) == 'apache') {
         $name_webserver = 'Apache';
         $icon_webserver_powered = 'lib/framework/img/powered_by_apache.png';
         $icon_webserver_logo = 'lib/framework/img/apache_logo_small_trans.png';
     } else {
         $icon_webserver_powered = 'lib/framework/img/powered_by_nginx.png';
         $icon_webserver_logo = 'lib/framework/img/nginx_logo_small_trans.png';
     }
     //end if else
     //--
     $version_dbserver = '';
     if (is_array($configs['pgsql'])) {
         if (defined('SMART_FRAMEWORK_DB_VERSION_PostgreSQL') and (string) $y_show_versions == 'yes') {
             $version_dbserver = ' :: ' . Smart::escape_html(SMART_FRAMEWORK_DB_VERSION_PostgreSQL);
         }
         //end if
         $name_dbserver = 'PostgreSQL';
         $icon_dbserver_powered = '<img src="lib/core/img/db/powered_by_postgresql.png">';
         $icon_dbserver_logo = '<img src="lib/core/img/db/postgresql_logo_small_trans.png">';
     } else {
         $name_dbserver = '';
         $icon_dbserver_powered = '';
         $icon_dbserver_logo = '';
     }
     //end if else
     //--
     if (is_array($configs['redis'])) {
         $name_cacheserver = 'Redis';
         $icon_cacheserver_powered = '<img src="lib/core/img/db/powered_by_redis.png">';
         $icon_cacheserver_logo = '<img src="lib/core/img/db/redis_logo_small_trans.png">';
     } else {
         $name_cacheserver = '';
         $icon_cacheserver_powered = '';
         $icon_cacheserver_logo = '';
     }
     //end if
     //--
     $name_dblite = 'SQLite';
     $icon_dblite_powered = 'lib/core/img/db/powered_by_sqlite.png';
     $icon_dblite_logo = 'lib/core/img/db/sqlite_logo_small.png';
     //--
     return (string) SmartMarkersTemplating::render_file_template('lib/core/templates/powered-info.inc.htm', ['OS-LOGO' => $os_pict, 'WEB-SERVER-POWERED-VERSION' => $name_webserver . $version_webserver, 'WEB-SERVER-POWERED-ICON' => $icon_webserver_powered, 'WEB-SERVER-VERSION' => $name_webserver . ' Web Server', 'WEB-SERVER-ICON' => $icon_webserver_logo, 'PHP-VERSION' => $version_php, 'DBSERVER-NAME' => $name_dbserver, 'DBSERVER-VERSION' => $version_dbserver, 'DBSERVER-POWERED-ICON' => $icon_dbserver_powered, 'DBSERVER-POWERED-LOGO' => $icon_dbserver_logo, 'CACHESERVER-NAME' => $name_cacheserver, 'CACHESERVER-POWERED-ICON' => $icon_cacheserver_powered, 'CACHESERVER-POWERED-LOGO' => $icon_cacheserver_logo, 'DBLITE-NAME' => $name_dblite, 'DBLITE-POWERED-ICON' => $icon_dblite_powered, 'DBLITE-POWERED-LOGO' => $icon_dblite_logo, 'SOFTWARE-NAME' => Smart::escape_html($y_software_name), 'SOFTWARE-POWERED-LOGO' => Smart::escape_html($y_software_powered_logo)]);
     //--
 }
 /**
  * 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;
     //--
 }
 public static function verify($y_form_name, $y_mode, $y_clear = true)
 {
     //--
     $y_form_name = trim((string) $y_form_name);
     //--
     $ok = 1;
     // default, if not active
     //--
     if (self::validate_form_name($y_form_name) !== 1) {
         return 0;
         // invalid form name
     }
     //end if
     //--
     $cookie_name = self::cookiename($y_form_name);
     //--
     if ((string) $y_mode == 'session') {
         //--
         $cookie_value = (string) SmartSession::get((string) $cookie_name);
         $run_mode = 'session';
         //--
     } else {
         //--
         $cookie_value = (string) $_COOKIE[(string) $cookie_name];
         $run_mode = 'cookie';
         //--
     }
     //end if else
     //--
     $var_name = self::jscookiename($y_form_name);
     $var_value = trim((string) $_COOKIE[(string) $var_name]);
     //--
     if ((string) $var_value != '') {
         $arr_value = explode('!', base64_decode(SmartUtils::crypto_blowfish_decrypt(SmartArchiverLZS::decompressFromBase64((string) $var_value), sha1($y_form_name . SMART_FRAMEWORK_SECURITY_KEY))));
         // explode by '!'
     }
     //end if
     //--
     $ok = 0;
     // error check by default
     //--
     if (@strlen($var_value) > 0 and (string) $cookie_value == (string) self::checksum(trim($arr_value[1]))) {
         //--
         $ok = 1;
         //--
         if ($y_clear == true) {
             // clear is optional (there are situations when after veryfying captcha, even if OK, other code must be run and if that code returns error, still captcha must be active, not cleared (so clearing it manually is a solution ...)
             self::clear($y_form_name, $y_mode);
         }
         //end if
         //--
     }
     //end if
     //--
     return $ok;
     //--
 }
 private static function print_log_resources($time_res, $mem_res)
 {
     //--
     $log = '';
     //--
     $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_head"><font size="4"><b>Script Execution :: RESOURCES Log</b></font></div>';
     $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_status_highlight" style="width:450px;"><b>Script Execution Resources</b></div>';
     $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_inforow" style="width:450px;">Execution Time: <b>' . Smart::format_number_dec($time_res, 13, '.', '') . ' sec.' . '</b></div>';
     $log .= '<div class="smartframework_debugbar_status smartframework_debugbar_inforow" style="width:450px;">Execution Memory: <b>' . SmartUtils::pretty_print_bytes($mem_res, 2) . '</b></div>';
     //--
     return $log;
     //--
 }
 /**
  * Get A UNIQUE (SAFE) ID for DB Tables
  *
  * @param ENUM $y_mode 							:: mode: uid10str | uid10num | uid36 | uid45
  * @param STRING $y_field_name 					:: the field name
  * @param STRING $y_table_name 					:: the table name
  * @param RESOURCE $y_connection 				:: the connection to mysql server
  * @return STRING 								:: the generated Unique ID
  *
  */
 public static function new_safe_id($y_mode, $y_id_field, $y_table_name, $y_connection = 'DEFAULT')
 {
     //==
     $y_connection = self::check_connection($y_connection, 'NEW-SAFE-ID');
     //==
     //--
     if (!self::validate_table_and_fields_names($y_table_name)) {
         self::error(self::get_connection_id($y_connection), 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Table Name', $y_table_name);
         return '';
     }
     //end if
     if (!self::validate_table_and_fields_names($y_id_field)) {
         self::error(self::get_connection_id($y_connection), 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Field Name', $y_id_field . ' / [Table=' . $y_table_name . ']');
         return '';
     }
     //end if
     //--
     //--
     $tmp_result = 'NO-ID-INIT';
     //init (must be not empty)
     $counter = 0;
     // default is zero
     //--
     while ((string) $tmp_result != '') {
         // while we cannot find an unused ID
         //--
         $counter += 1;
         //--
         if ($counter > 7500) {
             // loop to max 7500
             self::error(self::get_connection_id($y_connection), 'NEW-SAFE-ID', 'Get New Safe ID', 'Could Not Assign a Unique ID', '(timeout / 7500) ... try again !');
             return '';
         }
         //end if
         //--
         if ($counter % 500 == 0) {
             sleep(1);
         }
         //end if
         //--
         $new_id = 'NO-ID-ALGO';
         switch ((string) $y_mode) {
             case 'uid45':
                 $new_id = (string) Smart::uuid_45(SMART_FRAMEWORK_NETSERVER_ID . SmartUtils::get_server_current_url());
                 // will use the server ID.Host as Prefix to ensure it is true unique in a cluster
                 break;
             case 'uid36':
                 $new_id = (string) Smart::uuid_36(SMART_FRAMEWORK_NETSERVER_ID . SmartUtils::get_server_current_url());
                 // will use the server ID.Host as Prefix to ensure it is true unique in a cluster
                 break;
                 //			case 'uid10seq': // sequences are not safe without a second registry allocation table as the chance to generate the same ID in the same time moment is just 1 in 999
                 //				$new_id = (string) Smart::uuid_10_seq();
                 //				break;
             //			case 'uid10seq': // sequences are not safe without a second registry allocation table as the chance to generate the same ID in the same time moment is just 1 in 999
             //				$new_id = (string) Smart::uuid_10_seq();
             //				break;
             case 'uid10num':
                 $new_id = (string) Smart::uuid_10_num();
                 break;
             case 'uid10str':
             default:
                 $new_id = (string) Smart::uuid_10_str();
         }
         //end switch
         //--
         $result_arr = array();
         $result_arr = self::read_data('SELECT `' . $y_id_field . '` FROM `' . $y_table_name . '` WHERE (`' . $y_id_field . '` = \'' . $this->quote($new_id) . '\') LIMIT 1 OFFSET 0', 'Checking if NEW ID Exists ...', $y_connection);
         $tmp_result = (string) trim((string) $result_arr[0]);
         $result_arr = array();
         //--
     }
     //end while
     //--
     //--
     return (string) $new_id;
     //--
 }
 private function mov_draw_box($y_dir, $y_video_file, $y_type)
 {
     //--
     $description = Smart::escape_html($this->standardize_title($y_video_file));
     //--
     //--
     $base_preview = SmartFileSysUtils::version_add($y_video_file, 'mg-vpreview') . '.jpg';
     $preview_file = $y_dir . $base_preview;
     $video_file = $y_dir . $y_video_file;
     //--
     //--
     if ((string) $this->use_secure_links == 'yes') {
         // OK
         $the_preview = (string) $this->secure_download_link . SmartUtils::create_download_link($preview_file, $this->secure_download_ctrl_key);
         $the_video = (string) $this->secure_download_link . SmartUtils::create_download_link($video_file, $this->secure_download_ctrl_key);
     } else {
         $the_preview = (string) $preview_file;
         $the_video = (string) $video_file;
     }
     //end if else
     //--
     //--
     if ((string) $y_type == 'ogv' or (string) $y_type == 'webm' or (string) $y_type == 'mp4') {
         // {{{SYNC-MOVIE-TYPE}}}
         $link = $this->url_player_mov . $the_video;
     } else {
         // mp4, mov, flv
         //if((string)self::get_server_current_protocol() == 'https://'){} // needs fix: the Flash player do not work with mixing http/https
         $link = $this->url_player_mov . $the_video;
     }
     //end if else
     //--
     $link = str_replace(array('{{{MOVIE-FILE}}}', '{{{MOVIE-TYPE}}}', '{{{MOVIE-TITLE}}}'), array(rawurlencode($the_video), rawurlencode($y_type), rawurlencode($description)), $link);
     //--
     //--
     $out = '';
     //--
     if (strlen($this->force_preview_w) > 0) {
         $forced_dim = ' width="' . $this->force_preview_w . '"';
     } elseif (strlen($this->force_preview_h) > 0) {
         $forced_dim = ' height="' . $this->force_preview_h . '"';
     } else {
         $forced_dim = '';
     }
     //end if else
     //--
     $out .= '<div align="center" id="mediagallery_box_item">';
     //--
     if ((string) $this->preview_description == 'no') {
         $description = '';
     }
     //end if
     //--
     $out .= '<a data-smart="open.modal 780 475 1" rel="nofollow" href="' . $link . '" target="media-gallery-movie-player" ' . 'title="' . $description . '"' . '>';
     $out .= '<img src="' . Smart::escape_html($the_preview) . '" border="0" alt="' . $description . '" title="' . $description . '"' . $forced_dim . '>';
     $out .= '</a>';
     //--
     if (strlen($this->preview_formvar) > 0) {
         $out .= '<input type="checkbox" name="' . $this->preview_formvar . '[]" value="' . Smart::escape_html($y_video_file . '|' . $base_preview) . '" title="' . Smart::escape_html($y_video_file . '|' . $base_preview) . '">' . $this->preview_formpict;
     }
     //end if
     //--
     if ((string) $this->preview_description != 'no') {
         if (strlen($description) > 0) {
             $out .= '<div id="mediagallery_label">' . $description . '</div>';
         }
         //end if
     }
     //end if
     //--
     $out .= '</div>';
     //--
     //--
     return $out;
     //--
 }
示例#7
0
 public static final function DownloadsHandler($encrypted_download_pack, $controller_key)
 {
     //--
     $encrypted_download_pack = (string) $encrypted_download_pack;
     $controller_key = (string) $controller_key;
     //--
     $client_signature = SmartUtils::get_visitor_signature();
     //--
     if ((string) SMART_APP_VISITOR_COOKIE == '') {
         Smart::log_info('File Download', 'Failed: 400 / Invalid Visitor Cookie' . ' on Client: ' . $client_signature);
         self::Raise400Error('ERROR: Invalid Visitor UUID. Cookies must be enabled to enable this feature !');
         return '';
     }
     //end if
     //--
     $downloaded_file = '';
     // init
     //--
     $decoded_download_packet = (string) trim((string) SmartUtils::crypto_decrypt((string) $encrypted_download_pack, 'SmartFramework//DownloadLink' . SMART_FRAMEWORK_SECURITY_KEY));
     //--
     if ((string) $decoded_download_packet != '') {
         // if data is corrupted, decrypt checksum does not match, will return an empty string
         //--
         if (SMART_FRAMEWORK_ADMIN_AREA === true) {
             // {{{SYNC-DWN-CTRL-PREFIX}}}
             $controller_key = (string) 'AdminArea/' . $controller_key;
         } else {
             $controller_key = (string) 'IndexArea/' . $controller_key;
         }
         //end if
         //-- {{{SYNC-DOWNLOAD-ENCRYPT-ARR}}}
         $arr_metadata = explode("\n", (string) $decoded_download_packet, 6);
         // only need first 5 parts
         //print_r($arr_metadata);
         // #PACKET-STRUCTURE# [we will have an array like below, according with the: SmartUtils::create_download_link()]
         // [TimedAccess]\n
         // [FilePath]\n
         // [AccessKey]\n
         // [UniqueKey]\n
         // [SFR.UA]\n
         // #END#
         //--
         $crrtime = (string) trim((string) $arr_metadata[0]);
         $filepath = (string) trim((string) $arr_metadata[1]);
         $access_key = (string) trim((string) $arr_metadata[2]);
         $unique_key = (string) trim((string) $arr_metadata[3]);
         //--
         unset($arr_metadata);
         //--
         $timed_hours = 1;
         // default expire in 1 hour
         if (defined('SMART_FRAMEWORK_DOWNLOAD_EXPIRE')) {
             if ((int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE > 0) {
                 if ((int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE <= 24) {
                     // max is 24 hours (since download link is bind to unique browser signature + unique cookie ... make non-sense to keep more)
                     $timed_hours = (int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE;
                 }
                 //end if
             }
             //end if
         }
         //end if
         //--
         if ((int) $timed_hours > 0) {
             if ((int) $crrtime < (int) (time() - 60 * 60 * $timed_hours)) {
                 Smart::log_info('File Download', 'Failed: 403 / Download expired at: ' . date('Y-m-d H:i:s O', (int) $crrtime) . ' for: ' . $filepath . ' on Client: ' . $client_signature);
                 self::Raise403Error('ERROR: The Access Key for this Download is Expired !');
                 return '';
             }
             //end if
         }
         //end if
         //--
         if ((string) $access_key != (string) sha1('DownloadLink:' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . SMART_APP_VISITOR_COOKIE . ':' . $filepath . '^' . $controller_key)) {
             Smart::log_info('File Download', 'Failed: 403 / Invalid Access Key for: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise403Error('ERROR: Invalid Access Key for this Download !');
             return '';
         }
         //end if
         //--
         if ((string) $unique_key != (string) SmartHashCrypto::sha1('Time=' . $crrtime . '#' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . $access_key . '-' . SmartUtils::unique_auth_client_private_key() . ':' . $filepath . '+' . $controller_key)) {
             Smart::log_info('File Download', 'Failed: 403 / Invalid Client (Unique) Key for: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise403Error('ERROR: Invalid Client Key to Access this Download !');
             return '';
         }
         //end if
         //--
         if (SmartFileSysUtils::check_file_or_dir_name($filepath)) {
             //--
             $skip_log = 'no';
             // default log
             if (defined('SMART_FRAMEWORK_DOWNLOAD_SKIP_LOG')) {
                 $skip_log = 'yes';
                 // do not log if accessed via admin area and user is authenticated
             }
             //end if
             //--
             $tmp_file_ext = (string) strtolower(SmartFileSysUtils::get_file_extension_from_path($filepath));
             // [OK]
             $tmp_file_name = (string) strtolower(SmartFileSysUtils::get_file_name_from_path($filepath));
             //--
             $tmp_eval = SmartFileSysUtils::mime_eval($tmp_file_name);
             $mime_type = (string) $tmp_eval[0];
             $mime_disp = (string) $tmp_eval[1];
             //-- the path must not start with / but this is tested below
             $tmp_arr_paths = (array) explode('/', $filepath, 2);
             // only need 1st part for testing
             //-- allow file downloads just from specific folders like wpub/ or wsys/ (this is a very important security fix to dissalow any downloads that are not in the specific folders)
             if (substr((string) $filepath, 0, 1) != '/' and strpos((string) SMART_FRAMEWORK_DOWNLOAD_FOLDERS, '<' . trim((string) $tmp_arr_paths[0]) . '>') !== false and stripos((string) SMART_FRAMEWORK_DENY_UPLOAD_EXTENSIONS, '<' . $tmp_file_ext . '>') === false) {
                 //--
                 SmartFileSysUtils::raise_error_if_unsafe_path($filepath);
                 // re-test finally
                 //--
                 @clearstatcache();
                 //--
                 if (is_file($filepath)) {
                     //--
                     if (!headers_sent()) {
                         //--
                         $fp = @fopen($filepath, 'rb');
                         $fsize = @filesize($filepath);
                         //--
                         if (!$fp || $fsize <= 0) {
                             //--
                             Smart::log_info('File Download', 'Failed: 404 / The requested File is Empty or Not Readable: ' . $filepath . ' on Client: ' . $client_signature);
                             self::Raise404Error('WARNING: The requested File is Empty or Not Readable !');
                             return '';
                             //--
                         }
                         //end if
                         //-- set max execution time to zero
                         ini_set('max_execution_time', 0);
                         // we can expect a long time if file is big, but this will be anyway overriden by the WebServer Timeout Directive
                         //--
                         // cache headers are presumed to be sent by runtime before of this step
                         //--
                         header('Content-Type: ' . $mime_type);
                         header('Content-Disposition: ' . $mime_disp);
                         header('Content-Length: ' . $fsize);
                         //--
                         @fpassthru($fp);
                         // output without reading all in memory
                         //--
                         @fclose($fp);
                         //--
                     } else {
                         //--
                         Smart::log_info('File Download', 'Failed: 500 / Headers Already Sent: ' . $filepath . ' on Client: ' . $client_signature);
                         self::Raise500Error('ERROR: Download Failed, Headers Already Sent !');
                         return '';
                         //--
                     }
                     //end if else
                     //--
                     if ((string) $skip_log != 'yes') {
                         //--
                         $downloaded_file = (string) $filepath;
                         // return the file name to be logged
                         //--
                     }
                     //end if
                     //--
                 } else {
                     //--
                     Smart::log_info('File Download', 'Failed: 404 / The requested File does not Exists: ' . $filepath . ' on Client: ' . $client_signature);
                     self::Raise404Error('WARNING: The requested File for Download does not Exists !');
                     return '';
                     //--
                 }
                 //end if else
             } else {
                 //--
                 Smart::log_info('File Download', 'Failed: 403 / Access to this File is Denied: ' . $filepath . ' on Client: ' . $client_signature);
                 self::Raise403Error('ERROR: Download Access to this File is Denied !');
                 return '';
                 //--
             }
             //end if else
             //--
         } else {
             //--
             Smart::log_info('File Download', 'Failed: 400 / Unsafe File Path: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise400Error('ERROR: Unsafe Download File Path !');
             return '';
             //--
         }
         //end if else
         //--
     } else {
         //--
         Smart::log_info('File Download', 'Failed: 400 / Invalid Data Packet' . ' on Client: ' . $client_signature);
         self::Raise400Error('ERROR: Invalid Download Data Packet !');
         return '';
         //--
     }
     //end if else
     //--
     return (string) $downloaded_file;
     //--
 }
示例#8
0
 private function _generate_iv()
 {
     // Initialize pseudo random generator
     // seed rand: (double)microtime()*1000000 // no more needed
     // Collect very random data.
     // Add as many "pseudo" random sources as you can find.
     // Possible sources: Memory usage, diskusage, file and directory content...
     $iv = Smart::random_number();
     $iv .= Smart::unique_entropy();
     $iv .= SmartUtils::get_visitor_tracking_uid();
     $iv .= implode("\r", (array) $_SERVER);
     $iv .= implode("\r", (array) $_COOKIES);
     return $this->_hash($iv);
 }
 /**
  * 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;
     //--
 }
 /**
  * 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;
     //--
 }
示例#11
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
     //--
 }
 /**
  * Set a Page into the (Persistent) Cache.
  *
  * @param 	STRING 		$storage_namespace		:: the cache storage namespace, used to group keys
  * @param 	STRING 		$unique_key				:: the unique cache key
  * @param 	MIXED 		$content 				:: the cache content as a STRING or an ARRAY with Page Value(s) / Page Setting(s)
  * @param 	INTEGER 	$expiration 			:: The page cache expiration in seconds ; 0 will not expire
  *
  * @return 	BOOL								:: TRUE if the PersistentCache is active and value was set ; FALSE in the rest of the cases
  */
 public final function PageSetInCache($storage_namespace, $unique_key, $content, $expiration)
 {
     //--
     if (empty($content)) {
         return false;
     }
     //end if
     //--
     if (!SmartPersistentCache::isActive()) {
         return false;
     }
     //end if
     //--
     $cache = SmartUtils::cache_variable_archive($content);
     // mixed (number / string / array)
     if ((string) $cache == '') {
         return false;
     }
     //end if
     //--
     return SmartPersistentCache::setKey((string) $storage_namespace, (string) $unique_key, (string) $cache, (int) $expiration);
     //--
 }
 private static function mime_link($y_ctrl_key, $y_msg_file, $y_part, $y_link, $y_rawmime, $y_rawdisp, $y_printable = '')
 {
     //--
     $y_msg_file = (string) $y_msg_file;
     $y_part = (string) $y_part;
     $y_link = (string) $y_link;
     $y_rawmime = (string) $y_rawmime;
     $y_rawdisp = (string) $y_rawdisp;
     $y_printable = (string) $y_printable;
     //--
     $the_url_param_msg = '';
     $the_url_param_raw = '';
     $the_url_param_mime = '';
     $the_url_param_disp = '';
     //--
     if ((string) $y_link != '' and (string) $y_msg_file != '') {
         //--
         $the_url_param_msg = (string) self::encode_mime_fileurl((string) $y_msg_file, (string) $y_ctrl_key);
         // {{{SYNC-MIME-ENCRYPT-ARR}}}
         if ((string) $y_part != '') {
             $the_url_param_msg .= '@' . SmartUtils::url_hex_encode((string) $y_part);
             // have part
         }
         //end if
         //--
         if ((string) $y_rawmime != '') {
             $the_url_param_raw = 'raw';
             $the_url_param_mime = (string) Smart::escape_url(SmartUtils::url_hex_encode((string) $y_rawmime));
         }
         //end if
         if ((string) $y_rawdisp != '') {
             $the_url_param_raw = 'raw';
             $the_url_param_disp = (string) Smart::escape_url(SmartUtils::url_hex_encode((string) $y_rawdisp));
         }
         //end if
         //--
         if ((string) $y_printable != '') {
             // printable display
             $y_link .= '&' . SMART_FRAMEWORK_URL_PARAM_PRINTABLE . '=' . Smart::escape_url((string) SMART_FRAMEWORK_URL_VALUE_ENABLED);
             // .'&'.SMART_FRAMEWORK_URL_PARAM_MODALPOPUP.'='. Smart::escape_url((string)SMART_FRAMEWORK_URL_VALUE_ENABLED).'&';
         }
         //end if else
         //--
         $y_link = str_replace(array('{{{MESSAGE}}}', '{{{RAWMODE}}}', '{{{MIME}}}', '{{{DISP}}}'), array((string) $the_url_param_msg, (string) $the_url_param_raw, (string) $the_url_param_mime, (string) $the_url_param_disp), (string) $y_link);
         //--
     }
     //end if
     //--
     return (string) $y_link;
     //--
 }
 public static function Run()
 {
     //--
     global $configs;
     //--
     //==
     //--
     if (self::$MiddlewareCompleted !== false) {
         // avoid to execute more than 1 this middleware !
         self::Raise500Error('Middleware App Execution already completed ...');
         return;
     }
     //end if
     self::$MiddlewareCompleted = true;
     //--
     $the_midmark = '[A]';
     //--
     if (SMART_FRAMEWORK_ADMIN_AREA !== true) {
         Smart::raise_error('Admin Middleware ERROR: SMART_FRAMEWORK_ADMIN_AREA is not set to TRUE', 'Invalid Area / This middleware is designed for Admin area and requires to turn ON the Administration flag ...');
         return;
     }
     //end if
     //--
     if (!defined('SMART_APP_TEMPLATES_DIR')) {
         self::Raise500Error('The SMART_APP_TEMPLATES_DIR not defined ...');
         return;
     }
     //end if
     //--
     if (defined('SMART_APP_MODULE_AREA')) {
         self::Raise500Error('Smart App Area must NOT be Defined outside controllers ...');
         return;
     }
     //end if
     if (defined('SMART_APP_MODULE_AUTH')) {
         self::Raise500Error('Smart App Module Auth must NOT be Defined outside controllers ...');
         return;
     }
     //end if
     if (defined('SMART_APP_MODULE_REALM_AUTH')) {
         self::Raise500Error('Smart App Module Realm Auth must NOT be Defined outside controllers ...');
         return;
     }
     //end if
     if (defined('SMART_APP_MODULE_DIRECT_OUTPUT')) {
         self::Raise500Error('Smart App Module Direct Output must NOT be Defined outside controllers ...');
         return;
     }
     //end if
     //--
     //==
     //--
     $smartframeworkservice = '';
     // special operation
     if (SmartFrameworkRegistry::issetRequestVar('smartframeworkservice') === true) {
         $smartframeworkservice = (string) strtolower((string) SmartUnicode::utf8_to_iso((string) SmartFrameworkRegistry::getRequestVar('smartframeworkservice')));
         switch ((string) $smartframeworkservice) {
             case 'status':
             case 'debug':
                 break;
             default:
                 // invalid value
                 $smartframeworkservice = '';
         }
         //end switch
     }
     //end if
     //--
     //==
     //-- switch language by cookie (this needs to be before loading the app core)
     if (strlen(trim((string) $_COOKIE['SmartApp_ADM_LANGUAGE_SET'])) > 0) {
         SmartTextTranslations::setLanguage(trim((string) $_COOKIE['SmartApp_ADM_LANGUAGE_SET']));
     }
     //end if
     //-- switch language by print cookie (this needs to be before loading the app core and after language by cookie)
     if (SmartFrameworkRegistry::issetRequestVar((string) SMART_FRAMEWORK_URL_PARAM_PRINTABLE) === true) {
         if (strtolower((string) SmartFrameworkRegistry::getRequestVar((string) SMART_FRAMEWORK_URL_PARAM_PRINTABLE)) == strtolower((string) SMART_FRAMEWORK_URL_VALUE_ENABLED)) {
             if (strlen(trim((string) $_COOKIE['SmartApp_ADM_PRINT_LANGUAGE_SET'])) > 0) {
                 SmartTextTranslations::setLanguage(trim((string) $_COOKIE['SmartApp_ADM_PRINT_LANGUAGE_SET']));
             }
             //end if
         }
         //end if
     }
     //end if
     //--
     //== RAW OUTPUT FOR STATUS
     //--
     if ((string) $smartframeworkservice == 'status') {
         //--
         if (SMART_SOFTWARE_DISABLE_STATUS_POWERED === true) {
             $status_powered_info = '';
         } else {
             $status_powered_info = (string) SmartComponents::draw_powered_info('no');
         }
         //end if else
         //--
         self::HeadersNoCache();
         // headers: cache control, force no-cache
         echo SmartComponents::http_status_message('Smart.Framework :: Status :: [OK]', '<script type="text/javascript">setTimeout(function(){ self.location = self.location; }, 60000);</script><img src="lib/core/img/busy_bar.gif"><div><h1>' . date('Y-m-d H:i:s O') . ' // Service Ready :: ' . $the_midmark . '</h1></div>' . $status_powered_info . '<br>');
         //--
         return;
         // break stop
         //--
     }
     //end if
     //--
     //== OVERALL AUTHENTICATION BREAKPOINT
     //--
     SmartAppBootstrap::Authenticate('admin');
     // if the auth uses session it may start now
     //--
     //== RAW OUTPUT FOR DEBUG
     //--
     if ((string) $smartframeworkservice == 'debug') {
         //--
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             self::HeadersNoCache();
             // headers: cache control, force no-cache
             $the_debug_cookie = trim((string) $_COOKIE['SmartFramework__DebugAdmID']);
             echo SmartDebugProfiler::print_debug_info('adm', $the_debug_cookie);
         } else {
             http_response_code(404);
             echo SmartComponents::http_message_404_notfound('No Debug service has been activated on this server ...');
         }
         //end if
         //--
         return;
         // break stop
         //--
     }
     //end if else
     //--
     //== LOAD THE MODULE (OR DEFAULT MODULE)
     //--
     $reserved_controller_names = ['php', 'html', 'stml', 'css', 'js', 'json', 'xml', 'rss', 'txt', 'csv', 'sql', 'png', 'gif', 'jpg', 'pdf', 'svg', 'zip', '7z', 'netarch'];
     // these are reserved extensions and cannot be used as controller names because they need to be used also with friendly URLs as the 2nd param if module is missing from URL page param
     //--
     $err404 = '';
     $arr = array();
     //--
     $page = (string) SmartUnicode::utf8_to_iso((string) SmartFrameworkRegistry::getRequestVar('page'));
     $page = trim(str_replace(array('/', '\\', ':', '?', '&', '=', '%'), array('', '', '', '', '', '', ''), $page));
     // fix for get as it automatically replaces . with _ (so, reverse), but also fix some invalid characters ...
     if ((string) $page == '') {
         $page = (string) $configs['app']['admin-home'];
     }
     //end if
     //--
     if (strpos($page, '.') !== false) {
         // page can be as module.controller / module.controller(.php|html|stml|css|js|json|xml|rss|txt|csv|sql|png|gif|jpg|pdf|svg|zip|7z|netarch)
         //--
         $arr = (array) explode('.', (string) $page, 3);
         // separe 1st and 2nd from the rest
         //--
         //#
         //#
         $arr[0] = trim(strtolower((string) $arr[0]));
         // module
         $arr[1] = trim(strtolower((string) $arr[1]));
         // controller
         //#
         //# Admin will NOT integrate with friendly URLs SMART_FRAMEWORK_SEMANTIC_URL_SKIP_MODULE
         //# that feature is just for Index
         //#
         //--
     } elseif ((string) $configs['app']['admin-default-module'] != '') {
         //--
         $arr[0] = trim(strtolower((string) $configs['app']['admin-default-module']));
         // get default module
         $arr[1] = trim(strtolower((string) $page));
         // controller
         //--
     } else {
         //--
         if ((string) $err404 == '') {
             $err404 = 'Invalid Page (Invalid URL Page Segments Syntax): ' . $page;
         }
         //end if
         //--
     }
     //end if else
     //--
     if ((string) $arr[0] == '' or (string) $arr[1] == '') {
         if ((string) $err404 == '') {
             $err404 = 'Invalid Page (Empty or Missing URL Page Segments): ' . $page;
         }
         //end if
     }
     //end if
     if (!preg_match('/^[a-z0-9_\\-]+$/', (string) $arr[0]) or !preg_match('/^[a-z0-9_\\-]+$/', (string) $arr[1])) {
         if ((string) $err404 == '') {
             $err404 = 'Invalid Page (Invalid Characters in the URL Page Segments): ' . $page;
         }
         //end if
     }
     //end if
     if (in_array((string) $arr[1], (array) $reserved_controller_names)) {
         if ((string) $err404 == '') {
             $err404 = 'Invalid Page (Reserved Page Controller Name): [' . $arr[1] . '] in: ' . $page;
         }
         //end if
     }
     //end if
     //--
     $the_controller_name = (string) $arr[0] . '.' . $arr[1];
     $the_path_to_module = Smart::safe_pathname(SmartFileSysUtils::add_dir_last_slash('modules/mod-' . Smart::safe_filename($arr[0])));
     $the_module = Smart::safe_pathname($the_path_to_module . Smart::safe_filename($arr[1]) . '.php');
     if (!is_file($the_module)) {
         if ((string) $err404 == '') {
             $err404 = 'Page does not exist: ' . $page;
         }
         //end if
     }
     //end if
     //--
     if ((string) $err404 != '') {
         self::Raise404Error((string) $err404);
         return;
     }
     //end if
     //--
     if (!SmartFileSysUtils::check_file_or_dir_name($the_path_to_module) or !SmartFileSysUtils::check_file_or_dir_name($the_module)) {
         self::Raise400Error('Insecure Module Access for Page: ' . $page);
         return;
     }
     //end if
     //--
     if (class_exists('SmartAppIndexController') or class_exists('SmartAppAdminController')) {
         self::Raise500Error('Module Class Runtimes must be defined only in modules ...');
         return;
     }
     //end if
     //--
     require (string) $the_module;
     //--
     if ((string) SMART_APP_MODULE_AREA !== 'ADMIN' and (string) SMART_APP_MODULE_AREA !== 'SHARED') {
         self::Raise403Error('Page Access Denied for Admin Area: ' . $page);
         return;
     }
     //end if
     if (defined('SMART_APP_MODULE_AUTH')) {
         if (SmartAuth::check_login() !== true) {
             self::Raise403Error('Page Access Denied ! No Authentication: ' . $page);
             return;
         }
         //end if
         if (defined('SMART_APP_MODULE_REALM_AUTH')) {
             if ((string) SmartAuth::get_login_realm() !== (string) SMART_APP_MODULE_REALM_AUTH) {
                 self::Raise403Error('Page Access Denied ! Invalid Login Realm: ' . $page);
                 return;
             }
             //end if
         }
         //end if
     }
     //end if
     //--
     if (!class_exists('SmartAppAdminController')) {
         self::Raise500Error('Invalid Module Class Runtime for Page: ' . $page);
         return;
     }
     //end if
     if (!is_subclass_of('SmartAppAdminController', 'SmartAbstractAppController')) {
         self::Raise500Error('Invalid Module Class Inheritance for Controller Page: ' . $page);
         return;
     }
     //end if
     //--
     //== PATHS
     //--
     $base_script = SmartUtils::get_server_current_script();
     $base_full_path = SmartUtils::get_server_current_path();
     $base_full_url = SmartUtils::get_server_current_url();
     //--
     //== RUN THE MODULE
     //--
     $appModule = new SmartAppAdminController($the_path_to_module, $base_script, $base_full_path, $base_full_url, $page, $the_controller_name);
     //--
     if (SMART_APP_MODULE_DIRECT_OUTPUT !== true) {
         ob_start();
     }
     //end if
     $appStatusCode = (int) $appModule->Run();
     $appModule->ShutDown();
     if (SMART_APP_MODULE_DIRECT_OUTPUT !== true) {
         $ctrl_output = ob_get_contents();
         ob_end_clean();
         if ((string) $ctrl_output != '') {
             Smart::log_warning('The middleware service ' . $the_midmark . ' detected an illegal output in the controller: ' . $page . "\n" . 'The result of this output is: ' . $ctrl_output);
         }
         //end if
         $ctrl_output = '';
     } else {
         return;
         // break stop after the controller has terminated the direct output
     }
     //end if else
     //--
     $appSettings = (array) $appModule->PageViewGetCfgs();
     //--
     //== CACHE CONTROL
     //--
     if ((int) $appSettings['expires'] > 0 and (string) SMART_FRAMEWORK_DEBUG_MODE != 'yes') {
         self::HeadersCacheExpire((int) $appSettings['expires'], (int) $appSettings['modified']);
         // headers: cache expiration control
     } else {
         self::HeadersNoCache();
         // headers: cache control, force no-cache
     }
     //end if else
     //--
     //== STATUS CODE
     //--
     switch ((int) $appStatusCode) {
         //-- client errors
         case 400:
             self::Raise400Error((string) $appSettings['error']);
             return;
             break;
         case 401:
             self::Raise401Error((string) $appSettings['error']);
             return;
             break;
         case 403:
             self::Raise403Error((string) $appSettings['error']);
             return;
             break;
         case 404:
             self::Raise404Error((string) $appSettings['error']);
             return;
             break;
         case 429:
             self::Raise429Error((string) $appSettings['error']);
             return;
             break;
             //-- server errors
         //-- server errors
         case 500:
             self::Raise500Error((string) $appSettings['error']);
             return;
             break;
         case 502:
             self::Raise502Error((string) $appSettings['error']);
             return;
             break;
         case 503:
             self::Raise503Error((string) $appSettings['error']);
             return;
             break;
         case 504:
             self::Raise504Error((string) $appSettings['error']);
             return;
             break;
             //-- extended 2xx statuses: NOTICE / WARNING / ERROR that can be used for REST / API
         //-- extended 2xx statuses: NOTICE / WARNING / ERROR that can be used for REST / API
         case 202:
             // NOTICE
             if (!headers_sent()) {
                 http_response_code(202);
                 // Accepted (this should be used only as an alternate SUCCESS code instead of 200 for NOTICES)
             } else {
                 Smart::log_warning('Headers Already Sent before 202 ...');
             }
             //end if else
             break;
         case 203:
             // WARNING
             if (!headers_sent()) {
                 http_response_code(203);
                 // Non-Authoritative Information (this should be used only as an alternate SUCCESS code instead of 200 for WARNINGS)
             } else {
                 Smart::log_warning('Headers Already Sent before 203 ...');
             }
             //end if else
             break;
         case 208:
             // ERROR
             if (!headers_sent()) {
                 http_response_code(208);
                 // Already Reported (this should be used only as an alternate SUCCESS code instead of 200 for ERRORS)
             } else {
                 Smart::log_warning('Headers Already Sent before 208 ...');
             }
             //end if else
             break;
             //-- DEFAULT: OK
         //-- DEFAULT: OK
         case 200:
         default:
             // any other codes not listed above are not supported and will be interpreted as 200
             // nothing to do here ...
     }
     //end switch
     //--
     //== PREPARE THE OUTPUT
     //--
     if (stripos((string) $configs['js']['popup-override-mobiles'], '<' . SmartUtils::get_os_browser_ip('os') . '>') !== false) {
         $configs['js']['popup-mode'] = 'popup';
         // particular os settings for mobiles
     }
     //end if
     //--
     $rawpage = '';
     if (isset($appSettings['rawpage'])) {
         $rawpage = strtolower((string) $appSettings['rawpage']);
         if ((string) $rawpage == 'yes') {
             $rawpage = 'yes';
             // standardize the value
         }
         //end if
     }
     //end if
     if ((string) $rawpage != 'yes') {
         $rawpage = '';
     }
     //end if
     //--
     $rawmime = '';
     if (isset($appSettings['rawmime'])) {
         $rawmime = (string) $appSettings['rawmime'];
         if ((string) $rawmime != '') {
             $rawmime = SmartValidator::validate_mime_type($rawmime);
         }
         //end if
     }
     //end if else
     //--
     $rawdisp = '';
     if (isset($appSettings['rawdisp'])) {
         $rawdisp = (string) $appSettings['rawdisp'];
         if ((string) $rawdisp != '') {
             $rawdisp = SmartValidator::validate_mime_disposition($rawdisp);
         }
         //end if
     }
     //end if else
     //--
     $appData = (array) $appModule->PageViewGetVars();
     //--
     $appData['base-path'] = (string) $base_full_path;
     $appData['base-url'] = (string) $base_full_url;
     //--
     //== REDIRECTION HANDLER (this can be set only explicit from Controllers)
     //--
     if ((string) $appSettings['redirect-url'] != '') {
         // expects a valid URL
         //--
         $the_redirect_link = '<a href="' . Smart::escape_html((string) $appSettings['redirect-url']) . '">' . Smart::escape_html((string) $appSettings['redirect-url']) . '</a>';
         //--
         if (headers_sent()) {
             Smart::log_warning('Headers Already Sent before Redirection: [' . $appStatusCode . '] ; URL: ' . $appSettings['redirect-url']);
             self::Raise500Error('The app failed to Redirect to: ' . $the_redirect_link);
             return;
         }
         //end if
         switch ((int) $appStatusCode) {
             case 301:
                 http_response_code(301);
                 $the_redirect_text = 'Moved Permanently';
                 // permanent redirect for HTTP 1.0 / HTTP 1.1
                 break;
             case 302:
             default:
                 // any other code will be interpreted as 302 (the default redirection in PHP)
                 http_response_code(302);
                 $the_redirect_text = 'Found';
                 // temporary redirect for HTTP 1.0 / HTTP 1.1
                 break;
         }
         //end switch
         header('Location: ' . SmartFrameworkSecurity::FilterUnsafeString((string) $appSettings['redirect-url']));
         echo '<h1>' . Smart::escape_html($the_redirect_text) . '</h1>' . '<br>' . 'If the page redirection fails, click on the below link:' . '<br>' . $the_redirect_link;
         return;
         // break stop
     }
     //end if
     //--
     //== DOWNLOADS HANDLER (downloads can be set only explicit from Controllers)
     //--
     if ((string) $appSettings['download-packet'] != '' and (string) $appSettings['download-key'] != '') {
         // expects an encrypted data packet and a key
         $dwl_result = self::DownloadsHandler((string) $appSettings['download-packet'], (string) $appSettings['download-key']);
         if ((string) $dwl_result != '') {
             Smart::log_info('File Download - Client: ' . SmartUtils::get_visitor_signature(), (string) $dwl_result);
             // log result and mark it as finalized
         }
         //end if
         return;
         // break stop
     }
     //end if
     //--
     //== RAW OUTPUT FOR PAGES
     //--
     if ((string) $rawpage == 'yes') {
         //-- {{{SYNC-RESOURCES}}}
         if (function_exists('memory_get_peak_usage')) {
             $res_memory = @memory_get_peak_usage(false);
         } else {
             $res_memory = 'unknown';
         }
         //end if else
         $res_time = (double) (microtime(true) - (double) SMART_FRAMEWORK_RUNTIME_READY);
         //-- #END-SYNC
         if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
             //-- {{{SYNC-DEBUG-META-INFO}}}
             SmartFrameworkRegistry::setDebugMsg('stats', 'memory', $res_memory);
             // bytes
             SmartFrameworkRegistry::setDebugMsg('stats', 'time', $res_time);
             // seconds
             //-- #END-SYNC
             $the_debug_cookie = trim((string) $_COOKIE['SmartFramework__DebugAdmID']);
             SmartDebugProfiler::save_debug_info('adm', $the_debug_cookie, false);
         } else {
             $the_debug_cookie = '';
         }
         //end if
         //--
         if (headers_sent()) {
             Smart::raise_error('Middleware ERROR: Headers already sent', 'ERROR: Headers already sent !');
             return;
             // avoid serve raw pages with errors injections before headers
         }
         //end if
         //--
         if ((string) $rawmime != '') {
             header('Content-Type: ' . $rawmime);
         }
         //end if
         if ((string) $rawdisp != '') {
             header('Content-Disposition: ' . $rawdisp);
         }
         //end if
         header('Content-Length: ' . (0 + strlen((string) $appData['main'])));
         // must be strlen NOT SmartUnicode::str_len as it must get number of bytes not characters
         echo (string) $appData['main'];
         return;
         // break stop
         //--
     }
     //end if else
     //--
     //== DEFAULT OUTPUT
     //--
     if (isset($appSettings['template-path'])) {
         if ((string) $appSettings['template-path'] == '@') {
             // if template path is set to self (module)
             $the_template_path = '@';
             // this is a special setting
         } else {
             $the_template_path = Smart::safe_pathname(SmartFileSysUtils::add_dir_last_slash(trim((string) $appSettings['template-path'])));
         }
         //end if else
     } else {
         $the_template_path = Smart::safe_pathname(SmartFileSysUtils::add_dir_last_slash(trim((string) $configs['app']['admin-template-path'])));
         // use default template path
     }
     //end if else
     //--
     if (isset($appSettings['template-file'])) {
         $the_template_file = Smart::safe_filename(trim((string) $appSettings['template-file']));
     } else {
         $the_template_file = Smart::safe_filename(trim((string) $configs['app']['admin-template-file']));
         // use default template
     }
     //end if else
     //--
     if ((string) $the_template_path == '@') {
         $the_template_path = (string) $the_path_to_module . 'templates/';
         // must have the dir last slash as above
     } else {
         $the_template_path = (string) SMART_APP_TEMPLATES_DIR . $the_template_path;
         // finally normalize and set the complete template path
     }
     //end if else
     $the_template_file = (string) $the_template_file;
     // finally normalize
     //--
     if (!SmartFileSysUtils::check_file_or_dir_name($the_template_path)) {
         Smart::log_warning('Invalid Page Template Path: ' . $the_template_path);
         self::Raise500Error('Invalid Page Template Path. See the error log !');
         return;
     }
     //end if
     if (!is_dir($the_template_path)) {
         Smart::log_warning('Page Template Path does not Exists: ' . $the_template_path);
         self::Raise500Error('Page Template Path does not Exists. See the error log !');
         return;
     }
     //end if
     if (!SmartFileSysUtils::check_file_or_dir_name($the_template_path . $the_template_file)) {
         Smart::log_warning('Invalid Page Template File: ' . $the_template_path . $the_template_file);
         self::Raise500Error('Invalid Page Template File. See the error log !');
         return;
     }
     //end if
     if (!is_file($the_template_path . $the_template_file)) {
         Smart::log_warning('Page Template File does not Exists: ' . $the_template_path . $the_template_file);
         self::Raise500Error('Page Template File does not Exists. See the error log !');
         return;
     }
     //end if
     //--
     $the_template_content = trim(SmartMarkersTemplating::read_template_file($the_template_path . $the_template_file));
     if ((string) $the_template_content == '') {
         Smart::log_warning('Page Template File is Empty or cannot be read: ' . $the_template_path . $the_template_file);
         self::Raise500Error('Page Template File is Empty or cannot be read. See the error log !');
         return;
     }
     //end if
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         $the_template_content = str_ireplace('</head>', "\n" . SmartDebugProfiler::js_headers_debug('admin.php?smartframeworkservice=debug') . "\n" . '</head>', $the_template_content);
         $the_template_content = str_ireplace('</body>', "\n" . SmartDebugProfiler::div_main_debug() . "\n" . '</body>', $the_template_content);
     }
     //end if
     //--
     $appData['app-domain'] = (string) $configs['app']['admin-domain'];
     $appData['template-file'] = $the_template_path . $the_template_file;
     $appData['template-path'] = $the_template_path;
     $appData['js.settings'] = SmartComponents::js_inc_settings((string) $configs['js']['popup-mode'], true, (bool) SMART_APP_VISITOR_COOKIE);
     $appData['head-meta'] = (string) $appData['head-meta'];
     if ((string) $appData['head-meta'] == '') {
         $appData['head-meta'] = '<!-- Head Meta -->';
     }
     //end if
     $appData['title'] = (string) $appData['title'];
     $appData['main'] = (string) $appData['main'];
     $appData['lang'] = SmartTextTranslations::getLanguage();
     //--
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //--
         $the_debug_cookie = 'adm-' . Smart::uuid_10_seq() . '-' . Smart::uuid_10_num() . '-' . Smart::uuid_10_str();
         @setcookie('SmartFramework__DebugAdmID', (string) $the_debug_cookie, 0, '/');
         // debug token cookie is set just on main request
         //--
     }
     //end if
     //--
     echo SmartMarkersTemplating::render_mixed_template((string) $the_template_content, (array) $appData, (string) $appData['template-path'], 'no', 'no');
     //-- {{{SYNC-RESOURCES}}}
     if (function_exists('memory_get_peak_usage')) {
         $res_memory = @memory_get_peak_usage(false);
     } else {
         $res_memory = 'unknown';
     }
     //end if else
     $res_time = (double) (microtime(true) - (double) SMART_FRAMEWORK_RUNTIME_READY);
     //-- #END-SYNC
     if ((string) SMART_FRAMEWORK_DEBUG_MODE == 'yes') {
         //-- {{{SYNC-DEBUG-META-INFO}}}
         SmartFrameworkRegistry::setDebugMsg('stats', 'memory', $res_memory);
         // bytes
         SmartFrameworkRegistry::setDebugMsg('stats', 'time', $res_time);
         // seconds
         //-- #END-SYNC
         SmartDebugProfiler::save_debug_info('adm', $the_debug_cookie, true);
         //--
     }
     //end if else
     //--
     if (SMART_SOFTWARE_DISABLE_STATUS_POWERED !== true) {
         echo "\n" . '<!-- Smart.Framework スマート.フレームワーク :: ' . SMART_FRAMEWORK_RELEASE_TAGVERSION . ' / ' . SMART_FRAMEWORK_RELEASE_VERSION . ' @ ' . $the_midmark . ' :: ' . SMART_FRAMEWORK_RELEASE_URL . ' -->';
     }
     //end if
     echo "\n" . '<!-- Resources: [' . Smart::format_number_dec($res_time, 13, '.', '') . ' sec.] / [' . Smart::format_number_dec($res_memory, 0, '.', ' ') . ' by.]' . ' -->' . "\n";
     //--
 }
    public static function test_redisserver()
    {
        global $configs;
        //--
        if (SMART_FRAMEWORK_TESTUNIT_ALLOW_REDIS_TESTS !== true) {
            return SmartComponents::operation_notice('Test Unit for Redis Server is DISABLED ...');
        }
        //end if
        //--
        //--
        if (SmartPersistentCache::isActive()) {
            //--
            $redis_big_content = self::pack_test_archive();
            // CREATE THE Test Archive (time not counted)
            //--
            $redis_test_key = 'redis-test-key_' . Smart::uuid_10_num() . '-' . Smart::uuid_36() . '-' . Smart::uuid_45();
            $redis_test_value = array('unicode-test' => '"Unicode78źź:ăĂîÎâÂșȘțȚşŞţŢグッド', 'big-key-test' => (string) $redis_big_content, 'random-key' => Smart::uuid_10_str() . '.' . Smart::random_number(1000, 9999));
            $redis_test_checkum = sha1(implode("\n", (array) $redis_test_value));
            $redis_test_arch_content = SmartUtils::cache_variable_archive($redis_test_value);
            $redis_test_arch_checksum = sha1($redis_test_arch_content);
            //--
            $tests = array();
            $tests[] = '##### Redis / TESTS (Persistent Cache) with a Variable Key-Size of ' . SmartUtils::pretty_print_bytes(strlen($redis_test_arch_content), 2) . ' : #####';
            //--
            $err = '';
            //--
            if ((string) $err == '') {
                $tests[] = 'Building a Test Archive file for Redis Tests (time not counted)';
                // archive was previous created, only test here
                if ((string) $redis_big_content == '') {
                    $err = 'Failed to build the Test Archive file for the Redis Test (see the error log for more details) ...';
                }
                //end if
            }
            //end if
            //--
            $time = microtime(true);
            $tests[] = '++ START Counter ...';
            //--
            if ((string) $err == '') {
                $tests[] = 'Building the Cache Archive';
                if ((string) $redis_test_arch_content == '') {
                    $err = 'Failed to build the Cache Variable(s) Archive file for the Redis Test (see the error log for more details) ...';
                }
                //end if
            }
            //end if
            //--
            if ((string) $err == '') {
                $tests[] = 'Set a short Redis Key (auto-expire in 3 seconds)';
                $redis_set_key = SmartPersistentCache::setKey('redis-server-tests', $redis_test_key, (string) $redis_test_value['unicode-test'], 3);
                if ($redis_set_key !== true) {
                    $err = 'Redis SetKey (short) returned a non-true result: ' . "\n" . $redis_test_key;
                }
                //end if
                if ((string) $err == '') {
                    $tests[] = 'Wait 5 seconds for Redis Key to expire, then check again if exists (time not counted)';
                    sleep(5);
                    // wait the Redis Key to Expire
                    $time = (double) $time + 5;
                    // ignore those 5 seconds (waiting time) to fix counter
                    $tests[] = '-- FIX Counter (substract the 5 seconds, waiting time) ...';
                    if (SmartPersistentCache::keyExists('redis-server-tests', $redis_test_key)) {
                        $err = 'Redis (short) Key does still exists (but should be expired after 5 seconds) and is not: ' . "\n" . $redis_test_key;
                    }
                    //end if
                }
                //end if
            }
            //end if
            //--
            if ((string) $err == '') {
                $tests[] = 'Set a long Redis Key (will not expire)';
                $redis_set_key = SmartPersistentCache::setKey('redis-server-tests', $redis_test_key, $redis_test_arch_content);
                if ($redis_set_key !== true) {
                    $err = 'Redis SetKey (long) returned a non-true result: ' . "\n" . $redis_test_key;
                }
                //end if
            }
            //end if
            //--
            if ((string) $err == '') {
                $tests[] = 'Check if Redis Key exists (after set)';
                if (!SmartPersistentCache::keyExists('redis-server-tests', $redis_test_key)) {
                    $err = 'Redis Key does not exists: ' . "\n" . $redis_test_key;
                }
                //end if
            }
            //end if
            //--
            if ((string) $err == '') {
                $tests[] = 'Get Redis Key';
                $redis_cached_value = SmartUtils::cache_variable_unarchive(SmartPersistentCache::getKey('redis-server-tests', $redis_test_key));
                if (Smart::array_size($redis_cached_value) > 0) {
                    $tests[] = 'Check if Redis Key is valid (array-keys)';
                    if ((string) $redis_cached_value['unicode-test'] != '' and (string) $redis_cached_value['big-key-test'] != '') {
                        $tests[] = 'Check if Redis Key is valid (checksum)';
                        if ((string) sha1(implode("\n", (array) $redis_cached_value)) == (string) $redis_test_checkum) {
                            if ($redis_test_value === $redis_cached_value) {
                                $tests[] = 'Unset Redis Key';
                                $redis_unset_key = SmartPersistentCache::unsetKey('redis-server-tests', $redis_test_key);
                                if ($redis_unset_key === true) {
                                    $tests[] = 'Check if Redis Key exists (after unset)';
                                    if (SmartPersistentCache::keyExists('redis-server-tests', $redis_test_key)) {
                                        $err = 'Redis Key does exists (after unset) and should not: ' . "\n" . $redis_test_key;
                                    } else {
                                        // OK
                                    }
                                    //end if
                                } else {
                                    $err = 'Redis UnSetKey returned a non-true result: ' . "\n" . $redis_test_key;
                                }
                                //end if else
                            } else {
                                $err = 'Redis Cached Value is broken: comparing stored value with original value failed on key: ' . "\n" . $redis_test_key;
                            }
                            //end if else
                        } else {
                            $err = 'Redis Cached Value is broken: checksum failed on key: ' . "\n" . $redis_test_key;
                        }
                        //end if else
                    } else {
                        $err = 'Redis Cached Value is broken: array-key is missing after Cache-Variable-Unarchive on key: ' . "\n" . $redis_test_key;
                    }
                    //end if
                } else {
                    $err = 'Redis Cached Value is broken: non-array value was returned after Cache-Variable-Unarchive on key: ' . "\n" . $redis_test_key;
                }
                //end if
            }
            //end if
            //--
            $title = 'SmartFramework Redis Server Tests: DONE ...';
            //--
            $time = 'TOTAL TIME (Except building the test archive) was: ' . (microtime(true) - $time);
            // substract the 3 seconds waiting time for Redis Key to expire
            //--
            $end_tests = '##### END TESTS ... ' . $time . ' sec. #####';
            //--
            if ((string) $err == '') {
                $img_sign = 'lib/core/img/sign_info.png';
                $img_check = 'lib/core/img/q_completed.png';
                $text_main = Smart::escape_js('<span style="color:#83B953;">Good ... Perfect &nbsp;&nbsp;&nbsp; :: &nbsp;&nbsp;&nbsp; グッド ... パーフェクト</span>');
                $text_info = Smart::escape_js('<h2><span style="color:#83B953;">All</span> the SmartFramework Redis Server Operations <span style="color:#83B953;">Tests PASSED on PHP</span><hr></h2><span style="font-size:14px;">' . Smart::nl_2_br(Smart::escape_html(implode("\n" . '* ', $tests) . "\n" . $end_tests)) . '</span>');
            } else {
                $img_sign = 'lib/core/img/sign_error.png';
                $img_check = 'lib/core/img/q_warning.png';
                $text_main = Smart::escape_js('<span style="color:#FF5500;">An ERROR occured ... &nbsp;&nbsp;&nbsp; :: &nbsp;&nbsp;&nbsp; エラーが発生しました ...</span>');
                $text_info = Smart::escape_js('<h2><span style="color:#FF5500;">A test FAILED</span> when testing Redis Server Operations.<span style="color:#FF5500;"><hr>FAILED Test Details</span>:</h2><br><span style="font-size:14px;"><pre>' . Smart::escape_html($err) . '</pre></span>');
            }
            //end if else
            //--
        } else {
            //--
            $title = 'SmartFramework Redis Server Tests - Redis Server was NOT SET ...';
            //--
            $img_sign = 'lib/core/img/sign_info.png';
            $img_check = 'lib/core/img/q_warning.png';
            $text_main = Smart::escape_js('<span style="color:#778899;">No Redis Server Tests performed ...</span>');
            $text_info = '<h2>The current configuration have not set the Redis Server ...</h2>';
            //--
        }
        //end if
        //--
        //--
        $html = <<<HTML
<h1>{$title}</h1>
<script type="text/javascript">
\tSmartJS_BrowserUtils.alert_Dialog(
\t\t'<img src="{$img_sign}" align="right"><h1>{$text_main}</h1><hr><span style="color:#333333;"><img src="{$img_check}" align="right">{$text_info}<br>',
\t\t'',
\t\t'Redis Server Test Suite for SmartFramework: PHP',
\t\t'725',
\t\t'480'
\t);
</script>
HTML;
        //--
        //--
        return $html;
        //--
    }
    public static function Redirection_Monitor()
    {
        //--
        if (!defined('SMART_FRAMEWORK_VERSION')) {
            die('Smart Runtime // Redirection Monitor :: Requires SmartFramework to be loaded ...');
        }
        //end if
        //--
        if (self::$RedirectionMonitorStarted !== false) {
            return;
            // avoid run after it was used by runtime
        }
        //end if
        self::$RedirectionMonitorStarted = true;
        //--
        $url_redirect = '';
        //--
        $the_current_url = SmartUtils::get_server_current_url();
        $the_current_script = SmartUtils::get_server_current_script();
        //--
        if (SMART_SOFTWARE_FRONTEND_ENABLED === false and SMART_SOFTWARE_BACKEND_ENABLED === false) {
            // both frontend and backend are disabled
            die('FATAL ERROR: The FRONTEND but also the BACKEND of this application are DISABLED ! ...');
        }
        //end if
        if (SMART_SOFTWARE_FRONTEND_ENABLED === false and (string) $the_current_script == 'index.php') {
            $url_redirect = $the_current_url . 'admin.php';
        }
        //end if
        if (SMART_SOFTWARE_BACKEND_ENABLED === false and (string) $the_current_script == 'admin.php') {
            $url_redirect = $the_current_url . 'index.php';
        }
        //end if
        //--
        if ((string) $url_redirect == '' and isset($_SERVER['PATH_INFO'])) {
            //--
            if (strlen($_SERVER['PATH_INFO']) > 0) {
                //--
                if ((string) $the_current_script == 'index.php') {
                    $the_current_script = '';
                }
                //end if
                $url_redirect = $the_current_url . $the_current_script . '?' . $_SERVER['PATH_INFO'];
                //--
            }
            //end if
            //--
        }
        //end if
        //--
        $gopage = '
		<!DOCTYPE html>
		<!-- template :: RUNTIME REDIRECTION / PATH SUFFIX -->
		<html>
			<head>
				<meta charset="UTF-8">
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
				<meta http-equiv="refresh" content="3;URL=' . Smart::escape_html($url_redirect) . '">
			</head>
			<body>
				<h1>Redirecting to a valid URL ... wait ...</h1><br>
				<script type="text/javascript">setTimeout("self.location=\'' . Smart::escape_js($url_redirect) . '\'",1500);</script>
			</body>
		</html>
	';
        //--
        if (strlen($url_redirect) > 0) {
            @header('Location: ' . $url_redirect);
            die($gopage);
        }
        //end if
        //--
    }
示例#17
0
 /**
  * Get A UNIQUE (SAFE) ID for DB Tables / Schema
  *
  * @param ENUM 		$y_mode 					:: mode: uid10str | uid10num | uid10seq | uid36 | uid45
  * @param STRING 	$y_field_name 				:: the field name
  * @param STRING 	$y_table_name 				:: the table name
  * @param STRING 	$y_schema 					:: the schema
  * @param RESOURCE 	$y_connection 				:: pgsql connection
  * @return STRING 								:: the generated Unique ID
  *
  */
 public static function new_safe_id($y_mode, $y_id_field, $y_table_name, $y_schema = 'public', $y_connection = 'DEFAULT')
 {
     //==
     $y_connection = self::check_connection($y_connection, 'NEW-SAFE-ID');
     //==
     //--
     if (!self::validate_table_and_fields_names($y_id_field)) {
         self::error($y_connection, 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Field Name', $y_id_field . ' / [Schema=' . $y_schema . ';Table=' . $y_table_name . ']');
         return '';
     }
     //end if
     if (!self::validate_table_and_fields_names($y_table_name)) {
         self::error($y_connection, 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Table Name', $y_table_name);
         return '';
     }
     //end if
     if (!self::validate_table_and_fields_names($y_schema)) {
         self::error($y_connection, 'NEW-SAFE-ID', 'Get New Safe ID', 'Invalid Schema Name', $y_schema);
         return '';
     }
     //end if
     //--
     //--
     $use_safe_id_record = true;
     if (defined('SMART_SOFTWARE_DB_DISABLE_SAFE_IDS')) {
         if (SMART_SOFTWARE_DB_DISABLE_SAFE_IDS === true) {
             $use_safe_id_record = false;
         }
         //end if
     }
     //end if
     //--
     if ($use_safe_id_record === true) {
         //--
         if (self::check_if_table_exists('_safe_id_records', 'smart_runtime', $y_connection) !== 1) {
             if (self::check_if_schema_exists('smart_runtime', $y_connection) !== 1) {
                 self::write_data('CREATE SCHEMA "smart_runtime"', 'Initialize SafeID Schema', $y_connection);
             }
             //end if
             self::write_data((string) self::schema_safe_id_records_table(), 'Initialize SafeID Table', $y_connection);
         }
         //end if
         //--
         if ((int) Smart::random_number(0, 99) == 1) {
             // 1% chance to run it for cleanup records older than 24 hours
             self::write_data('DELETE FROM "smart_runtime"."_safe_id_records" WHERE ("date_time" < \'' . self::escape_str(date('Y-m-d H:i:s', @strtotime('-1 day')), 'no', $y_connection) . '\')', 'Safe ID Records Cleanup (OLDs)', $y_connection);
             // cleanup olds
         }
         //end if
         //--
     }
     //end if
     //--
     $tmp_result = 'NO-ID-INIT';
     //init (must be not empty)
     $counter = 0;
     $id_is_ok = false;
     //--
     while ($id_is_ok !== true) {
         // while we cannot find an unused ID
         //--
         $counter += 1;
         //--
         if ($counter > 7500) {
             // loop to max 7500
             self::error($y_connection, 'NEW-SAFE-ID', 'Get New Safe ID', 'Could Not Assign a Unique ID', '(timeout / 7500) ... try again !');
             return '';
         }
         //end if
         //--
         if ($counter % 500 == 0) {
             sleep(1);
         }
         //end if
         //--
         $new_id = 'NO-ID-ALGO';
         switch ((string) $y_mode) {
             case 'uid45':
                 $new_id = (string) Smart::uuid_45(SMART_FRAMEWORK_NETSERVER_ID . SmartUtils::get_server_current_url());
                 // will use the server ID.Host as Prefix to ensure it is true unique in a cluster
                 break;
             case 'uid36':
                 $new_id = (string) Smart::uuid_36(SMART_FRAMEWORK_NETSERVER_ID . SmartUtils::get_server_current_url());
                 // will use the server ID.Host as Prefix to ensure it is true unique in a cluster
                 break;
             case 'uid10seq':
                 if ($use_safe_id_record === true) {
                     // sequences are not safe without a second registry allocation table as the chance to generate the same ID in the same time moment is just 1 in 999
                     $new_id = (string) Smart::uuid_10_seq();
                 } else {
                     $new_id = (string) Smart::uuid_10_str();
                 }
                 //end if else
                 break;
             case 'uid10num':
                 $new_id = (string) Smart::uuid_10_num();
                 break;
             case 'uid10str':
             default:
                 $new_id = (string) Smart::uuid_10_str();
         }
         //end switch
         //--
         $result_arr = array();
         $chk_uniqueness = 'SELECT ' . self::escape_identifier($y_id_field, $y_connection) . ' FROM ' . self::escape_identifier($y_schema, $y_connection) . '.' . self::escape_identifier($y_table_name, $y_connection) . ' WHERE (' . self::escape_identifier($y_id_field, $y_connection) . ' = ' . self::escape_literal($new_id, 'no', $y_connection) . ') LIMIT 1 OFFSET 0';
         $result_arr = self::read_data($chk_uniqueness, 'Safe Check if NEW ID Exists into Table', $y_connection);
         $tmp_result = (string) trim((string) $result_arr[0]);
         $result_arr = array();
         //--
         if ((string) $tmp_result == '') {
             //--
             if ($use_safe_id_record === true) {
                 // with safety check against safe ID records table
                 //-- reserve this ID to bse sure will not be assigned to another instance
                 $uniqueness_mark = (string) $y_schema . '.' . $y_table_name . ':' . $y_id_field;
                 $write_res = self::write_igdata('INSERT INTO "smart_runtime"."_safe_id_records" ("id", "table_space", "date_time") ( SELECT \'' . self::escape_str($new_id, 'no', $y_connection) . '\', \'' . self::escape_str($uniqueness_mark, 'no', $y_connection) . '\', \'' . self::escape_str(date('Y-m-d H:i:s'), 'no', $y_connection) . '\' WHERE (NOT EXISTS ( SELECT 1 FROM "smart_runtime"."_safe_id_records" WHERE (("id" = \'' . self::escape_str($new_id, 'no', $y_connection) . '\') AND ("table_space" = \'' . self::escape_str($uniqueness_mark, 'no', $y_connection) . '\')) LIMIT 1 OFFSET 0 ) AND NOT EXISTS (' . $chk_uniqueness . ') ) )', 'Safe Record of NEW ID of Table into Zone Control', $y_connection);
                 //--
                 if ($write_res[1] === 1) {
                     $id_is_ok = true;
                 }
                 //end if
                 //--
             } else {
                 // default (not safe in very high load environments ...
                 //--
                 $id_is_ok = true;
                 //--
             }
             //end if else
             //--
         }
         //end if
         //--
     }
     //end while
     //--
     //--
     return (string) $new_id;
     //--
 }