function anaString($value = '') { # code... global $arrayNum; global $arrayABC; global $arrayabc; global $arrayBoolen; $Result = ''; for ($i = 0; $i < strlen($value); $i++) { # code... switch ($value[$i]) { case 'U': # code... $Result .= $arrayABC[array_rand($arrayABC)]; break; case 'L': # code... $Result .= $arrayabc[array_rand($arrayabc)]; break; case 'N': # code... $Result .= $arrayNum[array_rand($arrayNum)]; break; case 'C': # code... $Result .= unicode_decode("\\u" . dechex(rand(176, 215) << 8 | rand(161, 254))); break; case 'R': # code... $rand = mt_rand(0, 3); switch ($rand) { case 0: # code... $Result .= $arrayABC[array_rand($arrayABC)]; break; case 1: # code... $Result .= $arrayabc[array_rand($arrayabc)]; break; case 2: # code... $Result .= $arrayNum[array_rand($arrayNum)]; break; case 3: # code... $Result .= unicode_decode("\\u" . dechex(rand(176, 215) << 8 | rand(161, 254))); break; } // $Result .= unicode_decode("\\u" . dechex(rand(176, 215) << 8 | rand(161, 254))); break; default: # code... $Result .= $value[$i]; break; } } return iconv("GBK", "UTF-8", $Result); }
/** * Load binary unicode sequence * * @return void */ protected function _loadBinUnicode() { // read byte length $n = $this->_read(4); if (self::$_isLittleEndian === false) { $n = strrev($n); } list(, $n) = unpack('l', $n); $data = $this->_read($n); if (self::$_isPhp6) { $data = unicode_decode($data, 'UTF-8'); } $this->_stack[] = $data; }
function run_test($php, $file, $env) { global $log_format, $info_params, $ini_overwrites, $cwd, $PHP_FAILED_TESTS; global $pass_options, $DETAILED, $IN_REDIRECT, $test_cnt, $test_idx; global $leak_check, $temp_source, $temp_target, $cfg, $environment; global $no_clean; global $valgrind_version; $temp_filenames = null; $org_file = $file; if (isset($env['TEST_PHP_CGI_EXECUTABLE'])) { $php_cgi = $env['TEST_PHP_CGI_EXECUTABLE']; } if (is_array($file)) { $file = $file[0]; } if ($DETAILED) { echo "\n=================\nTEST {$file}\n"; } // Load the sections of the test file. $section_text = array('TEST' => ''); $fp = fopen($file, "rb") or error("Cannot open test file: {$file}"); $borked = false; $bork_info = ''; if (!feof($fp)) { $line = fgets($fp); if ($line === false) { $bork_info = "cannot read test"; $borked = true; } } else { $bork_info = "empty test [{$file}]"; $borked = true; } if (!$borked && strncmp('--TEST--', $line, 8)) { $bork_info = "tests must start with --TEST-- [{$file}]"; $borked = true; } $section = 'TEST'; $secfile = false; $secdone = false; while (!feof($fp)) { $line = fgets($fp); if ($line === false) { break; } // Match the beginning of a section. if (preg_match('/^--([_A-Z]+)--/', $line, $r)) { $section = $r[1]; settype($section, STRING_TYPE); if (isset($section_text[$section])) { $bork_info = "duplicated {$section} section"; $borked = true; } $section_text[$section] = binary_section($section) ? '' : ''; $secfile = $section == 'FILE' || $section == 'FILEEOF' || $section == 'FILE_EXTERNAL'; $secdone = false; continue; } if (!binary_section($section)) { $line = unicode_decode($line, "utf-8"); if ($line == false) { $bork_info = "cannot read test"; $borked = true; break; } } // Add to the section text. if (!$secdone) { $section_text[$section] .= $line; } // End of actual test? if ($secfile && preg_match('/^===DONE===\\s*$/', $line)) { $secdone = true; } } // the redirect section allows a set of tests to be reused outside of // a given test dir if (!$borked) { if (@count($section_text['REDIRECTTEST']) == 1) { if ($IN_REDIRECT) { $borked = true; $bork_info = "Can't redirect a test from within a redirected test"; } else { $borked = false; } } else { if (@count($section_text['FILE']) + @count($section_text['FILEEOF']) + @count($section_text['FILE_EXTERNAL']) != 1) { $bork_info = "missing section --FILE--"; $borked = true; } if (@count($section_text['FILEEOF']) == 1) { $section_text['FILE'] = preg_replace("/[\r\n]+\$/", '', $section_text['FILEEOF']); unset($section_text['FILEEOF']); } if (@count($section_text['FILE_EXTERNAL']) == 1) { // don't allow tests to retrieve files from anywhere but this subdirectory $section_text['FILE_EXTERNAL'] = dirname($file) . '/' . trim(str_replace('..', '', $section_text['FILE_EXTERNAL'])); if (file_exists($section_text['FILE_EXTERNAL'])) { $section_text['FILE'] = file_get_contents($section_text['FILE_EXTERNAL'], FILE_BINARY); unset($section_text['FILE_EXTERNAL']); } else { $bork_info = "could not load --FILE_EXTERNAL-- " . dirname($file) . '/' . trim($section_text['FILE_EXTERNAL']); $borked = true; } } if (@count($section_text['EXPECT']) + @count($section_text['EXPECTF']) + @count($section_text['EXPECTREGEX']) != 1) { $bork_info = "missing section --EXPECT--, --EXPECTF-- or --EXPECTREGEX--"; $borked = true; } } } fclose($fp); $shortname = str_replace($cwd . '/', '', $file); $tested_file = $shortname; if ($borked) { show_result("BORK", $bork_info, $tested_file); $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]"); return 'BORKED'; } $tested = trim($section_text['TEST']); /* For GET/POST tests, check if cgi sapi is available and if it is, use it. */ if (!empty($section_text['GET']) || !empty($section_text['POST']) || !empty($section_text['POST_RAW']) || !empty($section_text['COOKIE']) || !empty($section_text['EXPECTHEADERS'])) { if (isset($php_cgi)) { $old_php = $php; $php = $php_cgi . ' -C '; } else { if (!strncasecmp(PHP_OS, "win", 3) && file_exists(dirname($php) . "/php-cgi.exe")) { $old_php = $php; $php = realpath(dirname($php) . "/php-cgi.exe") . ' -C '; } else { if (file_exists(dirname($php) . "/../../sapi/cgi/php-cgi")) { $old_php = $php; $php = realpath(dirname($php) . "/../../sapi/cgi/php-cgi") . ' -C '; } else { if (file_exists("./sapi/cgi/php-cgi")) { $old_php = $php; $php = realpath("./sapi/cgi/php-cgi") . ' -C '; } else { show_result('SKIP', $tested, $tested_file, "reason: CGI not available"); return 'SKIPPED'; } } } } } show_test($test_idx, $shortname); if (is_array($IN_REDIRECT)) { $temp_dir = $test_dir = $IN_REDIRECT['dir']; } else { $temp_dir = $test_dir = realpath(dirname($file)); } if ($temp_source && $temp_target) { $temp_dir = str_replace($temp_source, $temp_target, $temp_dir); } $main_file_name = basename($file, 'phpt'); $diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'diff'; $log_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'log'; $exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'exp'; $output_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'out'; $memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'mem'; $sh_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'sh'; $temp_file = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'php'; $test_file = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'php'; $temp_skipif = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'skip.php'; $test_skipif = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'skip.php'; $temp_clean = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'clean.php'; $test_clean = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'clean.php'; $tmp_post = $temp_dir . DIRECTORY_SEPARATOR . uniqid('/phpt.'); $tmp_relative_file = str_replace(__DIR__ . DIRECTORY_SEPARATOR, '', $test_file) . 't'; if ($temp_source && $temp_target) { $temp_skipif .= 's'; $temp_file .= 's'; $temp_clean .= 's'; $copy_file = $temp_dir . DIRECTORY_SEPARATOR . basename(is_array($file) ? $file[1] : $file) . '.phps'; if (!is_dir(dirname($copy_file))) { mkdir(dirname($copy_file), 0777, true) or error("Cannot create output directory - " . dirname($copy_file)); } if (isset($section_text['FILE'])) { save_text($copy_file, $section_text['FILE']); } $temp_filenames = array('file' => $copy_file, 'diff' => $diff_filename, 'log' => $log_filename, 'exp' => $exp_filename, 'out' => $output_filename, 'mem' => $memcheck_filename, 'sh' => $sh_filename, 'php' => $temp_file, 'skip' => $temp_skipif, 'clean' => $temp_clean); } if (is_array($IN_REDIRECT)) { $tested = $IN_REDIRECT['prefix'] . ' ' . trim($section_text['TEST']); $tested_file = $tmp_relative_file; } // unlink old test results @unlink($diff_filename); @unlink($log_filename); @unlink($exp_filename); @unlink($output_filename); @unlink($memcheck_filename); @unlink($sh_filename); @unlink($temp_file); @unlink($test_file); @unlink($temp_skipif); @unlink($test_skipif); @unlink($tmp_post); @unlink($temp_clean); @unlink($test_clean); // Reset environment from any previous test. $env['REDIRECT_STATUS'] = ''; $env['QUERY_STRING'] = ''; $env['PATH_TRANSLATED'] = ''; $env['SCRIPT_FILENAME'] = ''; $env['REQUEST_METHOD'] = ''; $env['CONTENT_TYPE'] = ''; $env['CONTENT_LENGTH'] = ''; $env['TZ'] = ''; if (!empty($section_text['ENV'])) { foreach (explode("\n", trim($section_text['ENV'])) as $e) { $e = explode('=', trim($e), 2); if (!empty($e[0]) && isset($e[1])) { $env[$e[0]] = $e[1]; } } } // Default ini settings $ini_settings = array(); // additional ini overwrites //$ini_overwrites[] = 'setting=value'; settings2array($ini_overwrites, $ini_settings); // Any special ini settings // these may overwrite the test defaults... if (array_key_exists('INI', $section_text)) { if (strpos($section_text['INI'], '{PWD}') !== false) { $section_text['INI'] = str_replace('{PWD}', dirname($file), $section_text['INI']); } settings2array(preg_split("/[\n\r]+/", $section_text['INI']), $ini_settings); } settings2params($ini_settings); // Check if test should be skipped. $info = ''; $warn = false; if (array_key_exists('SKIPIF', $section_text)) { if (trim($section_text['SKIPIF'])) { show_file_block('skip', $section_text['SKIPIF']); save_text($test_skipif, $section_text['SKIPIF'], $temp_skipif); $extra = substr(PHP_OS, 0, 3) !== "WIN" ? "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;" : ""; if ($leak_check) { $env['USE_ZEND_ALLOC'] = '0'; } else { $env['USE_ZEND_ALLOC'] = '1'; } $output = system_with_timeout("{$extra} {$php} {$pass_options} -q {$ini_settings} -d display_errors=0 {$test_skipif}", $env); if (!$cfg['keep']['skip']) { @unlink($test_skipif); } if (!strncasecmp('skip', ltrim($output), 4)) { if (preg_match('/^\\s*skip\\s*(.+)\\s*/i', $output, $m)) { show_result('SKIP', $tested, $tested_file, "reason: {$m['1']}", $temp_filenames); } else { show_result('SKIP', $tested, $tested_file, '', $temp_filenames); } if (isset($old_php)) { $php = $old_php; } if (!$cfg['keep']['skip']) { @unlink($test_skipif); } return 'SKIPPED'; } if (!strncasecmp('info', ltrim($output), 4)) { if (preg_match('/^\\s*info\\s*(.+)\\s*/i', $output, $m)) { $info = " (info: {$m['1']})"; } } if (!strncasecmp('warn', ltrim($output), 4)) { if (preg_match('/^\\s*warn\\s*(.+)\\s*/i', $output, $m)) { $warn = true; /* only if there is a reason */ $info = " (warn: {$m['1']})"; } } } } if (@count($section_text['REDIRECTTEST']) == 1) { $test_files = array(); $IN_REDIRECT = eval($section_text['REDIRECTTEST']); $IN_REDIRECT['via'] = "via [{$shortname}]\n\t"; $IN_REDIRECT['dir'] = realpath(dirname($file)); $IN_REDIRECT['prefix'] = trim($section_text['TEST']); if (count($IN_REDIRECT['TESTS']) == 1) { if (is_array($org_file)) { $test_files[] = $org_file[1]; } else { $GLOBALS['test_files'] = $test_files; find_files($IN_REDIRECT['TESTS']); foreach ($GLOBALS['test_files'] as $f) { $test_files[] = array($f, $file); } } $test_cnt += @count($test_files) - 1; $test_idx--; show_redirect_start($IN_REDIRECT['TESTS'], $tested, $tested_file); // set up environment $redirenv = array_merge($environment, $IN_REDIRECT['ENV']); $redirenv['REDIR_TEST_DIR'] = realpath($IN_REDIRECT['TESTS']) . DIRECTORY_SEPARATOR; usort($test_files, "test_sort"); run_all_tests($test_files, $redirenv, $tested); show_redirect_ends($IN_REDIRECT['TESTS'], $tested, $tested_file); // a redirected test never fails $IN_REDIRECT = false; return 'REDIR'; } else { $bork_info = "Redirect info must contain exactly one TEST string to be used as redirect directory."; show_result("BORK", $bork_info, '', $temp_filenames); $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]"); } } if (is_array($org_file) || @count($section_text['REDIRECTTEST']) == 1) { if (is_array($org_file)) { $file = $org_file[0]; } $bork_info = "Redirected test did not contain redirection info"; show_result("BORK", $bork_info, '', $temp_filenames); $PHP_FAILED_TESTS['BORKED'][] = array('name' => $file, 'test_name' => '', 'output' => '', 'diff' => '', 'info' => "{$bork_info} [{$file}]"); return 'BORKED'; } // We've satisfied the preconditions - run the test! show_file_block('php', $section_text['FILE'], 'TEST'); save_text($test_file, $section_text['FILE'], $temp_file); if (array_key_exists('GET', $section_text)) { $query_string = trim($section_text['GET']); } else { $query_string = ''; } $env['REDIRECT_STATUS'] = '1'; $env['QUERY_STRING'] = $query_string; $env['PATH_TRANSLATED'] = $test_file; $env['SCRIPT_FILENAME'] = $test_file; if (array_key_exists('COOKIE', $section_text)) { $env['HTTP_COOKIE'] = trim($section_text['COOKIE']); } else { $env['HTTP_COOKIE'] = ''; } $args = isset($section_text['ARGS']) ? ' -- ' . $section_text['ARGS'] : ''; if (array_key_exists('POST_RAW', $section_text) && !empty($section_text['POST_RAW'])) { $post = trim($section_text['POST_RAW']); $raw_lines = explode("\n", $post); $request = ''; $started = false; foreach ($raw_lines as $line) { if (empty($env['CONTENT_TYPE']) && preg_match('/^Content-Type:(.*)/i', $line, $res)) { $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1])); continue; } if ($started) { $request .= "\n"; } $started = true; $request .= $line; } $env['CONTENT_LENGTH'] = strlen($request); $env['REQUEST_METHOD'] = 'POST'; if (empty($request)) { return 'BORKED'; } save_text($tmp_post, $request); $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\" 2>&1 < {$tmp_post}"; } else { if (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) { $post = trim($section_text['POST']); if (array_key_exists('GZIP_POST', $section_text) && function_exists('gzencode')) { $post = gzencode($post, 9, FORCE_GZIP); $env['HTTP_CONTENT_ENCODING'] = 'gzip'; } else { if (array_key_exists('DEFLATE_POST', $section_text) && function_exists('gzcompress')) { $post = gzcompress($post, 9); $env['HTTP_CONTENT_ENCODING'] = 'deflate'; } } save_text($tmp_post, $post); $content_length = strlen($post); $env['REQUEST_METHOD'] = 'POST'; $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; $env['CONTENT_LENGTH'] = $content_length; $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\" 2>&1 < {$tmp_post}"; } else { $env['REQUEST_METHOD'] = 'GET'; $env['CONTENT_TYPE'] = ''; $env['CONTENT_LENGTH'] = ''; $cmd = "{$php} {$pass_options} {$ini_settings} -f \"{$test_file}\" {$args} 2>&1"; } } if ($leak_check) { $env['USE_ZEND_ALLOC'] = '0'; if ($valgrind_version >= 330) { /* valgrind 3.3.0+ doesn't have --log-file-exactly option */ $cmd = "valgrind -q --tool=memcheck --trace-children=yes --log-file={$memcheck_filename} {$cmd}"; } else { $cmd = "valgrind -q --tool=memcheck --trace-children=yes --log-file-exactly={$memcheck_filename} {$cmd}"; } } else { $env['USE_ZEND_ALLOC'] = '1'; } if ($DETAILED) { echo "\nCONTENT_LENGTH = " . $env['CONTENT_LENGTH'] . "\nCONTENT_TYPE = " . $env['CONTENT_TYPE'] . "\nPATH_TRANSLATED = " . $env['PATH_TRANSLATED'] . "\nQUERY_STRING = " . $env['QUERY_STRING'] . "\nREDIRECT_STATUS = " . $env['REDIRECT_STATUS'] . "\nREQUEST_METHOD = " . $env['REQUEST_METHOD'] . "\nSCRIPT_FILENAME = " . $env['SCRIPT_FILENAME'] . "\nHTTP_COOKIE = " . $env['HTTP_COOKIE'] . "\nCOMMAND {$cmd}\n"; } $out = (string) system_with_timeout($cmd, $env, isset($section_text['STDIN']) ? $section_text['STDIN'] : null); if (array_key_exists('CLEAN', $section_text) && (!$no_clean || $cfg['keep']['clean'])) { if (trim($section_text['CLEAN'])) { show_file_block('clean', $section_text['CLEAN']); save_text($test_clean, trim($section_text['CLEAN']), $temp_clean); if (!$no_clean) { $clean_params = array(); settings2array($ini_overwrites, $clean_params); settings2params($clean_params); $extra = substr(PHP_OS, 0, 3) !== "WIN" ? "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;" : ""; system_with_timeout("{$extra} {$php} {$pass_options} -q {$clean_params} {$test_clean}", $env); } if (!$cfg['keep']['clean']) { @unlink($test_clean); } } } @unlink($tmp_post); $leaked = false; $passed = false; if ($leak_check) { // leak check $leaked = filesize($memcheck_filename) > 0; if (!$leaked) { @unlink($memcheck_filename); } } // Does the output match what is expected? $output = preg_replace("/\r\n/", "\n", trim($out)); /* when using CGI, strip the headers from the output */ $headers = ""; if (isset($old_php) && preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $out, $match)) { $output = trim($match[2]); $rh = preg_split("/[\n\r]+/", $match[1]); $headers = array(); foreach ($rh as $line) { if (strpos($line, ':') !== false) { $line = explode(':', $line, 2); $headers[trim($line[0])] = trim($line[1]); } } } $failed_headers = false; if (isset($section_text['EXPECTHEADERS'])) { $want = array(); $wanted_headers = array(); $lines = preg_split("/[\n\r]+/", (string) $section_text['EXPECTHEADERS']); foreach ($lines as $line) { if (strpos($line, ':') !== false) { $line = explode(':', $line, 2); $want[trim($line[0])] = trim($line[1]); $wanted_headers[] = trim($line[0]) . ': ' . trim($line[1]); } } $org_headers = $headers; $headers = array(); $output_headers = array(); foreach ($want as $k => $v) { if (isset($org_headers[$k])) { $headers = $org_headers[$k]; $output_headers[] = $k . ': ' . $org_headers[$k]; } if (!isset($org_headers[$k]) || $org_headers[$k] != $v) { $failed_headers = true; } } ksort($wanted_headers); $wanted_headers = join("\n", $wanted_headers); ksort($output_headers); $output_headers = join("\n", $output_headers); } show_file_block('out', $output); if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) { if (isset($section_text['EXPECTF'])) { $wanted = trim($section_text['EXPECTF']); } else { $wanted = trim($section_text['EXPECTREGEX']); } show_file_block('exp', $wanted); $wanted_re = preg_replace('/\\r\\n/', "\n", $wanted); if (isset($section_text['EXPECTF'])) { // do preg_quote, but miss out any %r delimited sections $temp = ""; $r = "%r"; $startOffset = 0; $length = strlen($wanted_re); while ($startOffset < $length) { $start = strpos($wanted_re, $r, $startOffset); if ($start !== false) { // we have found a start tag $end = strpos($wanted_re, $r, $start + 2); if ($end === false) { // unbalanced tag, ignore it. $end = $start = $length; } } else { // no more %r sections $start = $end = $length; } // quote a non re portion of the string $temp = $temp . preg_quote(substr($wanted_re, $startOffset, $start - $startOffset), '/'); // add the re unquoted. if ($end > $start) { $temp = $temp . '(' . substr($wanted_re, $start + 2, $end - $start - 2) . ')'; } $startOffset = $end + 2; } $wanted_re = $temp; $wanted_re = str_replace(array('%binary_string_optional%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? 'string' : 'binary string', $wanted_re); $wanted_re = str_replace(array('%unicode_string_optional%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? 'string' : 'Unicode string', $wanted_re); $wanted_re = str_replace(array('%unicode\\|string%', '%string\\|unicode%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? 'string' : 'unicode', $wanted_re); $wanted_re = str_replace(array('%u\\|b%', '%b\\|u%'), version_compare(PHP_VERSION, '6.0.0-dev') == -1 ? '' : 'u', $wanted_re); // Stick to basics $wanted_re = str_replace('%e', '\\' . DIRECTORY_SEPARATOR, $wanted_re); $wanted_re = str_replace('%s', '[^\\r\\n]+', $wanted_re); $wanted_re = str_replace('%S', '[^\\r\\n]*', $wanted_re); $wanted_re = str_replace('%a', '.+', $wanted_re); $wanted_re = str_replace('%A', '.*', $wanted_re); $wanted_re = str_replace('%w', '\\s*', $wanted_re); $wanted_re = str_replace('%i', '[+-]?\\d+', $wanted_re); $wanted_re = str_replace('%d', '\\d+', $wanted_re); $wanted_re = str_replace('%x', '[0-9a-fA-F]+', $wanted_re); $wanted_re = str_replace('%f', '[+-]?\\.?\\d+\\.?\\d*(?:[Ee][+-]?\\d+)?', $wanted_re); $wanted_re = str_replace('%c', '.', $wanted_re); // %f allows two points "-.0.0" but that is the best *simple* expression } /* DEBUG YOUR REGEX HERE var_dump($wanted_re); print(str_repeat('=', 80) . "\n"); var_dump($output); */ if (preg_match("/^{$wanted_re}\$/s", $output)) { $passed = true; if (!$cfg['keep']['php']) { @unlink($test_file); } if (isset($old_php)) { $php = $old_php; } if (!$leaked && !$failed_headers) { if (isset($section_text['XFAIL'])) { $warn = true; $info = " (warn: XFAIL section but test passes)"; } else { show_result("PASS", $tested, $tested_file, '', $temp_filenames); return 'PASSED'; } } } } else { $wanted = (string) trim($section_text['EXPECT']); $wanted = preg_replace('/\\r\\n/', "\n", $wanted); show_file_block('exp', $wanted); // compare and leave on success if (!strcmp($output, $wanted)) { $passed = true; if (!$cfg['keep']['php']) { @unlink($test_file); } if (isset($old_php)) { $php = $old_php; } if (!$leaked && !$failed_headers) { if (isset($section_text['XFAIL'])) { $warn = true; $info = " (warn: XFAIL section but test passes)"; } else { show_result("PASS", $tested, $tested_file, '', $temp_filenames); return 'PASSED'; } } } $wanted_re = null; } // Test failed so we need to report details. if ($failed_headers) { $passed = false; $wanted = (string) $wanted_headers . "\n--HEADERS--\n" . (string) $wanted; $output = (string) $output_headers . "\n--HEADERS--\n" . (string) $output; if (isset($wanted_re)) { $wanted_re = preg_quote($wanted_headers . "\n--HEADERS--\n", '/') . $wanted_re; } } if ($leaked) { $restype[] = 'LEAK'; } if ($warn) { $restype[] = 'WARN'; } if (!$passed) { if (isset($section_text['XFAIL'])) { $restype[] = 'XFAIL'; $info = ' XFAIL REASON: ' . $section_text['XFAIL']; } else { $restype[] = 'FAIL'; } } if (!$passed) { // write .exp if (strpos($log_format, 'E') !== false && file_put_contents($exp_filename, (string) $wanted, FILE_BINARY) === false) { error("Cannot create expected test output - {$exp_filename}"); } // write .out if (strpos($log_format, 'O') !== false && file_put_contents($output_filename, (string) $output, FILE_BINARY) === false) { error("Cannot create test output - {$output_filename}"); } // write .diff $diff = generate_diff($wanted, $wanted_re, $output); if (is_array($IN_REDIRECT)) { $diff = "# original source file: {$shortname}\n" . $diff; } show_file_block('diff', $diff); if (strpos($log_format, 'D') !== false && file_put_contents($diff_filename, (string) $diff, FILE_BINARY) === false) { error("Cannot create test diff - {$diff_filename}"); } // write .sh if (strpos($log_format, 'S') !== false && file_put_contents($sh_filename, "#!/bin/sh\n\n{$cmd}\n", FILE_BINARY) === false) { error("Cannot create test shell script - {$sh_filename}"); } chmod($sh_filename, 0755); // write .log if (strpos($log_format, 'L') !== false && file_put_contents($log_filename, "\n---- EXPECTED OUTPUT\n{$wanted}\n---- ACTUAL OUTPUT\n{$output}\n---- FAILED\n", FILE_BINARY) === false) { error("Cannot create test log - {$log_filename}"); error_report($file, $log_filename, $tested); } } show_result(implode('&', $restype), $tested, $tested_file, $info, $temp_filenames); foreach ($restype as $type) { $PHP_FAILED_TESTS[$type . 'ED'][] = array('name' => $file, 'test_name' => (is_array($IN_REDIRECT) ? $IN_REDIRECT['via'] : '') . $tested . " [{$tested_file}]", 'output' => $output_filename, 'diff' => $diff_filename, 'info' => $info); } if (isset($old_php)) { $php = $old_php; } return $restype[0] . 'ED'; }
$unistr = ''; for ($i = 0, $len = count($arrstr); $i < $len; $i++) { $dec = hexdec(bin2hex($arrstr[$i])); $unistr .= $prefix . $dec . $postfix; } return $unistr; } header('Content-type: image/png'); $char = '字'; $color = array('r' => 0, 'g' => 0, 'b' => 0); $url = $_SERVER['HTTP_HOST']; //$file = fopen("./test.txt","w"); //fwrite($file,$url); //fclose($file); //$url = "5b57.af10ea.icon.sukima.me"; if (preg_match("/^[0-9a-fA-F]{4}\\.[0-9a-fA-F]{6}\\.icon\\.sukima\\.me\$/", $url)) { $url = substr($url, 0, 11); $res = explode(".", $url); $char = unicode_decode("\\u" . hexdec($res[0]), 'UTF-8', "\\u", ''); $color = hex2rgb($res[1]); } else { $char = '字'; } $im = imagecreate(16, 16); $white = ImageColorAllocate($im, 255, 255, 255); $brush = ImageColorAllocate($im, $color['r'], $color['g'], $color['b']); imagecolortransparent($im, $white); $fnt = "./font.ttf"; imagettftext($im, 12, 0, 0, 14, $brush, $fnt, $char); ImagePng($im); ImageDestroy($im);
$zupanija = $_REQUEST['zupanija']; } else { $zupanija = null; } if ($zupanija != null) { $upit = "SELECT * FROM lovista WHERE zupanija='{$zupanija}'"; $rezultat = $baza->selectDB($upit); //$nesto=$rezultat->fetch_array(); if ($rezultat->num_rows != 0) { $data = array(); while ($nesto = $rezultat->fetch_array()) { $data[] = array("Id" => $nesto['idlovista'], "Naziv" => $nesto['naziv'], "Zupanija" => $nesto['zupanija']); } } else { $ispis = "Error"; } } else { $upit = "SELECT * FROM lovista"; $rezultat = $baza->selectDB($upit); //$nesto=$rezultat->fetch_array(); if ($rezultat->num_rows != 0) { $data = array(); while ($nesto = $rezultat->fetch_array()) { $data[] = array("Id" => $nesto['idlovista'], "Naziv" => $nesto['naziv'], "Zupanija" => $nesto['zupanija']); } } else { $ispis = "Error"; } } echo unicode_decode(json_encode(array("list" => $data)), ENT_SUBSTITUTE);
/** * curl() 函数用来进行远程 http 请求 * @param array $option 设置请求的参数,可最多包含下面 (array)$default 中所有的键值对 * @param boolean $iconvUtf8 尝试自动将文件流编码转换为 utf8, 默认位 true * @return string 返回请求结果,结果是字符串 */ function curl($option = array(), $iconvUtf8 = true) { /* 定义默认的参数 */ $default = array('url' => '', 'method' => 'get', 'data' => '', 'cookie' => '', 'referer' => '', 'userAgent' => '', 'requestHeaders' => array(), 'responseHeaders' => true, 'sessionCookie' => false, 'noBody' => false, 'followLocation' => false, 'maxRedirs' => 2, 'autoReferer' => true, 'sslVerify' => false, 'proxy' => '', 'clientIp' => '', 'timeout' => 30, 'username' => '', 'password' => '', 'charset' => ''); $option = array_merge($default, $option); $ch = curl_init(); if (strtolower($option['method']) == 'post') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $option['data']); } else { if ($option['data']) { $option['url'] .= (strpos('?', $option['url']) ? '&' : '?') . (is_array($option['data']) ? http_build_query($option['data']) : $option['data']); } } if (is_assoc($option['requestHeaders'])) { foreach ($option['requestHeaders'] as $key => $value) { array_push($option['requestHeaders'], "{$key}: {$value}"); unset($option['requestHeaders'][$key]); } } curl_setopt($ch, CURLOPT_URL, $option['url']); curl_setopt($ch, CURLOPT_COOKIESESSION, $option['sessionCookie']); curl_setopt($ch, CURLOPT_HEADER, $option['responseHeaders']); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_NOBODY, $option['noBody']); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $option['followLocation']); curl_setopt($ch, CURLOPT_MAXREDIRS, $option['maxRedirs']); curl_setopt($ch, CURLOPT_AUTOREFERER, $option['autoReferer']); curl_setopt($ch, CURLOPT_TIMEOUT, $option['timeout']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); if ($option['sslVerify']) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 2); } else { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } if ($option['cookie']) { curl_setopt($ch, CURLOPT_COOKIE, $option['cookie']); } if ($option['referer']) { curl_setopt($ch, CURLOPT_REFERER, $option['referer']); } if ($option['userAgent']) { curl_setopt($ch, CURLOPT_USERAGENT, $option['userAgent']); } if ($option['proxy']) { curl_setopt($ch, CURLOPT_PROXY, $option['proxy']); } if ($option['clientIp']) { array_push($option['requestHeaders'], 'CLIENT-IP: ' . $option['clientIp'], 'X-FORWARDED-FOR: ' . $option['clientIp']); } if (!empty($option['requestHeaders'])) { curl_setopt($ch, CURLOPT_HTTPHEADER, $option['requestHeaders']); } if ($option['username']) { curl_setopt($ch, CURLOPT_USERPWD, $option['username'] . ':' . $option['password']); } $data = curl_exec($ch); if (curl_errno($ch)) { return curl_error($ch); } curl_info(curl_getinfo($ch)); curl_close($ch); if (!$option['charset'] && $iconvUtf8) { if (preg_match('/text\\/html;[\\s]*charset=(.*)/i', curl_info('content_type'), $matches)) { $option['charset'] = $matches[1]; } else { if (preg_match('/<meta[\\s]*.*charset=["]*(.*)["][\\s]*.*>/i', $data, $matches)) { $option['charset'] = $matches[1]; } else { if (preg_match('/<\\?xml[\\s]*.*encoding=["]*(.*)["][\\s]*.*>/i', $data, $matches)) { $option['charset'] = $matches[1]; } } } } if ($option['charset']) { $data = iconv($option['charset'], 'UTF-8', $data); } curl_info('response_headers', parse_headers(substr($data, 0, curl_info('header_size')))); curl_info('request_headers', parse_headers(curl_info('request_header'))); curl_info('request_header', null); return unicode_decode(substr($data, curl_info('header_size'))); }
function get_message($num_iid, $focus = false) { global $_G; if ($_G[setting][get_message] || $focus) { // $url = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%2243151340941%22%7D'; $url = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data='; $url .= urlencode_utf8('{"item_num_id":"' . $num_iid . '"}'); $message = fetch($url); if (!$message) { return ''; } if (TAE) { $content = unicode_decode($content, 'UTF-8', ""); } $data2 = json_decode($message, 1); if (!is_array($data2)) { L('详情获取失败:' . $data2[ret][0] . ',url=>' . $url); return ''; } elseif ($data2[ret][0] != 'SUCCESS::接口调用成功') { L('详情获取失败:' . $data2[ret][0] . ',url=>' . $url); return false; } elseif (is_array($data2[data][images])) { $message = ''; foreach ($data2[data][images] as $k => $v) { $message .= '<p class="goods_imgs"><img src="' . $v . '" ></p>'; } return $message; } } return ''; }
$name .= $c; } else { $name .= $str; } } } return $name; } for ($x = 0; $x < $pass_num; $x++) { $content = ''; $str = ""; for ($i = 0; $i < $pass_length; $i++) { // echo "&#x" . dechex(rand(176, 215) << 8 | rand(161, 254)) . ";"; $str .= "\\u" . dechex(rand(176, 215) << 8 | rand(161, 254)); } $content .= unicode_decode($str); // echo '<p style="'.$resultStyle.'">' . $content . '</p>'; echo '<p style="' . $resultStyle . '">' . $content . '</p>'; } } else { if ($pass_struct != null) { // var_dump($pass_struct); for ($x = 0; $x < $pass_num; $x++) { $resultString = ''; # code... // $pass_struct_each = $value; for ($x = 0; $x < $pass_num; $x++) { $resultString = ''; foreach (str_split($pass_struct) as $key => $value) { # code... switch ($value) {
<?php header("Content-type: text/html; charset=utf-8"); $num = '_' . base_convert('http://inankai.com', 16, 10); $num2 = base_convert('http://in2732.om', 10, 16); $_2732 = unicode_decode("\\u6211\\u662f\\u7231"); $aac = unicode_decode("\\u7684"); echo unicode_encode($name); echo ${$num} . "inankai" . ${$num2}; function unicode_encode($name) { $name = iconv('UTF-8', 'UCS-2', $name); $len = strlen($name); $str = ''; for ($i = 0; $i < $len - 1; $i = $i + 2) { $c = $name[$i]; $c2 = $name[$i + 1]; if (ord($c) > 0) { // 两个字节的文字 $str .= '\\u' . base_convert(ord($c), 10, 16) . base_convert(ord($c2), 10, 16); } else { $str .= $c2; } } return $str; } function unicode_decode($name) { $pattern = '/([\\w]+)|(\\\\u([\\w]{4}))/i'; preg_match_all($pattern, $name, $matches); if (!empty($matches)) {
function filter_gen($str, $ext = 0) { $ext = !empty($ext) ? 1 : 0; $re_arr = array(' ', '【', '】', '★', '?', '☆', '(', ')', '(', ')', '.', ':', ':', '≪', '≫', '。', ',', '"', '&', '『', '』', '「', '」', 'φ', '\'', '・', '●', '◆', '*', '+', '#', '%', '$', '^', '|', '_', '[', ']', '〔', '〕', 'ü', '-', ' '); $str = str_replace($re_arr, '', $str); $str = utf8_unicode($str); $str = unicode_decode($str); //hwz:两次转换用于过滤其他无法识别的字符! if ($ext) { $str = filter_blankstr($str); } return $str; }
function do_import_resume($info, $uid) { global $db, $_CFG, $timestamp; if ($info && $uid) { require_once QISHI_ROOT_PATH . '/include/fun_import.php'; if (empty($info['basicinfo'])) { return false; } $info['basicinfo']['fullname'] = unicode_decode($info['basicinfo']['fullname']); $setsqlarr = iconv_to_gbk($info['basicinfo']); $setsqlarr['uid'] = intval($uid); $setsqlarr['title'] = "未命名简历"; $setsqlarr['display_name'] = 1; $setsqlarr['sex'] = $setsqlarr['sex_cn'] == '男' ? 1 : 2; $experience = match_experience($setsqlarr['experience_cn']); $setsqlarr['experience_cn'] = $experience[1]; $setsqlarr['experience'] = $experience[0]; $setsqlarr['email_notify'] = 1; $setsqlarr['marriage'] = $setsqlarr['marriage_cn'] == '已婚' ? 2 : 1; $intentionjobsarr = explode('、', $setsqlarr['intention_jobs']); $match_jobs_id_arr = array(); $match_jobs_cn_arr = array(); foreach ($intentionjobsarr as $key => $value) { $match_jobs_arr = match_jobs_category($value); if ($match_jobs_arr) { $match_jobs_id_arr[] = $match_jobs_arr['topclass'] . '.' . $match_jobs_arr['category'] . '.' . $match_jobs_arr['subclass']; $match_jobs_cn_arr[] = $match_jobs_arr['category_cn']; } } $setsqlarr['intention_jobs'] = !empty($match_jobs_cn_arr) ? implode(',', $match_jobs_cn_arr) : ''; $intention_jobs_id = !empty($match_jobs_id_arr) ? implode(',', $match_jobs_id_arr) : ''; $tradearr = explode('、', $setsqlarr['trade_cn']); $match_trade_id_arr = array(); foreach ($tradearr as $key => $value) { $match_trade_arr = match_trade($value); if ($match_trade_arr) { $match_trade_id_arr[] = $match_jobs_arr['id']; } } $intentiontrade = !empty($match_trade_id_arr) ? implode(',', $match_trade_id_arr) : ''; $districtarr = explode('、', $setsqlarr['district_cn']); $match_district_id_arr = array(); foreach ($districtarr as $key => $value) { $match_district_arr = match_district($value); if ($match_district_arr) { $match_district_id_arr[] = $match_district_arr['district'] . '.' . $match_district_arr['sdistrict']; } } $intentiondistrict = !empty($match_district_id_arr) ? implode(',', $match_district_id_arr) : ''; $match_current_arr = match_current($setsqlarr['current_cn']); if ($match_current_arr) { $setsqlarr['current'] = $match_current_arr['id']; $setsqlarr['current_cn'] = $match_current_arr['cn']; } $match_nature_arr = match_nature($setsqlarr['nature_cn']); if ($match_nature_arr) { $setsqlarr['nature'] = $match_nature_arr['id']; $setsqlarr['nature_cn'] = $match_nature_arr['cn']; } $match_wage_arr = match_wage($setsqlarr['wage_cn']); if ($match_wage_arr) { $setsqlarr['wage'] = $match_wage_arr['id']; $setsqlarr['wage_cn'] = $match_wage_arr['cn']; } $setsqlarr['refreshtime'] = $timestamp; $setsqlarr['audit'] = intval($_CFG['audit_resume']); $setsqlarr['resume_from_pc'] = 1; $setsqlarr['addtime'] = $timestamp; $pid = $db->inserttable(table('resume'), $setsqlarr, 1); if ($pid) { $searchtab['id'] = $pid; $searchtab['uid'] = $uid; $db->inserttable(table('resume_search_key'), $searchtab); $db->inserttable(table('resume_search_rtime'), $searchtab); add_resume_jobs($pid, $uid, $intention_jobs_id) ? "" : showmsg('保存失败!', 0); add_resume_district($pid, $uid, $intentiondistrict) ? "" : showmsg('保存失败!', 0); add_resume_trade($pid, $uid, $intentiontrade) ? "" : showmsg('保存失败!', 0); if (!get_userprofile($uid)) { $infoarr['realname'] = $setsqlarr['fullname']; $infoarr['sex'] = $setsqlarr['sex']; $infoarr['sex_cn'] = $setsqlarr['sex_cn']; $infoarr['birthday'] = $setsqlarr['birthdate']; $infoarr['residence'] = $setsqlarr['residence']; $infoarr['experience'] = $setsqlarr['experience']; $infoarr['experience_cn'] = $setsqlarr['experience_cn']; $infoarr['householdaddress'] = $setsqlarr['householdaddress']; $infoarr['marriage'] = $setsqlarr['marriage']; $infoarr['marriage_cn'] = $setsqlarr['marriage_cn']; $infoarr['phone'] = $setsqlarr['telephone']; $infoarr['email'] = $setsqlarr['email']; $infoarr['uid'] = intval($uid); $db->inserttable(table('members_info'), $infoarr); } //教育经历 if (!empty($info['eduinfo'])) { foreach ($info['eduinfo'] as $key => $value) { $eduarrsql = iconv_to_gbk($value); $eduarrsql['pid'] = $pid; $eduarrsql['uid'] = $uid; $match_education_arr = match_education($eduarrsql['education_cn']); if ($match_education_arr) { $eduarrsql['education'] = $match_education_arr['id']; $eduarrsql['education_cn'] = $match_education_arr['cn']; } $db->inserttable(table("resume_education"), $eduarrsql); } } //工作经历 if (!empty($info['workinfo'])) { foreach ($info['workinfo'] as $key => $value) { $workarrsql = iconv_to_gbk($value); $workarrsql['pid'] = $pid; $workarrsql['uid'] = $uid; $db->inserttable(table("resume_work"), $workarrsql); } } //培训经历 if (!empty($info['traininginfo'])) { foreach ($info['traininginfo'] as $key => $value) { $trainingarrsql = iconv_to_gbk($value); $trainingarrsql['pid'] = $pid; $trainingarrsql['uid'] = $uid; $db->inserttable(table("resume_training"), $trainingarrsql); } } //语言能力 if (!empty($info['languageinfo'])) { foreach ($info['languageinfo'] as $key => $value) { $languagearrsql = iconv_to_gbk($value); $languagearrsql['pid'] = $pid; $languagearrsql['uid'] = $uid; $match_language_arr = match_language($languagearrsql['language_cn']); if ($match_language_arr) { $languagearrsql['language'] = $match_language_arr['id']; $languagearrsql['language_cn'] = $match_language_arr['cn']; } $match_language_level_arr = match_language_level($languagearrsql['level_cn']); if ($match_language_level_arr) { $languagearrsql['level'] = $match_language_level_arr['id']; $languagearrsql['level_cn'] = $match_language_level_arr['cn']; } $db->inserttable(table("resume_language"), $languagearrsql); } } //证书 if (!empty($info['credentinfo'])) { foreach ($info['credentinfo'] as $key => $value) { $credentarrsql = iconv_to_gbk($value); $credentarrsql['pid'] = $pid; $credentarrsql['uid'] = $uid; $db->inserttable(table("resume_credent"), $credentarrsql); } } check_resume($uid, $pid); write_memberslog($uid, 2, 1101, $_SESSION['username'], "导入了简历"); return true; } else { return false; } } else { return false; } }
function JLMS_postChatMsg($course_id, $option) { global $JLMS_DB, $my, $JLMS_CONFIG; $JLMS_ACL =& JLMSFactory::getACL(); if ($JLMS_ACL->CheckPermissions('chat', 'view')) { $XML_data = ''; $group_id = intval(mosGetParam($_REQUEST, 'group_id', 0)); $do_chat = false; if ($JLMS_ACL->CheckPermissions('chat', 'manage')) { if ($group_id) { if ($JLMS_CONFIG->get('use_global_groups', 1)) { $query = "SELECT group_chat FROM #__lms_usergroups WHERE course_id = 0 AND id = {$group_id}"; $JLMS_DB->SetQuery($query); if ($JLMS_DB->LoadResult()) { $do_chat = true; } } else { $query = "SELECT group_chat FROM #__lms_usergroups WHERE course_id = {$course_id} AND id = {$group_id}"; $JLMS_DB->SetQuery($query); if ($JLMS_DB->LoadResult()) { $do_chat = true; } } } else { $do_chat = true; } } else { if ($group_id) { if ($JLMS_CONFIG->get('use_global_groups', 1)) { $query = "SELECT group_chat FROM #__lms_users_in_global_groups AS uigg, #__lms_usergroups AS ug WHERE uigg.user_id = {$my->id} AND uigg.group_id = {$group_id} AND ug.id = uigg.group_id"; $JLMS_DB->setQuery($query); if ($JLMS_DB->LoadResult()) { $do_chat = true; } } else { $query = "SELECT b.group_chat FROM #__lms_users_in_groups as a, #__lms_usergroups as b" . "\n WHERE a.course_id = {$course_id} AND a.group_id = {$group_id} AND a.user_id = '" . $my->id . "' AND a.group_id = b.id AND b.id = {$group_id} AND b.course_id = {$course_id}"; $JLMS_DB->SetQuery($query); if ($JLMS_DB->LoadResult()) { $do_chat = true; } } } else { $do_chat = true; } } if ($do_chat) { $query = "SELECT time_enter FROM #__lms_chat_users" . "\n WHERE user_id = '" . $my->id . "' AND course_id = '" . $course_id . "' AND group_id = '" . $group_id . "'"; $JLMS_DB->SetQuery($query); $time_online = $JLMS_DB->LoadResult(); $user_msg = ''; /*print_r($_REQUEST);*/ if (isset($_REQUEST['message'])) { $user_msg = trim(strval($_REQUEST['message'])); $user_msg = get_magic_quotes_gpc() ? stripslashes($user_msg) : $user_msg; } if ($time_online && ($user_msg || $user_msg === '0' || $user_msg === 0)) { //query (Update time) $query = "UPDATE #__lms_chat_users SET time_post = '" . gmdate('Y-m-d H:i:s') . "'" . "\n WHERE user_id = '" . $my->id . "' AND course_id = '" . $course_id . "' AND group_id = '" . $group_id . "'"; $JLMS_DB->SetQuery($query); $JLMS_DB->query(); //query (post Message) $user_msg = $JLMS_DB->GetEscaped(unicode_decode($user_msg)); /* print_r($user_msg); die; */ $query = "INSERT INTO #__lms_chat_history (course_id, group_id, user_id, recv_id, user_message, mes_time)" . "\n VALUES ('" . $course_id . "', '" . $group_id . "', '" . $my->id . "', '0', '" . $user_msg . "', '" . gmdate('Y-m-d H:i:s') . "')"; $JLMS_DB->SetQuery($query); $JLMS_DB->query(); JLMS_getChatXML($course_id, $group_id, $option, true); } } } JLMS_getChatXML($course_id, $group_id, $option, false); }
/** * Convert some data from one encoding to the internal encoding. * * @param string Data to convert. * @param ?string Charset to convert from (NULL: that read by the last http_download_file call). * @param ?string Charset to convert to (NULL: current encoding). * @return string Converted data. */ function convert_to_internal_encoding($data, $input_charset = NULL, $internal_charset = NULL) { global $VALID_ENCODING; convert_data_encodings(); // In case it hasn't run yet. We need $VALID_ENCODING to be set. if (is_null($input_charset)) { $input_charset = $GLOBALS['HTTP_CHARSET']; } if ($input_charset === '' || is_null($input_charset)) { return $data; } if (is_null($internal_charset)) { $internal_charset = get_charset(); } if ((version_compare(phpversion(), '4.3.0') >= 0 || strtolower($internal_charset) == 'iso-8859-1') && strtolower($input_charset) == 'utf-8' && will_be_unicode_neutered($data) && in_array(strtolower($internal_charset), array('iso-8859-1', 'iso-8859-15', 'koi8-r', 'big5', 'gb2312', 'big5-hkscs', 'shift_jis', 'euc-jp'))) { $test = entity_utf8_decode($data, $internal_charset); if ($test !== false) { $data = $test; } } elseif (function_exists('unicode_decode') && $internal_charset != 'utf-8' && $input_charset == 'utf-8' && $VALID_ENCODING) { $test = @unicode_decode($data, $input_charset); if ($test !== false) { $data = $test; } } elseif (function_exists('unicode_encode') && $internal_charset == 'utf-8' && $input_charset != 'utf-8' && $VALID_ENCODING) { $test = @unicode_encode($data, $input_charset); if ($test !== false) { $data = $test; } } elseif (function_exists('iconv') && $VALID_ENCODING && get_value('disable_iconv') !== '1') { $test = @iconv($input_charset, $internal_charset . '//TRANSLIT', $data); if ($test !== false) { $data = $test; } } elseif (function_exists('mb_convert_encoding') && $VALID_ENCODING && get_value('disable_mbstring') !== '1') { if (function_exists('mb_list_encodings')) { $good_encoding = in_array(strtolower($input_charset), array_map('strtolower', mb_list_encodings())); } else { $good_encoding = true; } if ($good_encoding) { $test = @mb_convert_encoding($data, $internal_charset, $input_charset); if ($test !== false) { $data = $test; } } } elseif (strtolower($input_charset) == 'utf-8' && strtolower(substr($internal_charset, 0, 3)) != 'utf') { $test = utf8_decode($data); // Imperfect as it assumes ISO-8859-1, but it's our last resort. if ($test !== false) { $data = $test; } } elseif (strtolower($internal_charset) == 'utf-8' && strtolower(substr($input_charset, 0, 3)) != 'utf') { $test = utf8_encode($data); // Imperfect as it assumes ISO-8859-1, but it's our last resort. if ($test !== false) { $data = $test; } } return $data; }
function unicode_decode($unistr, $encoding = 'UTF-8', $prefix = '&#', $postfix = ';') { if (!$unistr) { return $unistr; } if (is_array($unistr)) { foreach ($unistr as $k => $v) { $unistr[$k] = unicode_decode($v, $encoding, $prefix, $postfix); } } else { if (is_string($unistr)) { $arruni = explode($prefix, $unistr); $unistr = ''; for ($i = 1, $len = count($arruni); $i < $len; $i++) { if (strlen($postfix) > 0) { $arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix)); } $temp = intval($arruni[$i]); $unistr .= $temp < 256 ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256); } $unistr = iconv('UCS-2', $encoding, $unistr); } } return $unistr; }
/** * convert a string for SEF url's **/ function pmxsef_encode($string) { global $modSettings, $sourcedir, $PortaMxSEF, $txt; static $utf8_db = array(); $string = trim($string); if (empty($string)) { return ''; } // make all strings to ISO-8859-1 or UTF-8 and if not, convert to UTF-8 $char_set = empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set']; if ($char_set != 'ISO-8859-1' || $char_set != 'UTF-8') { if (function_exists('iconv')) { $string = iconv($char_set, 'UTF-8//IGNORE', $string); } elseif (function_exists('mb_convert_encoding')) { $string = mb_convert_encoding($string, 'UTF8', $char_set); } elseif (function_exists('unicode_decode')) { $string = unicode_decode($string, $char_set); } } $character = 0; $result = ''; $length = strlen($string); $i = 0; while ($i < $length) { $charInt = ord($string[$i++]); // normal Ascii character if (($charInt & 0x80) == 0) { $character = $charInt; } elseif (($charInt & 0xe0) == 0xc0) { $temp1 = ord($string[$i++]); if (($temp1 & 0xc0) != 0x80) { $character = 63; } else { $character = ($charInt & 0x1f) << 6 | $temp1 & 0x3f; } } elseif (($charInt & 0xf0) == 0xe0) { $temp1 = ord($string[$i++]); $temp2 = ord($string[$i++]); if (($temp1 & 0xc0) != 0x80 || ($temp2 & 0xc0) != 0x80) { $character = 63; } else { $character = ($charInt & 0xf) << 12 | ($temp1 & 0x3f) << 6 | $temp2 & 0x3f; } } elseif (($charInt & 0xf8) == 0xf0) { $temp1 = ord($string[$i++]); $temp2 = ord($string[$i++]); $temp3 = ord($string[$i++]); if (($temp1 & 0xc0) != 0x80 || ($temp2 & 0xc0) != 0x80 || ($temp3 & 0xc0) != 0x80) { $character = 63; } else { $character = ($charInt & 0x7) << 18 | ($temp1 & 0x3f) << 12 | ($temp2 & 0x3f) << 6 | $temp3 & 0x3f; } } else { $character = 63; } // get the codepage for this character. $charBank = $character >> 8; if (!isset($utf8_db[$charBank])) { // Load up the codepage if it's not already in memory $cpFile = $sourcedir . $PortaMxSEF['codepages'] . sprintf('%02x', $charBank) . '.php'; if (file_exists($cpFile)) { include_once $cpFile; } else { $utf8_db[$charBank] = array(); } } $finalChar = $character & 255; $result .= isset($utf8_db[$charBank][$finalChar]) ? $utf8_db[$charBank][$finalChar] : '?'; } $result = trim(str_replace($PortaMxSEF['stripchars'], '', $result), "\t\r\n\v ."); $result = urlencode($result); $result = str_replace(array('%2F', '%2C', '%27', '%60'), '', $result); $result = str_replace(array($PortaMxSEF['spacechar'], '.'), '+', $result); $result = preg_replace('~(\\+)+~', $PortaMxSEF['spacechar'], $result); return !empty($PortaMxSEF['lowercase']) ? strtolower($result) : $result; }