/** * 构造方法 * * @access public * @return boolean */ public function __construct() { if (!function_exists('eaccelerator')) { Controller::halt('The eAccelerator extension to be loaded.'); } return true; }
/** * 构造方法 * * 用于初始化运行环境,或对基本变量进行赋值 * * @access public * * @param array $params 数据库连接参数,如主机名,数据库用户名,密码等 * * @return boolean */ public function __construct($params = array()) { if (!extension_loaded('mongo')) { Controller::halt('The mongo extension to be loaded!'); } //参数分析 if (!$params || !is_array($params)) { //加载数据库配置文件. $params = Configure::get('mongo'); } $params = is_array($params) ? $params + $this->_defaultConfig : $this->_defaultConfig; if (!isset($params['dbname']) || !$params['dbname']) { Controller::halt('The file of MongoDB config is error, dbname is not found!'); } try { //实例化mongo $this->_mongo = new Mongo($params['dsn'], $params['option']); //连接mongo数据库 $this->_dbLink = $this->_mongo->selectDB($params['dbname']); //用户登录 if (isset($params['username']) && isset($params['password'])) { $this->_dbLink->authenticate($params['username'], $params['password']); } return true; } catch (Exception $exception) { //抛出异常信息 throw new DoitException('MongoDb connect error!<br/>' . $exception->getMessage(), $exception->getCode()); } }
/** * 执行SQL语句 */ public function query($sql, $link = null) { $link = $link ? $link : $this->db_link; $result = mysql_query($sql, $link); //file_put_contents('sql.txt', $sql . PHP_EOL, FILE_APPEND); //日志操作,当调试模式开启时,将所执行过的SQL写入SQL跟踪日志文件,便于DBA进行MYSQL优化。若调试模式关闭,当SQL语句执行错误时写入日志文件 if (SYS_DEBUG === false) { if ($result == false) { //获取当前运行的namespace、controller及action名称 $action_id = App::get_action_id(); $namespace_id = App::get_namespace_id(); $controller_id = App::get_controller_id(); $namespace_code = $namespace_id ? '[' . $namespace_id . ']' : ''; if (SYS_LOG === true) { Log::write($namespace_code . '[' . $controller_id . '][' . $action_id . '] SQL execute failed :' . $sql . ' Error Code:' . $this->errno() . 'Error Message:' . $this->error()); } } } else { //获取当前运行的namespace、controller及action名称 $action_id = App::get_action_id(); $namespace_id = App::get_namespace_id(); $controller_id = App::get_controller_id(); $sql_log_file = APP_ROOT . 'logs' . DIRECTORY_SEPARATOR . 'SQL_' . date('Y_m_d', $_SERVER['REQUEST_TIME']) . '.log'; $namespace_code = $namespace_id ? '[' . $namespace_id . ']' : ''; if ($result == true) { if (SYS_LOG === true) { Log::write($namespace_code . '[' . $controller_id . '][' . $action_id . ']:' . $sql, 'Normal', $sql_log_file); } } else { Controller::halt($namespace_code . '[' . $controller_id . '][' . $action_id . '] SQL execute failed :' . $sql . '<br/>Error Message:' . $this->error() . '<br/>Error Code:' . $this->errno() . '<br/>Error SQL:' . $sql); } } return $result; }
/** * 构造方法 * * @access public * @return boolean */ public function __construct() { if (!extension_loaded('apc')) { Controller::halt('The apc extension to be loaded.'); } return true; }
/** * 构造方法 * * @access public * @return boolean */ public function __construct() { if (!extension_loaded('wincache')) { Controller::halt('The WinCache extension to be loaded.'); } return true; }
/** * 构造方法 * * @access public * @return boolean */ public function __construct() { //分析xcache扩展模块 if (!extension_loaded('xcache')) { Controller::halt('The xcache extension to be loaded before use!'); } return true; }
/** * 类方法自动调用引导 * * 用于处理类外调用本类不存在的方法时的信息提示 * * @access public * * @param string $method 类方法名称 * @param array $args 参数值。注:本参数为数组 * * @return mixed */ public function __call($method, $args) { //参数分析 $method = strtolower($method); if (in_array($method, array('count', 'max', 'min', 'sum', 'avg'))) { array_unshift($args, $method); return call_user_func_array(array($this, '_selectByFunction'), $args); } return Controller::halt("The method: {$method}() is not found in DbCommand class!", 'Normal'); }
/** * 构造函数 * * @access public * * @param array $params 数据库连接参数,如主机名,数据库用户名,密码等 * * @return boolean */ public function __construct($options = null) { if (!extension_loaded('redis')) { Controller::halt('The redis extension to be loaded!'); } //当参数为空时,程序则自动加载配置文件中数据库连接参数 if (!$options || !is_array($options)) { $options = Configure::get('redis'); if (!$options) { $options = array(); } } $options += $this->_defaultServer; //连接数据库 $this->_dbLink = new Redis(); $this->_dbLink->connect($options['host'], $options['port']); return true; }
/** * 构造方法 * * @access public * * @param array $params 数据库连接参数,如主机名,数据库用户名,密码等 * * @return boolean */ public function __construct($options = null) { //分析memcache扩展模块的加载 if (!extension_loaded('memcache')) { Controller::halt('The memcache extension to be loaded before use!'); } //获取Memcache服务器连接参数 if (!$options || !is_array($options)) { $options = Configure::get('memcache'); } if (is_array($options) && $options) { $this->_defaultOptions = $options + $this->_defaultOptions; } if (!$this->_defaultOptions['servers']) { $this->_defaultOptions['servers'][] = $this->_defaultServer; } $this->_dbLink = new Memcache(); foreach ($this->_defaultOptions['servers'] as $server) { $server += array('host' => '127.0.0.1', 'port' => 11211, 'persistent' => true); $this->_dbLink->addServer($server['host'], $server['port'], $this->_defaultOptions['persistent']); } return true; }
/** * 构造方法 * * 用于初始化运行环境,或对基本变量进行赋值 * * @access public * * @param array $params 数据库连接参数,如主机名,数据库用户名,密码等 * * @return boolean */ public function __construct($params = array()) { //参数分析 if (!$params['dsn']) { Controller::halt('database config params error!', 'Normal'); } $params += $this->_defaultConfig; //数据库连接 try { $flags = array(PDO::ATTR_PERSISTENT => $params['persistency'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); //实例化数据库连接 $this->_dbLink = new PDO($params['dsn'], $params['username'], $params['password'], $flags); } catch (PDOException $exception) { //当调试模式关闭时 if (DOIT_DEBUG === false) { //记录错误日志 Log::write("Database server connect error! Error Code:{$exception->getCode()} Error Message:{$exception->getMessage()}", 'Warning'); //提示错误信息 Controller::showMsg('数据库连接失败!'); } //抛出异常信息 throw new DoitException('Database connect error!<br/>' . $exception->getMessage(), $exception->getCode()); } //设置数据编码 $driverName = $this->_dbLink->getAttribute(PDO::ATTR_DRIVER_NAME); switch ($driverName) { case 'mysql': case 'pgsql': $this->_dbLink->exec("SET NAMES {$params['charset']}"); break; case 'sqlsrv': $this->_dbLink->setAttribute(PDO::SQLSRV_ATTR_ENCODING, $params['charset']); break; } return true; }
/** * trigger_error()的简化函数 * * 用于显示错误信息. 若调试模式关闭时(即:SYS_DEBUG为false时),则将错误信息并写入日志 * @access public * @param string $message 所要显示的错误信息 * @param string $level 日志类型. 默认为Error. 参数:Warning, Error, Notice * @return void */ public function halt($message, $level = 'Error') { return Controller::halt($message, $level); }
/** * 类方法自动调用引导 * * 用于处理类外调用本类不存在的方法时的信息提示 * * @access public * * @param string $method 类方法名称 * @param array $args 所调用类方法的参数 * * @return mixed */ public function __call($method, $args) { //分析 findByxx()的类方法调用 if (strpos($method, 'findBy') !== false) { //分析所要查询的数据表字段名 $fieldsName = substr($method, 6); $fieldsName = ltrim(strtolower(preg_replace('#[A-Z]#', '_\\0', $fieldsName)), '_'); array_unshift($args, "{$fieldsName}=?"); return call_user_func_array(array($this, 'getOne'), $args); } //分析 findAllByxx()的类方法调用 if (strpos($method, 'findAllBy') !== false) { //分析所要查询的数据表字段名 $fieldsName = substr($method, 9); $fieldsName = ltrim(strtolower(preg_replace('#[A-Z]#', '_\\0', $fieldsName)), '_'); array_unshift($args, "{$fieldsName}=?"); return call_user_func_array(array($this, 'getAll'), $args); } return Controller::halt("The method: {$method}() is not found in Model class!", 'Normal'); }
/** * 读取名字为$name的zip包的内容 * * @access public * * @param string $name 所读取的zip文件的路径 * * @return array */ public function readZip($name) { //参数分析 if (!$name) { return false; } if (!is_file($name)) { Controller::halt("The File: {$name} is not found!"); } // File information $size = filesize($name); // Read file $fh = fopen($name, "rb"); $filedata = fread($fh, $size); fclose($fh); // Break into sections $filesecta = explode("PK", $filedata); // ZIP Comment $unpackeda = unpack('x16/v1length', $filesecta[1]); $comment = substr($filesecta[1], 18, $unpackeda['length']); $comment = str_replace(array("\r\n", "\r"), "\n", $comment); // CR + LF and CR -> LF // Cut entries from the central directory $filesecta = explode("PK", $filedata); $filesecta = explode("PK", $filesecta[0]); array_shift($filesecta); // Removes empty entry/signature $files = array(); foreach ($filesecta as $filedata) { // CRC:crc, FD:file date, FT: file time, CM: compression method, GPF: general purpose flag, VN: version needed, CS: compressed size, UCS: uncompressed size, FNL: filename length $entrya = array(); $unpackeda = unpack("v1version/v1general_purpose/v1compress_method/v1file_time/v1file_date/V1crc/V1size_compressed/V1size_uncompressed/v1filename_length", $filedata); // Check for value block after compressed data if ($unpackeda['general_purpose'] & 0x8) { $unpackeda2 = unpack("V1crc/V1size_compressed/V1size_uncompressed", substr($filedata, -12)); $unpackeda['crc'] = $unpackeda2['crc']; $unpackeda['size_compressed'] = $unpackeda2['size_uncompressed']; $unpackeda['size_uncompressed'] = $unpackeda2['size_uncompressed']; unset($unpackeda2); } $entrya['name'] = substr($filedata, 26, $unpackeda['filename_length']); if (substr($entrya['name'], -1) == "/") { continue; } $entrya['dir'] = dirname($entrya['name']); $entrya['dir'] = $entrya['dir'] == "." ? "" : $entrya['dir']; $entrya['name'] = basename($entrya['name']); $files[] = $entrya; } return $files; }
/** * 加载视图文件 * * 加载视图文件并对视图标签进行编译 * * @access protected * * @param string $viewFile 视图文件及路径 * * @return string */ protected function _loadViewFile($viewFile) { //分析视图文件是否存在 if (!is_file($viewFile)) { Controller::halt("The view file: {$viewFile} is not found!", 'Normal'); } $viewContent = file_get_contents($viewFile); //编译视图标签 return $this->_handleViewFile($viewContent); }
/** * 显示验证码. * * @access public * * @param string $imageUrl 验证码的背影图片路径 * * @return void */ public function show($imageUrl = null) { //当前面没有session_start()调用时. Session::start(); if (!is_null($imageUrl)) { $this->_imageUrl = trim($imageUrl); } $this->_image = !function_exists('imagecreatetruecolor') ? imagecreate($this->_width, $this->_height) : imagecreatetruecolor($this->_width, $this->_height); //当有背景图片存在时 if ($this->_imageUrl) { //初始化图片信息. list($imageWidth, $imageHeight, $type) = getimagesize($this->_imageUrl); //分析图片的格式 switch ($type) { case 1: $image = imagecreatefromgif($this->_imageUrl); $this->_type = 'gif'; break; case 2: $image = imagecreatefromjpeg($this->_imageUrl); $this->_type = 'jpg'; break; case 3: $image = imagecreatefrompng($this->_imageUrl); $this->_type = 'png'; break; case 4: $image = imagecreatefromwbmp($this->_imageUrl); $this->_type = 'bmp'; break; } //背景 $srcX = $imageWidth > $this->_width ? mt_rand(0, $imageWidth - $this->_width) : 0; $srcY = $imageHeight > $this->_height ? mt_rand(0, $imageHeight - $this->_height) : 0; imagecopymerge($this->_image, $image, 0, 0, $srcX, $srcY, $this->_width, $this->_height, 100); imagedestroy($image); //边框 $borderColor = imagecolorallocate($this->_image, 255, 255, 255); imagerectangle($this->_image, 1, 1, $this->_width - 2, $this->_height - 2, $borderColor); } else { //定义图片类型 $this->_type = 'png'; //背景 $bgColorArray = !$this->_bgColor ? array(255, 255, 255) : $this->_bgColor; $back_color = imagecolorallocate($this->_image, $bgColorArray[0], $bgColorArray[1], $bgColorArray[2]); imagefilledrectangle($this->_image, 0, 0, $this->_width - 1, $this->_height - 1, $back_color); //边框 $borderColor = imagecolorallocate($this->_image, 238, 238, 238); imagerectangle($this->_image, 0, 0, $this->_width - 1, $this->_height - 1, $borderColor); } //获取验证码内容. $this->getPincodeContent(); //验证码中含有汉字 if (!preg_match('~[\\x{4e00}-\\x{9fa5}]+~u', $this->_textContent)) { //计算验证码的位数 $codeStrlen = strlen($this->_textContent); //每位验证码所占用的图片宽度 $perWidth = ceil(($this->_width - 10) / $codeStrlen); for ($i = 0; $i < $codeStrlen; $i++) { //获取单个字符 $textContent = $this->_textContent[$i]; $bbox = imagettfbbox($this->_fontSize, 0, $this->_fontName, $textContent); $fontW = $bbox[2] - $bbox[0]; $fontH = abs($bbox[7] - $bbox[1]); $fontX = ceil(($perWidth - $fontW) / 2) + $perWidth * $i + 5; $min_y = $fontH + 5; $max_y = $this->_height - 5; $fontY = rand($min_y, $max_y); $fontColor = !$this->_fontColor ? imagecolorallocate($this->_image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)) : imagecolorallocate($this->_image, $this->_fontColor[0], $this->_fontColor[1], $this->_fontColor[2]); imagettftext($this->_image, $this->_fontSize, 0, $fontX, $fontY, $fontColor, $this->_fontName, $textContent); } } else { //分析验证码的位置 $bbox = imagettfbbox($this->_fontSize, 0, $this->_fontName, $this->_textContent); $fontW = $bbox[2] - $bbox[0]; $fontH = abs($bbox[7] - $bbox[1]); $fontX = ceil(($this->_width - $fontW) / 2) + 5; $min_y = $fontH + 5; $max_y = $this->_height - 5; $fontY = rand($min_y, $max_y); $fontColor = !$this->_fontColor ? imagecolorallocate($this->_image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)) : imagecolorallocate($this->_image, $this->_fontColor[0], $this->_fontColor[1], $this->_fontColor[2]); imagettftext($this->_image, $this->_fontSize, 0, $fontX, $fontY, $fontColor, $this->_fontName, $this->_textContent); } //干扰线 for ($i = 0; $i < 5; $i++) { $line_color = imagecolorallocate($this->_image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); imageline($this->_image, mt_rand(2, $this->_width - 3), mt_rand(2, $this->_height - 3), mt_rand(2, $this->_width - 3), mt_rand(2, $this->_height - 3), $line_color); } //将显示的验证码赋值给session. Session::set($this->_sessionName, $this->_textContent); //当有headers内容输出时. if (headers_sent()) { Controller::halt('headers already sent'); } //显示图片,根据背景图片的格式显示相应格式的图片. switch ($this->_type) { case 'gif': header('Content-type:image/gif'); imagegif($this->_image); break; case 'jpg': header('Content-type:image/jpeg'); imagejpeg($this->_image); break; case 'png': header('Content-type:image/png'); imagepng($this->_image); break; case 'bmp': header('Content-type:image/wbmp'); imagewbmp($this->_image); break; } imagedestroy($this->_image); }
/** * 文件重命名或移动文件 * * @access public * * @param string $sourceFile 源文件 * @param string $destFile 新文件名或路径 * * @return boolean */ public static function moveFile($sourceFile, $destFile) { //参数分析 if (!$sourceFile || !$destFile) { return false; } //文件及目录分析 if (!is_file($sourceFile)) { Controller::halt('The file:' . $sourceFile . ' is not found!'); } self::_parseDir(dirname($destFile), true); return rename($sourceFile, $destFile); }
/** * 获取项目配置文件内容 * * 根据DoitPHP项目的配置文件名称,获取该项目配置文件的内容,并将该内容进行返回 * * @access public * * @param string $fileName 项目配置文件名。注:不含“.php”后缀。 * * @return array */ public static function getConfig($fileName) { //参数分析. if (!$fileName) { return false; } if (!isset(self::$_config[$fileName])) { $filePath = BASE_PATH . '/config/' . $fileName . '.php'; //判断文件是否存在 if (!is_file($filePath)) { Controller::halt('The configuration file: ' . $fileName . '.php is not exists!', 'Normal'); } $config = array(); include_once $filePath; self::$_config[$fileName] = $config; } return self::$_config[$fileName]; }
/** * 根据图片原来的宽和高的比例,自适应性处理缩略图的宽度和高度 * * @access protected * @return boolean */ protected function _handleImageSize() { //当没有所生成的图片的宽度和高度设置时. if (!$this->_width || !$this->_height) { Controller::halt('You do not set the image height size or width size!'); } $perW = $this->_width / $this->_imageWidth; $perH = $this->_height / $this->_imageHeight; if (ceil($this->_imageHeight * $perW) > $this->_height) { $this->_widthNew = ceil($this->_imageWidth * $perH); $this->_heightNew = $this->_height; } else { $this->_widthNew = $this->_width; $this->_heightNew = ceil($this->_imageHeight * $perW); } return true; }
/** * 静态加载文件 */ public static function load_file($file_name) { if (!$file_name) { return false; } if (!isset(self::$_inc_files[$file_name]) || self::$_inc_files[$file_name] == false) { if (!is_file($file_name)) { Controller::halt('The file:' . $file_name . ' not found!'); } include_once $file_name; self::$_inc_files[$file_name] = true; } return self::$_inc_files[$file_name]; }
/** * 自动加载挂件文件 * * @access private * * @param string $className 所需要加载的类的名称,注:不含后缀名 * @param boolean $supportModule 是否支持模块(Module)文件的自动加载 (true:支持/false:不支持) * * @return void */ private static function _loadWidget($className, $supportModule = true) { //定义所要加载的文件是否在模块(Module)目录中。(true:在/false:不在) $isModule = false; //获取当前所运行的模块(Module) $moduleName = Doit::getModuleName(); //当支持模块(Module)文件自动加载开关开启时 if ($supportModule) { //获取Widget文件目录路径 if (!$moduleName) { $widgetHomePath = BASE_PATH . 'widgets' . DIRECTORY_SEPARATOR; } else { $widgetHomePath = BASE_PATH . 'modules' . DIRECTORY_SEPARATOR . $moduleName . DIRECTORY_SEPARATOR . 'widgets' . DIRECTORY_SEPARATOR; //重定义所要加载的文件是否在模块(Module)目录中 $isModule = true; } } else { $widgetHomePath = BASE_PATH . 'widgets' . DIRECTORY_SEPARATOR; } //分析Widget文件的实际路径 $widgetFilePath = self::_parseFilePath($widgetHomePath, substr($className, 0, -6)); //当Widget文件在Widget根目录中存在时 if (!is_file($widgetFilePath)) { //当模块(Module)中Widget目录不存在所要加载的Widget文件时,对application中Widget目录进行分析并加载Widget文件 if ($isModule) { return self::_loadWidget($className, false); } //当所要加载的Widget文件不存在时,显示错误提示信息 Controller::halt('The Widget file: ' . $widgetFilePath . ' is not found!', 'Normal'); } //加载Widget文件 Doit::loadFile($widgetFilePath); return true; }
/** * 静态加载文件(相当于PHP函数require_once) * * include 以$fileName为名的php文件,如果加载了,这里将不再加载. * @param string $filePath 文件路径,注:含后缀名 * @return boolean */ public static function loadFile($filePath) { //参数分析 if (!$filePath) { return false; } //判断文件有没有加载过,加载过的直接返回true if (!isset(self::$_incFiles[$filePath])) { //分析文件是不是真实存在,若文件不存在,则只能... if (!is_file($filePath)) { //当所要加载的文件不存在时,错误提示 Controller::halt('The file: ' . $filePath . ' is not found!'); } include_once $filePath; self::$_incFiles[$filePath] = true; } return self::$_incFiles[$filePath]; }
/** * 分析视图文件路径 * * 获取视图的路径,便于程序进行include操作。注:本方法不支持视图布局结构(layout) * * @access publice * * @param string $fileName 视图文件名。注:名称中不带.php后缀。 * * @return string */ protected function _parseViewFile($fileName = null) { //参数分析 if (!$fileName) { $viewFileName = Doit::getControllerName() . DIRECTORY_SEPARATOR . Doit::getActionName(); } else { $fileName = str_replace('.', '/', $fileName); $viewFileName = strpos($fileName, '/') === false ? Doit::getControllerName() . DIRECTORY_SEPARATOR . $fileName : $fileName; } $viewPath = $this->_viewPath . $viewFileName . VIEW_EXT; //分析视图文件是否存在 if (!is_file($viewPath)) { Controller::halt("The view File: {$viewPath} is not found!", 'Normal'); } return $viewPath; }
/** * 加载语言数据文件 * * @access public * * @param string $langName 语言名称 * * @return array */ public function loadLanguage($langName = 'zh_cn') { //参数分析 if (!$langName) { return false; } $langFilePath = $this->_langPath . $langName . '.php'; static $_langArray = array(); if (!isset($_langArray[$langName])) { //分析语言文件是否存在 if (!is_file($langFilePath)) { Controller::halt("The Langueage File: {$langFilePath} is not found!", 'Normal'); } //获取语言包内容 $lang = array(); include_once $langFilePath; $_langArray[$langName] = $lang; } return $_langArray[$langName]; }
/** * 根据图片原来的宽和高的比例,自适应性处理缩略图的宽度和高度 * * @return boolean */ protected function handle_image_size() { //当没有所生成的图片的宽度和高度设置时. if (!$this->width || !$this->height) { Controller::halt('You do not set the image height size or width size!'); } $per_w = $this->width / $this->image_width; $per_h = $this->height / $this->image_height; if (ceil($this->image_height * $per_w) > $this->height) { $this->width_new = ceil($this->image_width * $per_h); $this->height_new = $this->height; } else { $this->width_new = $this->width; $this->height_new = ceil($this->image_height * $per_w); } return true; }