乱码的PHP代码需要一些修复

时间:2011-04-11 15:49:38

标签: php decode phpbb

我正在为我的phpBB3讨论板添加修改,其中一个步骤是添加一行代码到/ functions.php

因此,当我复制该文件并在wordpad中打开时,我看到它看起来全是乱码。部分内容如下:

<?php /** * * @package phpBB3 * @version $Id$ * @copyright (c) 2005 phpBB Group * @license http://opensource.org/licenses/gpl-license.php GNU Public License * */  /** * @ignore */ if (!defined('IN_PHPBB')) {     exit; }  // Common global functions  /** * set_var * * Set variable, used by {@link request_var the request_var function} * * @access private */ function set_var(&$result, $var, $type, $multibyte = false) {  settype($var, $type);   $result = $var;     if ($type == 'string')  {       $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $result), ENT_COMPAT, 'UTF-8'));          if (!empty($result))        {           // Make sure multibyte characters are wellformed            if ($multibyte)             {               if (!preg_match('/^./u', $result))              {                   $result = '';               }           }           else            {               // no multibyte, allow only ASCII (0-127)               $result = preg_replace('/[\x80-\xFF]/', '?', $result);          }       }       $result = (STRIP) ? stripslashes($result) : $result;    } }  /** * request_var * * Used to get passed variable */ function request_var($var_name, $default, $multibyte = false, $cookie = false) {  if (!$cookie && isset($_COOKIE[$var_name]))     {       if (!isset($_GET[$var_name]) && !isset($_POST[$var_name]))      {           return (is_array($default)) ? array() : $default;       }       $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name];     }   $super_global = ($cookie) ? '_COOKIE' : '_REQUEST';     if (!isset($GLOBALS[$super_global][$var_name]) || is_array($GLOBALS[$super_global][$var_name]) != is_array($default))   {       return (is_array($default)) ? array() : $default;   }   $var = $GLOBALS[$super_global][$var_name];  if (!is_array($default))    {       $type = gettype($default);  }   else    {       list($key_type, $type) = each($default);        $type = gettype($type);         $key_type = gettype($key_type);         if ($type == 'array')       {           reset($default);            $default = current($default);           list($sub_key_type, $sub_type) = each($default);            $sub_type = gettype($sub_type);             $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type;            $sub_key_type = gettype($sub_key_type);         }   }   if (is_array($var))     {       $_var = $var;       $var = array();         foreach ($_var as $k => $v)         {           set_var($k, $k, $key_type);             if ($type == 'array' && is_array($v))           {               foreach ($v as $_k => $_v)              {                   if (is_array($_v))                  {                       $_v = null;                     }                   set_var($_k, $_k, $sub_key_type, $multibyte);                   set_var($var[$k][$_k], $_v, $sub_type, $multibyte);                 }           }           else            {               if ($type == 'array' || is_array($v))               {                   $v = null;              }               set_var($var[$k], $v, $type, $multibyte);           }       }   }   else    {       set_var($var, $var, $type, $multibyte);     }   return $var; }  /** * Set config value. Creates missing config entry. */ function set_config($config_name, $config_value, $is_dynamic = false) {    global $db, $cache, $config;    $sql = 'UPDATE ' . CONFIG_TABLE . "         SET config_value = '" . $db->sql_escape($config_value) . "'         WHERE config_name = '" . $db->sql_escape($config_name) . "'";   $db->sql_query($sql);   if (!$db->sql_affectedrows() && !isset($config[$config_name]))  {       $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array(          'config_name'   => $config_name,            'config_value'  => $config_value,           'is_dynamic'    => ($is_dynamic) ? 1 : 0));         $db->sql_query($sql);   }   $config[$config_name] = $config_value;      if (!$is_dynamic)   {       $cache->destroy('config');  } }  /** * Set dynamic config value with arithmetic operation. */ function set_config_count($config_name, $increment, $is_dynamic = false) {    global $db, $cache;     switch ($db->sql_layer)     {       case 'firebird':        case 'postgres':            $sql_update = 'CAST(CAST(config_value as DECIMAL(255, 0)) + ' . (int) $increment . ' as VARCHAR(255))';         break;          // MySQL, SQlite, mssql, mssql_odbc, oracle         default:            $sql_update = 'config_value + ' . (int) $increment;         break;  }   $db->sql_query('UPDATE ' . CONFIG_TABLE . ' SET config_value = ' . $sql_update . " WHERE config_name = '" . $db->sql_escape($config_name) . "'");   if (!$is_dynamic)   {       $cache->destroy('config');  } }  /** * Generates an alphanumeric random string of given length * * @return string */ function gen_rand_string($num_chars = 8) {     // [a, z] + [0, 9] = 36     return substr(strtoupper(base_convert(unique_id(), 16, 36)), 0, $num_chars); }  /** * Generates a user-friendly alphanumeric random string of given length * We remove 0 and O so users cannot confuse those in passwords etc. * * @return string */ function gen_rand_string_friendly($num_chars = 8) {    $rand_str = unique_id();    // Remove Z and Y from the base_convert(), replace 0 with Z and O with Y    // [a, z] + [0, 9] - {z, y} = [a, z] + [0, 9] - {0, o} = 34     $rand_str = str_replace(array('0', 'O'), array('Z', 'Y'), strtoupper(base_convert($rand_str, 16, 34)));     return substr($rand_str, 0, $num_chars); }  /** * Return unique id * @param string $extra additional entropy */ function unique_id($extra = 'c') {  static $dss_seeded = false;     global $config;     $val = $config['rand_seed'] . microtime();  $val = md5($val);   $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra);   if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10)))   {       set_config('rand_seed', $config['rand_seed'], true);        set_config('rand_seed_last_update', time(), true);      $dss_seeded = true;     }   return substr($val, 4, 16); }  /** * Return formatted string for filesizes * * @param int   $value          filesize in bytes * @param bool $string_only    true if language string should be returned * @param array   $allowed_units  only allow these units (data array indexes) * * @return mixed                   data array if $string_only is false * @author bantu */ function get_formatted_filesize($value, $string_only = true, $allowed_units = false) {   global $user;   $available_units = array(       'gb' => array(          'min'       => 1073741824, // pow(2, 30)            'index'     => 3,           'si_unit'   => 'GB',            'iec_unit'  => 'GIB',       ),      'mb' => array(          'min'       => 1048576, // pow(2, 20)           'index'     => 2,           'si_unit'   => 'MB',            'iec_unit'  => 'MIB',       ),      'kb' => array(          'min'       => 1024, // pow(2, 10)          'index'     => 1,           'si_unit'   => 'KB',            'iec_unit'  => 'KIB',       ),      'b' => array(           'min'       => 0,           'index'     => 0,           'si_unit'   => 'BYTES', // Language index           'iec_unit'  => 'BYTES',  // Language index      ),  );      foreach ($available_units as $si_identifier => $unit_info)  {       if (!empty($allowed_units) && $si_identifier != 'b' && !in_array($si_identifier, $allowed_units))       {           continue;       }       if ($value >= $unit_info['min'])        {           $unit_info['si_identifier'] = $si_identifier;           break;      }   }   unset($available_units);    for ($i = 0; $i < $unit_info['index']; $i++)    {       $value /= 1024;     }   $value = round($value, 2);      // Lookup units in language dictionary  $unit_info['si_unit'] = (isset($user->lang[$unit_info['si_unit']])) ? $user->lang[$unit_info['si_unit']] : $unit_info['si_unit'];   $unit_info['iec_unit'] = (isset($user->lang[$unit_info['iec_unit']])) ? $user->lang[$unit_info['iec_unit']] : $unit_info['iec_unit'];   // Default to IEC   $unit_info['unit'] = $unit_info['iec_unit'];    if (!$string_only)  {       $unit_info['value'] = $value;       return $unit_info;  }   return $value  . ' ' . $unit_info['unit']; }  /** * Determine whether we are approaching the maximum execution time. Should be called once * at the beginning of the script in which it's used. * @return   bool    Either true if the maximum execution time is nearly reached, or false *                 if some time is still left. */ function still_on_time($extra_time = 15) {   static $max_execution_time, $start_time;    $time = explode(' ', microtime());  $current_time = $time[0] + $time[1];    if (empty($max_execution_time))     {       $max_execution_time = (function_exists('ini_get')) ? (int) @ini_get('max_execution_time') : (int) @get_cfg_var('max_execution_time');       // If zero, then set to something higher to not let the user catch the ten seconds barrier.         if ($max_execution_time === 0)      {           $max_execution_time = 50 + $extra_time;         }       $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50);        // For debugging purposes       // $max_execution_time = 10;        global $starttime;      $start_time = (empty($starttime)) ? $current_time : $starttime;     }   return (ceil($current_time - $start_time) < $max_execution_time) ? true : false; }  /** * * @version Version 0.1 / slightly modified for phpBB 3.0.x (using $H$ as hash type identifier) * * Portable PHP password hashing framework. * * Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in * the public domain. * * There's absolutely no warranty. * * The homepage URL for this framework is: * * http://www.openwall.com/phpass/ * * Please be sure to update the Version line if you edit this file in any way. * It is suggested that you leave the main version number intact, but indicate * your project name (after the slash) and add your own revision information. * * Please do not change the "private" password hashing method implemented in * here, thereby making your hashes incompatible.  However, if you must, please * change the hash type identifier (the "$P$") to something different. * * Obviously, since this code is in the public domain, the above are not * requirements (there can be none), but merely suggestions. * * * Hash the password */ function phpbb_hash($password) {     $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';   $random_state = unique_id();    $random = '';   $count = 6;     if (($fh = @fopen('/dev/urandom', 'rb')))   {       $random = fread($fh, $count);       fclose($fh);    }   if (strlen($random) < $count)   {       $random = '';       for ($i = 0; $i < $count; $i += 16)         {           $random_state = md5(unique_id() . $random_state);           $random .= pack('H*', md5($random_state));      }       $random = substr($random, 0, $count);   }   $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64);   if (strlen($hash) == 34)    {       return $hash;   }   return md5($password); }  /** * Check for correct password * * @param string $password The password in plain text * @param string $hash The stored password hash * * @return bool Returns true if the password is correct, false if not. */ function phpbb_check_hash($password, $hash) {   $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';   if (strlen($hash) == 34)    {       return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;   }   return (md5($password) === $hash) ? true : false; }  /** * Generate salt for hash generation */ function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6) {   if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)    {       $iteration_count_log2 = 8;  }   $output = '$H$';    $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)];  $output .= _hash_encode64($input, 6, $itoa64);      return $output; }  /** * Encode hash */ function _hash_encode64($input, $count, &$itoa64) {     $output = '';   $i = 0;     do  {       $value = ord($input[$i++]);         $output .= $itoa64[$value & 0x3f];          if ($i < $count)        {           $value |= ord($input[$i]) << 8;         }       $output .= $itoa64[($value >> 6) & 0x3f];       if ($i++ >= $count)         {           break;      }       if ($i < $count)        {           $value |= ord($input[$i]) << 16;        }       $output .= $itoa64[($value >> 12) & 0x3f];          if ($i++ >= $count)         {           break;      }       $output .= $itoa64[($value >> 18) & 0x3f];  }   while ($i < $count);    return $output; }  /** * The crypt function/replacement */ function _hash_crypt_private($password, $setting, &$itoa64) {    $output = '*';      // Check for correct hash   if (substr($setting, 0, 3) != '$H$')    {       return $output;     }   $count_log2 = strpos($itoa64, $setting[3]);     if ($count_log2 < 7 || $count_log2 > 30)    {       return $output;     }   $count = 1 << $count_log2;  $salt = substr($setting, 4, 8);     if (strlen($salt) != 8)     {       return $output;     }   /**     * We're kind of forced to use MD5 here since it's the only  * cryptographic primitive available in all versions of PHP  * currently in use.  To implement our own low-level crypto  * in PHP would result in much worse performance and     * consequently in lower iteration counts and hashes that are    * quicker to crack (by non-PHP code).   */  if (PHP_VERSION >= 5)   {       $hash = md5($salt . $password, true);       do      {           $hash = md5($hash . $password, true);       }       while (--$count);   }   else    {       $hash = pack('H*', md5($salt . $password));         do      {           $hash = pack('H*', md5($hash . $password));         }       while (--$count);   }   $output = substr($setting, 0, 12);  $output .= _hash_encode64($hash, 16, $itoa64);      return $output; }  /** * Hashes an email address to a big integer * * @param string $email      Email address * * @return string            Unsigned Big Integer */ function phpbb_email_hash($email) {     return sprintf('%u', crc32(strtolower($email))) . strlen($email); }  /** * Global function for chmodding directories and files for internal use * * This function determines owner and group whom the file belongs to and user and group of PHP and then set safest possible file permissions. * The function determines owner and group from common.php file and sets the same to the provided file. * The function uses bit fields to build the permissions. * The function sets the appropiate execute bit on directories. * * Supported constants representing bit fields are: * * CHMOD_ALL - all permissions (7) * CHMOD_READ - read permission (4) * CHMOD_WRITE - write permission (2) * CHMOD_EXECUTE - execute permission (1) * * NOTE: The function uses POSIX extension and fileowner()/filegroup() functions. If any of them is disabled, this function tries to build proper permissions, by calling is_readable() and is_writable() functions. * * @param string $filename   The file/directory to be chmodded * @param int  $perms      Permissions to set * * @return bool true on success, otherwise false * @author faw, phpBB Group */ function phpbb_chmod($filename, $perms = CHMOD_READ) {   static $_chmod_info;    // Return if the file no longer exists.     if (!file_exists($filename))    {       return false;   }   // Determine some common vars   if (empty($_chmod_info))    {       if (!function_exists('fileowner') || !function_exists('filegroup'))         {           // No need to further determine owner/group - it is unknown             $_chmod_info['process'] = false;        }       else        {           global $phpbb_root_path, $phpEx;            // Determine owner/group of common.php file and the filename we want to change here             $common_php_owner = @fileowner($phpbb_root_path . 'common.' . $phpEx);          $common_php_group = @filegroup($phpbb_root_path . 'common.' . $phpEx);              // And the owner and the groups PHP is running under.           $php_uid = (function_exists('posix_getuid')) ? @posix_getuid() : false;             $php_gids = (function_exists('posix_getgroups')) ? @posix_getgroups() : false;              // If we are unable to get owner/group, then do not try to set them by guessing             if (!$php_uid || empty($php_gids) || !$common_php_owner || !$common_php_group)          {               $_chmod_info['process'] = false;            }           else            {               $_chmod_info = array(                   'process'       => true,                    'common_owner'  => $common_php_owner,                   'common_group'  => $common_php_group,                   'php_uid'       => $php_uid,                    'php_gids'      => $php_gids,               );          }       }   }   if ($_chmod_info['process'])    {       $file_uid = @fileowner($filename);      $file_gid = @filegroup($filename);          // Change owner         if (@chown($filename, $_chmod_info['common_owner']))        {           clearstatcache();           $file_uid = @fileowner($filename);      }       // Change group         if (@chgrp($filename, $_chmod_info['common_group']))        {           clearstatcache();           $file_gid = @filegroup($filename);      }       // If the file_uid/gid now match the one from common.php we can process further, else we are not able to change something       if ($file_uid != $_chmod_info['common_owner'] || $file_gid != $_chmod_info['common_group'])         {           $_chmod_info['process'] = false;        }   }   // Still able to process?   if ($_chmod_info['process'])    {       if ($file_uid == $_chmod_info['php_uid'])       {           $php = 'owner';         }       else if (in_array($file_gid, $_chmod_info['php_gids']))         {           $php = 'group';         }       else        {           // Since we are setting the everyone bit anyway, no need to do expensive operations             $_chmod_info['process'] = false;        }   }   // We are not able to determine or change something     if (!$_chmod_info['process'])   {       $php = 'other';     }   // Owner always has read/write permission   $owner = CHMOD_READ | CHMOD_WRITE;  if (is_dir($filename))  {       $owner |= CHMOD_EXECUTE;        // Only add execute bit to the permission if the dir needs to be readable       if ($perms & CHMOD_READ)        {           $perms |= CHMOD_EXECUTE;        }   }   switch ($php)   {       case 'owner':           $result = @chmod($filename, ($owner << 6) + (0 << 3) + (0 << 0));           clearstatcache();           if (is_readable($filename) && phpbb_is_writable($filename))             {               break;          }       case 'group':           $result = @chmod($filename, ($owner << 6) + ($perms << 3) + (0 << 0));              clearstatcache();           if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))            {               break;          }       case 'other':           $result = @chmod($filename, ($owner << 6) + ($perms << 3) + ($perms << 0));             clearstatcache();           if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename)))            {               break;          }       default:            return false;       break;  }   return $result; }  /** * Test if a file/directory is writable * * This function calls the native is_writable() when not running under * Windows and it is not disabled. * * @param string $file Path to perform write test on * @return bool True when the path is writable, otherwise false. */ function phpbb_is_writable($file) {    if (strtolower(substr(PHP_OS, 0, 3)) === 'win' || !function_exists('is_writable'))  {       if (file_exists($file))         {           // Canonicalise path to absolute path           $file = phpbb_realpath($file);              if (is_dir($file))          {               // Test directory by creating a file inside the directory               $result = @tempnam($file, 'i_w');               if (is_string($result) && file_exists($result))                 {                   unlink($result);                    // Ensure the file is actually in the directory (returned realpathed)                   return (strpos($result, $file) === 0) ? true : false;               }           }           else            {               $handle = @fopen($file, 'r+');                  if (is_resource($handle))               {                   fclose($handle);                    return true;                }           }       }       else        {           // file does not exist test if we can write to the directory            $dir = dirname($file);              if (file_exists($dir) && is_dir($dir) && phpbb_is_writable($dir))           {               return true;            }       }       return false;   }   else    {       return is_writable($file);  } }  // Compatibility functions  if (!function_exists('array_combine')) {   /**     * A wrapper for the PHP5 function array_combine()   * @param array $keys contains keys for the resulting array  * @param array $values contains values for the resulting array  *   * @return Returns an array by using the values from the keys array as keys and the  *   values from the values array as the corresponding values. Returns false if the  *   number of elements for each array isn't equal or if the arrays are empty.   */  function array_combine($keys, $values)  {       $keys = array_values($keys);        $values = array_values($values);        $n = sizeof($keys);         $m = sizeof($values);       if (!$n || !$m || ($n != $m))       {           return false;       }       $combined = array();        for ($i = 0; $i < $n; $i++)         {           $combined[$keys[$i]] = $values[$i];         }       return $combined;   } }  if (!function_exists('str_split')) {   /**     * A wrapper for the PHP5 function str_split()   * @param array $string contains the string to be converted  * @param array $split_length contains the length of each chunk  *   * @return  Converts a string to an array. If the optional split_length parameter is specified,  *   the returned array will be broken down into 

正如你所看到的那样,所有的新线都被切断了,所以它只是一团糟。我还是添加了新代码,它搞砸了所有内容。我能做什么?是否有某种类型的脚本或任何我可以运行这个PHP文件,将修复线?请注意,我没有PHP经验,所以请在回复中详细说明!

4 个答案:

答案 0 :(得分:1)

写字板和Notepad ++都可以很好地处理UNIX风格的换行符。我猜你或其他人以前打开并用另一个程序保存它,如记事本,它不理解这些新行,可能搞砸了。如果到目前为止尚未修改文件,最简单的解决方案可能是从phpBB3存档获取此文件的新副本。

答案 1 :(得分:0)

该文件可能是在* Nix中创建的,并使用Unix换行符。写字板可能无法处理这些。

尝试使用可以处理不同类型换行样式的程序打开它,例如Notepad++

答案 2 :(得分:0)

http://beta.phpformatter.com/

这将使您的代码看起来更好。

答案 3 :(得分:0)

请参阅其他解决方案或尝试:

<?php

file_put_contents("source-fixed.php",
  str_replace("\n", "\r\n", file_get_contents("source.php")));

?>

当然,相应地调整文件名。