sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function hook($hook, $params = []) { $hookRun = isset(self::$mountInfo[$hook]) ? self::$mountInfo[$hook] : null; if (!is_null($hookRun)) { foreach ($hookRun as $key => $val) { if (is_int($key)) { $callBack = $val; } else {...
执行插件 @param string $hook 插件钩子名称 @param array $params 参数 @return mixed
entailment
public static function mount($hook, $params = []) { is_array($params) || $params = [$params]; if (isset(self::$mountInfo[$hook])) { self::$mountInfo[$hook] += $params; } else { self::$mountInfo[$hook] = $params; } }
挂载插件到钩子 \Cml\Plugin::mount('hookName', [ function() {//匿名函数 }, '\App\Test\Plugins' => 'run' //对象, '\App\Test\Plugins::run'////静态方法 ]); @param string $hook 要挂载的目标钩子 @param array $params 相应参数
entailment
public function get($key) { $filename = $this->getFilename($key); if (!$filename || !is_file($filename)) return false; Cml::requireFile($filename); return true; }
静态页面-获取静态页面 @param string $key 静态页面标识符,可以用id代替 @return bool
entailment
private function html() { $filename = $this->getFilename($this->key); if (!$filename) return false; return @file_put_contents($filename, ob_get_contents(), LOCK_EX); }
静态页面-生成静态页面 @return bool
entailment
private function getFilename($key) { $filename = ($this->ismd5 == true) ? md5($key) : $key; if (!is_dir($this->htmlPath)) return false; return $this->htmlPath . '/' . $filename . '.htm'; }
静态页面-静态页面文件 @param string $key 静态页面标识符,可以用id代替 @return string
entailment
public function addRule($pattern, $replacement, $haveDelimiter = true) { if ($pattern && $replacement) { $this->pattern = $haveDelimiter ? '#' . $this->options['leftDelimiter'] . $pattern . $this->options['rightDelimiter'] . '#s' : "#{$pattern}#s"; $this->replacement = $replacement; ...
添加一个模板替换规则 @param string $pattern 正则 @param string $replacement 替换成xx内容 @param bool $haveDelimiter $pattern的内容是否要带上左右定界符 @return $this
entailment
public function setHtmlEngineOptions($name, $value = '') { if (is_array($name)) { $this->options = array_merge($this->options, $name); } else { $this->options[$name] = $value; } return $this; }
设定模板配置参数 @param string | array $name 参数名称 @param mixed $value 参数值 @return $this
entailment
private function getFile($file, $type = 0) { $type == 1 && $file = $this->initBaseDir($file);//初始化路径 //$file = str_replace([('/', '\\'], DIRECTORY_SEPARATOR, $file); $cacheFile = $this->getCacheFile($file); if ($this->options['autoUpdate']) { $tplFile = $this->getTplFile(...
获取模板文件缓存 @param string $file 模板文件名称 @param int $type 缓存类型0当前操作的模板的缓存 1包含的模板的缓存 @return string
entailment
private function compile($tplFile, $cacheFile, $type) { //取得模板内容 //$template = file_get_contents($tplFile); $template = $this->getTplContent($tplFile, $type); //执行替换 $template = preg_replace($this->pattern, $this->replacement, $template); if (!Cml::$debug) { ...
对模板文件进行缓存 @param string $tplFile 模板文件名 @param string $cacheFile 模板缓存文件名 @param int $type 缓存类型0当前操作的模板的缓存 1包含的模板的缓存 @return mixed
entailment
private function getTplContent($tplFile, $type) { if ($type === 0 && !is_null($this->layout)) {//主模板且存在模板布局 $layoutCon = file_get_contents($this->layout); $tplCon = file_get_contents($tplFile); //获取子模板内容 $presult = preg_match_all( '#' . $this-...
获取模板文件内容 使用布局的时候返回处理完的模板 @param $tplFile @param int $type 缓存类型0当前操作的模板的缓存 1包含的模板的缓存 @return string
entailment
private function makePath($path) { $path = dirname($path); if (!is_dir($path) && !mkdir($path, 0700, true)) { throw new MkdirErrorException(Lang::get('_CREATE_DIR_ERROR_') . "[{$path}]"); } return true; }
根据指定的路径创建不存在的文件夹 @param string $path 路径/文件夹名称 @return string
entailment
private function initBaseDir($templateFile, $inOtherApp = false) { $baseDir = $inOtherApp ? $inOtherApp : Cml::getContainer()->make('cml_route')->getAppName(); $baseDir && $baseDir .= '/'; $baseDir .= Cml::getApplicationDir('app_view_path_name') . (Config::get('html_theme') != '' ? DIRECTORY...
初始化目录 @param string $templateFile 模板文件名 @param bool|false $inOtherApp 是否在其它app @return string
entailment
public function display($templateFile = '', $inOtherApp = false) { // 网页字符编码 header('Content-Type:text/html; charset=' . Config::get('default_charset')); echo $this->fetch($templateFile, $inOtherApp); Cml::cmlStop(); }
模板显示 调用内置的模板引擎显示方法, @param string $templateFile 指定要调用的模板文件 默认为空 由系统自动定位模板文件 @param bool $inOtherApp 是否为载入其它应用的模板 @return void
entailment
public function fetch($templateFile = '', $inOtherApp = false, $doNotSetDir = false, $donNotWriteCacheFileImmediateReturn = false) { if (Config::get('form_token')) { Secure::setToken(); } ob_start(); if ($donNotWriteCacheFileImmediateReturn) { $tplFile = $thi...
渲染模板获取内容 调用内置的模板引擎显示方法, @param string $templateFile 指定要调用的模板文件 默认为空 由系统自动定位模板文件 @param bool $inOtherApp 是否为载入其它应用的模板 @param bool $doNotSetDir 不自动根据当前请求设置目录模板目录。用于特殊模板显示 @param bool $donNotWriteCacheFileImmediateReturn 不要使用模板缓存,实时渲染(系统模板使用) @return string
entailment
public function displayWithLayout($templateFile = '', $layout = 'master', $layoutInOtherApp = false, $tplInOtherApp = false) { $this->layout = Cml::getApplicationDir('apps_path') . DIRECTORY_SEPARATOR . ($layoutInOtherApp ? $layoutInOtherApp : Cml::getContainer()->make('cml_route')->getAppName()...
使用布局模板并渲染 @param string $templateFile 模板文件 @param string $layout 布局文件 @param bool|false $layoutInOtherApp 布局文件是否在其它应用 @param bool|false $tplInOtherApp 模板是否在其它应用
entailment
public function execute(array $args, array $options = []) { if (empty($args) || strpos($args[0], '/') < 1) { throw new \InvalidArgumentException('please input action'); } Route::setPathInfo(explode('/', trim(trim($args[0], '/\\')))); return 'don_not_exit'; }
命令的入口方法 @param array $args 传递给命令的参数 @param array $options 传递给命令的选项 @return string;
entailment
public function execute(array $args, array $options = []) { $this->bootstrap($args, $options); $version = isset($options['target']) ? $options['target'] : $options['t']; $date = isset($options['date']) ? $options['date'] : $options['d']; $force = isset($options['force']) ? $options[...
回滚迁移 @param array $args 参数 @param array $options 选项
entailment
public static function parse($theme = 'layui', $onCurrentApp = true, $render = true) { if (!in_array($theme, ['bootstrap', 'layui'])) { throw new \InvalidArgumentException(Lang::get('_PARAM_ERROR_', 'theme', '[bootstrap / layui]')); } $result = []; $app = is_string($onCur...
从注释解析生成文档 @param string $theme 主题layui/bootstrap两种 @param bool|string 为字符串时从其所在的app下读取。否则从执行当前方法的app下读取 @param bool $render 是否渲染输出 @return array|bool
entailment
public static function getAnnotationParams($controller, $action) { $result = []; $reflection = new \ReflectionClass($controller); $res = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($res as $method) { if ($method->name == $action) { $an...
解析获取某控制器注释参数信息 @param string $controller 控制器名 @param string $action 方法名 @return array
entailment
private static function formatCode($code) { $code = array_map(function ($val) { return trim(ltrim(trim($val), '*')); }, explode("\n", trim($code))); $dep = 0; foreach ($code as $lineNum => &$line) { $pos = strpos($line, '//'); $pos || $pos = strpo...
格式化json代码 @param $code @return string
entailment
public function lock($key, $wouldBlock = false) { if (empty($key)) { return false; } $key = $this->getKey($key); if ( isset($this->lockCache[$key]) && $this->lockCache[$key] == Model::getInstance()->cache($this->useCache)->getInstance()->get($key)...
上锁 @param string $key 要上的锁的key @param bool $wouldBlock 是否堵塞 @return mixed
entailment
public function setMailBody($data, $template_html = null, $format = 'HTML') { if ( !is_array($data) && $template_html == null ) { if ( $format == 'TEXT' ) { $this->isHTML = false; return $this->textBody = $data; } return $this->htmlBody = $data; } else...
Set Mail Body configuration Format email message Body, this can be an external template html file with a copy of a plain-text like template.txt or HTML/plain-text string. This method can be used by passing a template file HTML name and an associative array with the values that can be parsed into the file HTML by the k...
entailment
public function sendMail($subject = null, $mailto = null, $mailtoName = null) { # mailer send FROM $this->setFrom($this->from_mail, $this->from_name); # mailer Reply TO $this->addReplyTo($this->replyto_mail, $this->replyto_name); # mailer set BCC ( $this->setBcc ) ? $this->addBc...
sendMail with PHPMailer Library @see PHPMailer @see SMTP @param string $subject set a string to be a email message subject @param mixed $mailto [array|string] the mail address or both Mail and Name as an array if its not defined the config replyTo will be used instead @param string $mailtoName can be defined followed...
entailment
public function execute(array $args, array $options = []) { $className = $args[0]; $this->bootstrap($args, $options); if (!Util::isValidPhinxClassName($className)) { throw new \InvalidArgumentException(sprintf( 'The migration class name "%s" is invalid. Please u...
创建一个迁移 @param array $args 参数 @param array $options 选项
entailment
public function setOptions(array $options) { if (isset($options['indent'])) { $this->indent = $options['indent']; } if (isset($options['quote'])) { $this->quote = $options['quote']; } if (isset($options['foregroundColors'])) { $this->foregr...
设置参数 @param array $options @return $this
entailment
public function format($text) { $lines = explode("\n", $text); foreach ($lines as &$line) { $line = ($this->quote) . str_repeat(' ', $this->indent) . $line; } return Colour::colour(implode("\n", $lines), $this->foregroundColors, $this->backgroundColors); }
格式化文本 @param string $text @return string
entailment
public static function get($key = null, $default = null) { // 无参数时获取所有 if (empty($key)) { return self::$_content; } $key = strtolower($key); return Cml::doteToArr($key, self::$_content['normal'], $default); }
获取配置参数不区分大小写 @param string $key 支持.获取多维数组 @param string $default 不存在的时候默认值 @return mixed
entailment
public static function load($file, $global = true) { if (isset(static::$_content[$global . $file])) { return static::$_content[$global . $file]; } else { $filePath = ( $global === true ? Cml::getApplicationDir('global_config...
从文件载入Config @param string $file @param bool $global 是否从全局加载,true为从全局加载、false为载入当前app下的配置、字符串为从指定的app下加载 @return array
entailment
public function execute(array $args, array $options = []) { $this->writeln("CmlPHP Console " . Cml::VERSION . "\n", ['foregroundColors' => [Colour::GREEN, Colour::HIGHLIGHT]]); $format = new Format(['indent' => 2]); if (empty($args)) { $this->writeln("Usage:"); $this...
执行命令入口 @param array $args 参数 @param array $options 选项
entailment
private function formatCommand() { $cmdGroup = []; $noGroup = []; foreach ($this->console->getCommands() as $name => $class) { if ($class !== __CLASS__) { $class = new \ReflectionClass($class); $property = $class->getDefaultProperties(); ...
格式化命令 @return array
entailment
private function formatOptions($options = [], $command = '') { $dumpOptions = [ '-h | --help' => "display {$command}command help info", '--no-ansi' => "disable ansi output" ]; count($options) > 0 && $dumpOptions = array_merge($dumpOptions, $options); $option...
格式化选项 @param array $options @param string $command @return array
entailment
private function formatArguments(Array $arguments) { $echoArguments = []; $argsLength = 0; foreach ($arguments as $argument => $desc) { $argument = Colour::colour($argument, Colour::GREEN); $echoArguments[$argument] = $desc; $argsLength > strlen($argument)...
格式化参数 @param array $arguments @return array
entailment
private function formatEcho(Format $format, $args) { foreach ($args as $group => $list) { if (is_array($list)) { $this->writeln($format->format($group)); foreach ($list as $name => $desc) { $this->writeln($format->format(' ' . $name . str_repe...
格式化输出 @param Format $format @param array $args
entailment
public function getPlaceList(Location $location, $contentTypes, $languages = array()) { $query = new Query(); $query->filter = new Criterion\LogicalAnd( array( new Criterion\ContentTypeIdentifier($contentTypes), new Criterion\Subtree($location->pathString)...
Returns all places contained in a place_list. @param \eZ\Publish\API\Repository\Values\Content\Location $location of a place_list @param string|string[] $contentTypes to be retrieved @param string|string[] $languages to be retrieved @return \eZ\Publish\API\Repository\Values\Content\Content[]
entailment
public function getPlaceListSorted(Location $location, $latitude, $longitude, $contentTypes, $maxDist = null, $sortClauses = array(), $languages = array()) { if ($maxDist === null) { $maxDist = $this->placeListMaxDist; } $query = new Query(); $query->filter = new Criteri...
Returns all places contained in a place_list that are located between the range defined in the default configuration. A sort clause array can be provided in order to sort the results. @param \eZ\Publish\API\Repository\Values\Content\Location $location of a place_list @param float $latitude @param float $longitude @par...
entailment
public static function lockWait($key, $reTryTimes = 3) { $reTryTimes = intval($reTryTimes); $i = 0; while (!self::lock($key)) { if (++$i >= $reTryTimes) { return false; } usleep(2000); } return true; }
上锁并重试N次-每2000微秒重试一次 @param string $key 要解锁的锁的key @param int $reTryTimes 重试的次数 @return bool
entailment
public function display() { header('Content-Type: application/json;charset=' . Config::get('default_charset')); if (Cml::$debug) { $sql = Debug::getSqls(); if (Config::get('dump_use_php_console')) { $sql && \Cml\dumpUsePHPConsole($sql, 'sql'); ...
输出数据
entailment
public static function setTableName($type = 'access', $tableName = 'access') { if (is_array($type)) { self::$tables = array_merge(self::$tables, $type); } else { self::$tables[$type] = $tableName; } }
自定义表名 @param string|array $type @param string $tableName
entailment
public static function getTableName($type = 'access') { if (isset(self::$tables[$type])) { return self::$tables[$type]; } else { throw new \InvalidArgumentException($type); } }
获取表名 @param string $type @return mixed
entailment
public static function setLoginStatus($uid, $sso = true, $cookieExpire = 0, $notOperationAutoLogin = 3600, $cookiePath = '', $cookieDomain = '') { $cookieExpire > 0 && $notOperationAutoLogin = 0; $user = [ 'uid' => $uid, 'expire' => $notOperationAutoLogin > 0 ? Cml::$nowTime ...
保存当前登录用户的信息 @param int $uid 用户id @param bool $sso 是否为单点登录,即踢除其它登录用户 @param int $cookieExpire 登录的过期时间,为0则默认保持到浏览器关闭,> 0的值为登录有效期的秒数。默认为0 @param int $notOperationAutoLogin 当$cookieExpire设置为0时,这个值为用户多久不操作则自动退出。默认为1个小时 @param string $cookiePath path @param string $cookieDomain domain
entailment
public static function getLoginInfo() { if (is_null(self::$authUser)) { //Cookie::get本身有一重解密 这里解第二重 self::$authUser = Encry::decrypt(Cookie::get(Config::get('userauthid')), self::$encryptKey); empty(self::$authUser) || self::$authUser = json_decode(self::$authUser, true);...
获取当前登录用户的信息 @return array
entailment
public static function checkAcl($controller) { $authInfo = self::getLoginInfo(); if (!$authInfo) return false; //登录超时 //当前登录用户是否为超级管理员 if (self::isSuperUser()) { return true; } $checkUrl = Cml::getContainer()->make('cml_route')->getFullPathNotContainSubD...
检查对应的权限 @param object|string $controller 传入控制器实例对象,用来判断当前访问的方法是不是要跳过权限检查。 如当前访问的方法为web/User/list则传入new \web\Controller\User()获得的实例。最常用的是在基础控制器的init方法或构造方法里传入$this。 传入字符串如web/User/list时会自动 new \web\Controller\User()获取实例用于判断 @throws \Exception @return bool
entailment
public static function getMenus($format = true, $columns = '') { $res = []; $authInfo = self::getLoginInfo(); if (!$authInfo) { //登录超时 return $res; } $result = Model::getInstance()->table([self::$tables['menus'] => 'm']) ->columns(['distinct m.id', 'm...
获取有权限的菜单列表 @param bool $format 是否格式化返回 @param string $columns 要额外获取的字段 @return array
entailment
public static function logout() { $user = Acl::getLoginInfo(); $user && Model::getInstance()->cache()->delete("SSOSingleSignOn" . $user['id']); Cookie::delete(Config::get('userauthid')); }
登出
entailment
public static function isSuperUser() { $authInfo = self::getLoginInfo(); if (!$authInfo) {//登录超时 return false; } $admin = Config::get('administratorid'); return is_array($admin) ? in_array($authInfo['id'], $admin) : ($authInfo['id'] === $admin); }
判断当前登录用户是否为超级管理员 @return bool
entailment
public function get($key) { $fileName = $this->getFileName($key); if (!is_file($fileName)) { if ($this->lock) { $this->lock = false; $this->set($key, 0); return 0; } return false; } $fp = fopen($fileN...
获取缓存 @param string $key 要获取的缓存key @return mixed
entailment
public function set($key, $value, $expire = 0) { $value = '<?php exit;?>' . time() . "($expire)" . serialize($value); if ($this->lock) {//自增自减 fseek($this->lock, 0); $return = fwrite($this->lock, $value); flock($this->lock, LOCK_UN); fclose($this->loc...
写入缓存 @param string $key key 要缓存的数据的key @param mixed $value 要缓存的数据 要缓存的值,除resource类型外的数据类型 @param int $expire 缓存的有效时间 0为不过期 @return bool
entailment
public function delete($key) { $fileName = $this->getFileName($key); return (is_file($fileName) && unlink($fileName)); }
删除缓存 @param string $key 要删除的数据的key @return bool
entailment
public function cleanDir($dir) { if (empty($dir)) return false; $dir === 'all' && $dir = '';//删除所有 $fullDir = $this->conf['CACHE_PATH'] . $dir; if (!is_dir($fullDir)) { return false; } $files = scandir($fullDir); foreach ($files as $file) { ...
清空文件夹 @param string $dir @return bool
entailment
public function increment($key, $val = 1) { $this->lock = true; $v = $this->get($key); if (is_int($v)) { return $this->update($key, $v + abs(intval($val))); } else { $this->set($key, 1); return 1; } }
自增 @param string $key 要自增的缓存的数据的key @param int $val 自增的进步值,默认为1 @return bool
entailment
private function getFileName($key) { $md5Key = md5($this->conf['prefix'] . $key); $dir = $this->conf['CACHE_PATH'] . substr($key, 0, strrpos($key, '/')) . DIRECTORY_SEPARATOR; $dir .= substr($md5Key, 0, 2) . DIRECTORY_SEPARATOR . substr($md5Key, 2, 2); is_dir($dir) || mkdir($dir, 07...
获取缓存文件名 @param string $key 缓存名 @return string
entailment
public function log($level, $message, array $context = []) { $db = Config::get('db_log_use_db', 'default_db'); $table = Config::get('db_log_use_table', 'cmlphp_log'); $tablePrefix = Config::get('db_log_use_tableprefix', null); if ($level === self::EMERGENCY) {//致命错误记文件一份,防止db挂掉什么信息都...
任意等级的日志记录 @param mixed $level 日志等级 @param string $message 要记录到log的信息 @param array $context 上下文信息 @return null
entailment
public function fatalError(&$error) { if (!Cml::$debug) { //正式环境 只显示‘系统错误’并将错误信息记录到日志 Log::emergency('fatal_error', [$error]); $error = []; $error['message'] = Lang::get('_CML_ERROR_'); } else { $error['exception'] = 'Fatal Error'; ...
致命错误捕获 @param array $error 错误信息
entailment
public function appException(&$e) { $error = []; $exceptionClass = new \ReflectionClass($e); $error['exception'] = '\\' . $exceptionClass->name; $error['message'] = $e->getMessage(); $trace = $e->getTrace(); foreach ($trace as $key => $val) { $error['files...
自定义异常处理 @param mixed $e 异常对象
entailment
public function execute(array $args, array $options = []) { $rootDir = null; if (isset($options['root-dir']) && !empty($options['root-dir'])) { $rootDir = $options['root-dir']; } StaticResource::createSymbolicLink($rootDir); }
命令的入口方法 @param array $args 传递给命令的参数 @param array $options 传递给命令的选项
entailment
public function setBarcode($code, $type) { $mode = explode(',', $type); $qrtype = strtoupper($mode[0]); switch ($qrtype) { case 'QRCODE': { // QR-CODE require_once(dirname(__FILE__).'/qrcode.php'); if (!isset($mode[1]) OR (!in_array($mode[1],array('L','M','Q','H')))) { $mode[1] = 'L'; // Ddefault:...
Set the barcode. @param string $code code to print @param string $type type of barcode: <ul><li>RAW: raw mode - comma-separad list of array rows</li><li>RAW2: raw mode - array rows are surrounded by square parenthesis.</li><li>QRCODE : QR-CODE Low error correction</li><li>QRCODE,L : QR-CODE Low error correction</li><li...
entailment
public function execute(array $args, array $options = []) { $this->bootstrap($args, $options); $version = isset($options['target']) ? $options['target'] : $options['t']; $date = isset($options['date']) ? $options['date'] : $options['d']; // run the migrations $start = micro...
运行迁移 @param array $args 参数 @param array $options 选项 @return int
entailment
public function addField($type, $mandatory, $defaultValue = '', $name = '') { $this->fields[$type] = array( 'name' => $name, 'mandatory' => $mandatory, 'defaultValue' => $defaultValue, ); }
Define a new field of the payment page @param string $type the type of field can be: title, forename, surname, company, street, postcode, place, phone, country, email, date_of_birth, terms, custom_field_1, custom_field_2, custom_field_3, custom_field_4, custom_field_5 @param boolean $mandatory TRUE if the field has to...
entailment
public static function createSymbolicLink($rootDir = null) { $isCli = Request::isCli(); is_null($rootDir) && $rootDir = CML_PROJECT_PATH . DIRECTORY_SEPARATOR . 'public'; is_dir($rootDir) || mkdir($rootDir, true, 0700); if ($isCli) { Output::writeln(Colour::colour('crea...
生成软链接 @param null $rootDir 站点静态文件根目录默认为项目目录下的public目录
entailment
public static function parseResourceUrl($resource = '', $echo = true) { //简单判断没有.的时候当作是目录不加版本号 $resource = ltrim($resource, '/'); $isDir = strpos($resource, '.') === false ? true : false; if (Cml::$debug) { $file = Response::url("cmlframeworkstaticparse/{$resource}", fals...
解析一个静态资源的地址 @param string $resource 文件地址 @param bool $echo 是否输出 true输出 false return @return mixed
entailment
public static function parseResourceFile() { if (Cml::$debug) { $file = ''; $pathInfo = Route::getPathInfo(); array_shift($pathInfo); if (isset($pathInfo[0]) && $pathInfo[0] == 'cmlphpstatic') { array_shift($pathInfo); $file = ...
解析一个静态资源的内容
entailment
private static function message($message = '') { $message = sprintf("%s %d %d %s", date('Y-m-d H:i:s'), posix_getpid(), posix_getppid(), $message); Output::writeln(Colour::colour($message, Colour::GREEN)); }
向shell输出一条消息 @param string $message
entailment
private static function getPid() { if (!is_file(self::$pidFile)) { return 0; } $pid = intval(file_get_contents(self::$pidFile)); return $pid; }
获取进程id @return int
entailment
protected static function setProcessName($title) { $title = "cmlphp_daemon_{$title}"; if (function_exists('cli_set_process_title')) { cli_set_process_title($title); } elseif (extension_loaded('proctitle') && function_exists('setproctitle')) { setproctitle($title); ...
设置进程名称 @param $title
entailment
private static function demonize() { php_sapi_name() != 'cli' && die('should run in cli'); umask(0); $pid = pcntl_fork(); if ($pid < 0) { die("can't Fork!"); } else if ($pid > 0) { exit(); } if (posix_setsid() === -1) {//使进程成为会话组长。让进程...
初始化守护进程
entailment
private static function setUser($name) { $result = false; if (empty($name)) { return true; } $user = posix_getpwnam($name); if ($user) { $uid = $user['uid']; $gid = $user['gid']; $result = posix_setuid($uid); posix_s...
设置运行的用户 @param string $name @return bool
entailment
private static function signReload() { $pid = self::getPid(); if ($pid == posix_getpid()) { $status = self::getStatus(); foreach ($status['pid'] as $cid) { posix_kill($cid, SIGUSR1); } $status['pid'] = []; file_put_contents(...
reload
entailment
private static function signStop() { $pid = self::getPid(); if ($pid == posix_getpid()) { $status = self::getStatus(); foreach ($status['pid'] as $cid) { posix_kill($cid, SIGINT); } sleep(3); unlink(self::$pidFile); ...
stop
entailment
public static function addTask($task, $frequency = 60) { self::initEvn(); $frequency < 1 || $frequency = 60; $task || self::message('task is empty'); $status = self::getStatus(); isset($status['task']) || $status['task'] = []; $key = md5($task); isset($st...
添加任务 @param string $task 任务的类名带命名空间 @param int $frequency 执行的频率 @return void
entailment
public static function start() { self::initEvn(); if (self::getPid() > 0) { self::message('already running...'); } else { self::message('starting...'); self::demonize(); } }
开始运行
entailment
public static function getStatus($showInfo = false) { self::initEvn(); $status = is_file(self::$status) ? Cml::requireFile(self::$status) : []; if (!$showInfo) { return $status; } if (self::getPid() > 0) { self::message('is running'); sel...
检查脚本运气状态 @param bool $showInfo 是否直接显示状态 @return array|void
entailment
private static function initEvn() { if (!self::$pidFile) { self::$pidFile = Cml::getApplicationDir('global_store_path') . DIRECTORY_SEPARATOR . 'DaemonProcess_.pid'; self::$log = Cml::getApplicationDir('global_store_path') . DIRECTORY_SEPARATOR . 'DaemonProcess_.log'; sel...
初始化环境
entailment
public static function run($cmd) { self::initEvn(); $param = is_array($cmd) && count($cmd) == 2 ? $cmd[1] : $cmd; switch ($param) { case 'start': self::start(); break; case 'stop': self::stop(); break; ...
shell参数处理并启动守护进程 @param string $cmd
entailment
protected static function createChildrenProcess() { $pid = pcntl_fork(); if ($pid > 0) { $status = self::getStatus(); $status['pid'][$pid] = $pid; isset($status['task']) || $status['task'] = []; file_put_contents(self::$status, '<?php return ' . var_e...
创建一个子进程
entailment
public static function createFile($filename) { if (is_file($filename)) return false; self::createDir(dirname($filename)); //创建目录 return file_put_contents($filename,''); }
创建空文件 @param string $filename 需要创建的文件 @return mixed
entailment
public static function writeFile($filename, $content, $type = 1) { if ($type == 1) { is_file($filename) && self::delFile($filename); //删除文件 self::createFile($filename); self::writeFile($filename, $content, 2); return true; } else { if (!is_...
写文件 @param string $filename 文件名称 @param string $content 写入文件的内容 @param int $type 类型,1=清空文件内容,写入新内容,2=再内容后街上新内容 @return bool
entailment
public static function copyFile($filename, $newfilename) { if (!is_file($filename) || !is_writable($filename)) return false; self::createDir(dirname($newfilename)); //创建目录 return copy($filename, $newfilename); }
拷贝一个新文件 @param string $filename 文件名称 @param string $newfilename 新文件名称 @return bool
entailment
public static function moveFile($filename, $newfilename) { if (!is_file($filename) || !is_writable($filename)) return false; self::createDir(dirname($newfilename)); //创建目录 return rename($filename, $newfilename); }
移动文件 @param string $filename 文件名称 @param string $newfilename 新文件名称 @return bool
entailment
public static function getFileInfo($filename) { if (!is_file($filename)) { return false; } return [ 'atime' => date("Y-m-d H:i:s", fileatime($filename)), 'ctime' => date("Y-m-d H:i:s", filectime($filename)), 'mtime' => date("Y-m-d H:i:s", filem...
获取文件信息 @param string $filename 文件名称 @return bool | array ['上次访问时间','inode 修改时间','取得文件修改时间','大小','类型']
entailment
public static function createDir($path) { if (is_dir($path)) return false; self::createDir(dirname($path)); mkdir($path); chmod($path, 0777); return true; }
创建目录 @param string $path 目录 @return bool
entailment
public static function delDir($path) { $succeed = true; if (is_dir($path)){ $objDir = opendir($path); while (false !== ($fileName = readdir($objDir))){ if (($fileName != '.') && ($fileName != '..')){ chmod("$path/$fileName", 0777); ...
删除目录 @param string $path 目录 @return bool
entailment
public static function getImageInfo($image) { $imagesInfoArr = @getimagesize($image); if (!$imagesInfoArr) return false; list($imagesInfo['width'], $imagesInfo['height'], $imagesInfo['ext']) = $imagesInfoArr; $imagesInfo['ext'] = strtolower(ltrim(image_type_to_extension($imagesInfo['...
取得图像信息 @access public @param string $image 图像文件名 @return array | false
entailment
public static function addWaterMark($sourceImage, $waterMarkImage, $saveName = null, $alpha = 80, $positionW = null, $positionH = null, $quality = 100) { if (!is_file($sourceImage) || !is_file($waterMarkImage)) return false; //获取图片信息 $sourceImageInfo = self::getImageInfo($sourceImage); ...
图片打水印 @param string $sourceImage 源图片 @param string $waterMarkImage 水印 @param null|string $saveName 保存路径,默认为覆盖原图 @param int $alpha 水印透明度 @param null $positionW 水印位置 相对原图横坐标 @param null $positionH 水印位置 相对原图纵坐标 @param int $quality 生成的图片的质量 jpeg有效 @return mixed
entailment
public static function makeThumb($image, $thumbName, $type = null, $width = 100, $height = 50, $isAutoFix = true) { is_dir(dirname($thumbName)) || mkdir(dirname($thumbName), 0700, true); $imageInfo = self::getImageInfo($image); if (!$imageInfo) return false; $type = is_null($type) ?...
生成缩略图 @param string $image 要缩略的图 @param string $thumbName 生成的缩略图的路径 @param null $type 要生成的图片类型 默认跟原图一样 @param int $width 缩略图的宽度 @param int $height 缩略图的高度 @param bool $isAutoFix 是否按比例缩放 @return false|string
entailment
public function showSearchResultsAction(Request $request) { $response = new Response(); $searchText = ''; $searchCount = 0; // Creating a form using Symfony's form component $simpleSearch = new SimpleSearch(); $form = $this->createForm($this->get('ezdemo.form.type.si...
Displays the simple search page. @param Request $request @return Response
entailment
public function searchBoxAction() { $response = new Response(); $simpleSearch = new SimpleSearch(); $form = $this->createForm($this->get('ezdemo.form.type.simple_search'), $simpleSearch); return $this->render( 'eZDemoBundle::page_header_searchbox.html.twig', ...
Displays the search box for the page header. @return Response HTML code of the page
entailment
public function fatalError(&$error) { if (Cml::$debug) { $run = new Run(); $run->pushHandler(Request::isCli() ? new PlainTextHandler() : new PrettyPageHandler()); $run->handleException(new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $...
致命错误捕获 @param array $error 错误信息
entailment
public function appException(&$e) { if (Cml::$debug) { $run = new Run(); $run->pushHandler(Request::isCli() ? new PlainTextHandler() : new PrettyPageHandler()); $run->handleException($e); } else { $error = []; $error['message'] = $e->getMes...
自定义异常处理 @param mixed $e 异常对象
entailment
public static function junctionTable($name, $tables) { sort($tables); $tables = implode('_', $tables); if ($name === $tables) { return true; } return false; }
@param $name @param $tables @return bool
entailment
public function requestApi($apiUrl, $params = array(), $method = 'POST') { $curlOpts = array( CURLOPT_URL => $apiUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_USERAGENT => 'payrexx-php/1.0.0', CURLOPT_SSL_VERIFYPEER...
{@inheritdoc}
entailment
public function bind($abstract, $concrete = null, $singleton = false) { if (is_array($abstract)) { list($abstract, $alias) = [key($abstract), current($abstract)]; $this->alias($abstract, $alias); } $abstract = $this->filter($abstract); $concrete = $this->filt...
绑定服务 @param mixed $abstract 要绑定的服务,传数组的时候则设置别名 @param mixed $concrete 实际执行的服务 @param bool $singleton 是否为单例 @return $this
entailment
public function make($abstract, $parameters = []) { if ($alias = $this->getAlias($abstract)) { $abstract = $alias; } if (isset($this->instances[$abstract])) { return $this->instances[$abstract]; } if (!isset($this->binds[$abstract])) { th...
实例化服务 @param mixed $abstract 服务的名称 @param mixed $parameters 参数 @return mixed
entailment
public static function filterScript($value, $clear = false) { $value = preg_replace("/javascript:/i", $clear ? '' : "&111", $value); $value = preg_replace("/(javascript:)?on(click|load|key|mouse|error|abort|move|unload|change|dblclick|move|reset|resize|submit)/i", $clear ? '' : "&111n\\2", $value); ...
过滤javascript,css,iframes,object等标签 @param string $value 需要过滤的值 @param bool $clear 转义还是删除 @return mixed
entailment
public static function filterStr($value) { $value = str_replace(["\0", "%00", "\r"], '', $value); $value = preg_replace(['/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/', '/&(?!(#[0-9]+|[a-z]+);)/is'], ['', '&amp;'], $value); $value = str_replace(["%3C", '<'], '&lt;', $value); $value = str_rep...
过滤特殊字符 @param string $value 需要过滤的值 @return mixed
entailment
public static function filterAll(&$var) { if (is_array($var)) { foreach ($var as &$v) { self::filterAll($v); } } else { $var = addslashes($var); $var = self::filterStr($var); $var = self::filterSql($var); } r...
/* 加强型过滤 @param $value @return mixed
entailment
public static function checkCsrf($type = 1) { if ($type !== 0 && isset($_SERVER['HTTP_REFERER']) && !strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])) { if ($type == 1) { if (!empty($_POST)) { Response::sendHttpStatus(403); throw new...
防止csrf跨站攻击 @param int $type 检测类型 0不检查,1、只检查post,2、post get都检查
entailment
public static function checkToken() { $token = Input::postString('CML_TOKEN'); if (empty($token)) return false; if ($token !== self::getToken()) return false; unset($_COOKIE['CML_TOKEN']); return true; }
类加载-检测token值 @return bool
entailment
public static function setToken() { if (!isset($_COOKIE['CML_TOKEN']) || empty($_COOKIE['CML_TOKEN'])) { $str = substr(md5(Cml::$nowTime . Request::getService('HTTP_USER_AGENT')), 5, 8); setcookie('CML_TOKEN', $str, null, '/'); $_COOKIE['CML_TOKEN'] = $str; } ...
类加载-设置全局TOKEN,防止CSRF攻击 @return void
entailment
public function config($enCoding, $boolean, $title, $filename = '') { if (func_num_args() == 3) { $filename = $title; $title = $boolean; } //编码 $this->coding = $enCoding; //表标题 $title = preg_replace('/[\\\|:|\/|\?|\*|\[|\]]/', '', $title); ...
Excel基础配置 @param string $enCoding 编码 @param bool|string $boolean 转换类型 @param string $title 表标题 @param string $filename Excel文件名 @return void
entailment
public function excelXls($data) { header("Content-Type: application/vnd.ms-excel; charset=" . $this->coding); header('Content-Disposition: attachment; filename="' . rawurlencode($this->filename . ".xls") . '"'); echo sprintf($this->header, $this->coding, $this->tWorksheetTitle); echo...
生成Excel文件 @param array $data @return void
entailment