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 { $plugin = new $key(); $callBack = [$plugin, $val]; } $return = call_user_func_array($callBack, array_slice(func_get_args(), 1)); if (!is_null($return)) { return $return; } } } return null; }
执行插件 @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; } return $this; }
添加一个模板替换规则 @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($file); if (!is_readable($tplFile)) { throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $tplFile)); } if (!is_file($cacheFile)) { if ($type !== 1 && !is_null($this->layout)) { if (!is_readable($this->layout)) { throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $this->layout)); } } $this->compile($tplFile, $cacheFile, $type); return $cacheFile; } $compile = false; $tplMtime = filemtime($tplFile); $cacheMtime = filemtime($cacheFile); if ($cacheMtime && $tplMtime) { ($cacheMtime < $tplMtime) && $compile = true; } else {//获取mtime失败 $compile = true; } if ($compile && $type !== 1 && !is_null($this->layout)) { if (!is_readable($this->layout)) { throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $this->layout)); } } //当子模板未修改时判断布局模板是否修改 if (!$compile && $type !== 1 && !is_null($this->layout)) { if (!is_readable($this->layout)) { throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $this->layout)); } $layoutMTime = filemtime($this->layout); if ($layoutMTime) { $cacheMtime < $layoutMTime && $compile = true; } else { $compile = true; } } $compile && $this->compile($tplFile, $cacheFile, $type); } return $cacheFile; }
获取模板文件缓存 @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) { /* 去除html空格与换行 */ $find = ['~>\s+<~', '~>(\s+\n|\r)~']; $replace = ['><', '>']; $template = preg_replace($find, $replace, $template); $template = str_replace('?><?php', '', $template); } //添加 头信息 $template = '<?php if (!class_exists(\'\Cml\View\')) die(\'Access Denied\');?>' . $template; if (!$cacheFile) { return $template; } //写入缓存文件 $this->makePath($cacheFile); file_put_contents($cacheFile, $template, LOCK_EX); return true; }
对模板文件进行缓存 @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->options['leftDelimiter'] . 'to\s+([a_zA-Z]+?)' . $this->options['rightDelimiter'] . '(.*?)' . $this->options['leftDelimiter'] . '\/to' . $this->options['rightDelimiter'] . '#is', $tplCon, $tmpl ); $tplCon = null; if ($presult > 0) { array_shift($tmpl); } //保存子模板提取完的区块内容 for ($i = 0; $i < $presult; $i++) { $this->layoutBlockData[$tmpl[0][$i]] = $tmpl[1][$i]; } $presult = null; //将子模板内容替换到布局文件返回 $layoutBlockData = &$this->layoutBlockData; $layoutCon = preg_replace_callback( '#' . $this->options['leftDelimiter'] . 'block\s+([a_zA-Z]+?)' . $this->options['rightDelimiter'] . '(.*?)' . $this->options['leftDelimiter'] . '\/block' . $this->options['rightDelimiter'] . '#is', function ($matches) use ($layoutBlockData) { array_shift($matches); if (isset($layoutBlockData[$matches[0]])) { //替换{parent}标签并返回 return str_replace( $this->options['rightDelimiter'] . 'parent' . $this->options['rightDelimiter'], $matches[1], $layoutBlockData[$matches[0]] ); } else { return ''; } }, $layoutCon ); unset($layoutBlockData); $this->layoutBlockData = []; return $layoutCon;//返回替换完的布局文件内容 } else { return file_get_contents($tplFile); } }
获取模板文件内容 使用布局的时候返回处理完的模板 @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_SEPARATOR . Config::get('html_theme') : ''); if ($templateFile === '') { $baseDir .= '/' . Cml::getContainer()->make('cml_route')->getControllerName() . '/'; $file = Cml::getContainer()->make('cml_route')->getActionName(); } else { $templateFile = str_replace('.', '/', $templateFile); $baseDir .= DIRECTORY_SEPARATOR . dirname($templateFile) . DIRECTORY_SEPARATOR; $file = basename($templateFile); } $options = [ 'templateDir' => Cml::getApplicationDir('apps_path') . DIRECTORY_SEPARATOR . $baseDir, //指定模板文件存放目录 'cacheDir' => Cml::getApplicationDir('runtime_cache_path') . DIRECTORY_SEPARATOR . $baseDir, //指定缓存文件存放目录 'autoUpdate' => true, //当模板修改时自动更新缓存 ]; $this->setHtmlEngineOptions($options); return $file; }
初始化目录 @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 = $this->getTplFile($doNotSetDir ? $templateFile : $this->initBaseDir($templateFile, $inOtherApp)); if (!is_readable($tplFile)) { throw new FileCanNotReadableException(Lang::get('_TEMPLATE_FILE_NOT_FOUND_', $tplFile)); } empty($this->args) || extract($this->args, EXTR_PREFIX_SAME, "xxx"); $return = $this->compile($tplFile, false, 0); eval('?>' . $return . '<?php '); } else { Cml::requireFile($this->getFile(($doNotSetDir ? $templateFile : $this->initBaseDir($templateFile, $inOtherApp))), $this->args); } $this->args = []; $this->reset(); return ob_get_clean(); }
渲染模板获取内容 调用内置的模板引擎显示方法, @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()) . DIRECTORY_SEPARATOR . Cml::getApplicationDir('app_view_path_name') . DIRECTORY_SEPARATOR . (Config::get('html_theme') != '' ? Config::get('html_theme') . DIRECTORY_SEPARATOR : '') . 'layout' . DIRECTORY_SEPARATOR . $layout . Config::get('html_template_suffix'); $this->display($templateFile, $tplInOtherApp); }
使用布局模板并渲染 @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['force'] : $options['f']; // rollback the specified environment $start = microtime(true); if (null !== $date) { $this->getManager()->rollbackToDateTime(new \DateTime($date), $force); } else { $this->getManager()->rollback($version, $force); } $end = microtime(true); Output::writeln(''); Output::writeln(Colour::colour('All Done. Took ', Colour::GREEN) . sprintf('%.4fs', $end - $start)); }
回滚迁移 @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($onCurrentApp) ? $onCurrentApp : (Config::get('route_app_hierarchy', 1) < 1 ? true : false); $config = Config::load('api', $app); foreach ($config['version'] as $version => $apiList) { isset($result[$version]) || $result[$version] = []; foreach ($apiList as $model => $api) { $pos = strrpos($api, '\\'); $controller = substr($api, 0, $pos); $action = substr($api, $pos + 1); if (class_exists($controller) === false) { continue; } $annotationParams = self::getAnnotationParams($controller, $action); empty($annotationParams) || $result[$version][$model] = $annotationParams; } } foreach ($result as $key => $val) { if (count($val) < 1) { unset($result[$key]); } } //$systemCode = Cml::requireFile(__DIR__ . DIRECTORY_SEPARATOR . 'resource' . DIRECTORY_SEPARATOR . 'code.php'); if ($render) { View::getEngine('Html')->assign(['config' => $config, 'result' => $result]); Cml::showSystemTemplate(__DIR__ . DIRECTORY_SEPARATOR . 'resource' . DIRECTORY_SEPARATOR . $theme . '.html'); return true; } else { return ['config' => $config, 'result' => $result]; } }
从注释解析生成文档 @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) { $annotation = $method->getDocComment(); if (strpos($annotation, '@doc') !== false) { //$result[$version][$model]['all'] = $annotation; //描述 preg_match('/@desc([^\n]+)/', $annotation, $desc); $result['desc'] = isset($desc[1]) ? trim($desc[1]) : ''; //参数 preg_match_all('/@param([^\n]+)/', $annotation, $params); foreach ($params[1] as $key => $val) { $tmp = explode(' ', preg_replace('/\s(\s+)/', ' ', trim($val))); isset($tmp[3]) || $tmp[3] = 'N'; substr($tmp[1], 0, 1) == '$' && $tmp[1] = substr($tmp[1], 1); $result['params'][] = $tmp; } //请求示例 preg_match('/@req(.+?)(\*\s*?@|\*\/)/s', $annotation, $reqEg); $result['req'] = isset($reqEg[1]) ? self::formatCode($reqEg[1]) : ''; //请求成功示例 preg_match('/@success(.+?)(\*\s*?@|\*\/)/s', $annotation, $success); $result['success'] = isset($success[1]) ? self::formatCode($success[1]) : ''; //请求失败示例 preg_match('/@error(.+?)(\*\s*?@|\*\/)/s', $annotation, $error); $result['error'] = isset($error[1]) ? self::formatCode($error[1]) : ''; } } } return $result; }
解析获取某控制器注释参数信息 @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 = strpos($line, '#'); $wordLine = $pos === false ? $line : trim(substr($line, 0, $pos)); $firstWord = substr($wordLine, 0, 1); $lastWord = substr($wordLine, -1); $lineNum === 0 && $line !== '{' && $line = "{\n " . substr($line, 1); //本行就要减空格 if ( $firstWord === '}'//行首 || $firstWord === ']' //行首 || ($lastWord === '}' && false === strpos($line, '{')) || ($lastWord === ']' && false === strpos($line, '[')) ) { --$dep; } $line = str_pad("", $dep * 4, " ", STR_PAD_LEFT) . $line; //下一行加空格 if ( $lastWord === '{' || $lastWord === '[' || ($firstWord === '{' && false === strpos($line, '}')) || ($firstWord === '[' && false === strpos($line, ']')) ) { ++$dep; } } return implode("\n", $code); }
格式化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) ) { return true; } $driverType = Model::getInstance()->cache($this->useCache)->getDriverType(); if ($driverType === 1) { //memcached $isLock = Model::getInstance()->cache($this->useCache)->getInstance()->add($key, (string)Cml::$nowMicroTime, $this->expire); } else {//memcache $isLock = Model::getInstance()->cache($this->useCache)->getInstance()->add($key, (string)Cml::$nowMicroTime, 0, $this->expire); } if ($isLock) { $this->lockCache[$key] = (string)Cml::$nowMicroTime; return true; } //非堵塞模式 if (!$wouldBlock) { return false; } //堵塞模式 do { usleep(200); if ($driverType === 1) { //memcached $isLock = Model::getInstance()->cache($this->useCache)->getInstance()->add($key, (string)Cml::$nowMicroTime, $this->expire); } else {//memcache $isLock = Model::getInstance()->cache($this->useCache)->getInstance()->add($key, (string)Cml::$nowMicroTime, 0, $this->expire); } } while (!$isLock); $this->lockCache[$key] = (string)Cml::$nowMicroTime; return true; }
上锁 @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; } elseif ( is_array($data) && $template_html == null ) { return $this->htmlBody = implode('<br> ', $data); } else { $templatePath = ($this->TemplateFolder) ? $this->TemplateFolder . '/' . $template_html : $template_html; // Support load different path to views available in CI v3.0 if ( defined('VIEWPATH') ) { $views_path = VIEWPATH; } else { $views_path = APPPATH .'views/'; } if ( !file_exists( $views_path . $templatePath ) ) { log_message('error','setEmailBody() HTML template file not found: ' . $template_html); return $this->htmlBody = 'Template ' . ($template_html) . ' not found.'; //'none template message found in: ' .$template_html; } else { $this->htmlBody = $this->CI->load->view($templatePath, '', true); if ( preg_match('/\.txt$/', $template_html) ) { $this->textBody = $this->htmlBody; } else { $templateTextPath = preg_replace('/\.[html|php|htm]+$/', '.txt', $templatePath); if ( file_exists( $views_path . $templateTextPath ) ) { $this->textBody = $this->CI->load->view($templateTextPath, '', true); } } } $data = (is_array($data)) ? $data : array($data); $data = array_merge($data, $this->TemplateOptions); if ( $format == 'HTML' ) { foreach ($data as $key => $value) { $this->htmlBody = str_replace("{".$key."}", "".$value."", $this->htmlBody); $this->textBody = str_replace("{".$key."}", "".$value."", $this->textBody); } } elseif ( $format == 'TEXT' ) { $this->isHTML = false; $this->textBody = @vsprintf($this->textBody, $data); } } }
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 key KEY_NAME found in your array to your HTML {KEY_NAME}. Other optional ways to format the mail body is available like instead of a template the param $data can be set as an array or string, but param $template_html must be equal to null @update 2014-04-01 01:46 @author Adriano Rosa (http://adrianorosa.com) @param mixed $data [array|string] that contain the values to be parsed in mail body @param string $template_html the external html template filename , OR the message as HMTL string @param string $format [HTML|TEXT] @return string
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->addBcc($this->mail_bcc) : false; # mailer set CC ( $this->setCc ) ? $this->addCc($this->mail_cc) : false; # mailer send TO --> If $mailto is null by default the replyTo config mail value will be used instead if ( is_null($mailto) ) { $this->addAddress($this->replyto_mail, $this->replyto_name); } else { ( is_array($mailto) ) ? $this->addAddress($mailto[0], $mailto[1]) : $this->addAddress($mailto, $mailtoName); } # mailer message subject $this->Subject = $subject; # mailer line wrap for text/plain format: see RFC 2646; $this->WordWrap = 72; if ( !$this->isHTML ) { # format only plain/text format $this->isHTML(false); $this->Body = $this->textBody; } else { # format message as HTML and alternatively text/plain for # those Email Client that do not support HTML format such as Eudora $this->msgHTML($this->htmlBody); # If it is set a template.txt file, its contents will be parsed instead # of strip html tags form the content HTML body # the use of plain-text as template might be better than just let the html be stripped to # a text format wich can get some break lines and undesirable message body if ( $this->textBody ) { $this->AltBody = $this->formatHtml2Text($this->textBody); } else { $this->AltBody = $this->formatHtml2Text($this->AltBody); } } # to debug the message body in browser set # config mail_debug to 'local' in mail_config file $this->local_debug(); if (!$this->send()) { log_message('error','PHPMailer Error : mail address --> ' . $mailto); return false; } else { return true; } }
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 by $mailto as long as it is not an array @return bool
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 use CamelCase format.', $className )); } // get the migration path from the config $path = $this->getConfig()->getMigrationPath(); if (!is_dir($path)) { $ask = new Dialog(); if ($ask->confirm(Colour::colour('Create migrations directory?', [Colour::RED, Colour::HIGHLIGHT]))) { mkdir($path, 0755, true); } } $this->verifyMigrationDirectory($path); $path = realpath($path); if (!Util::isUniqueMigrationClassName($className, $path)) { throw new \InvalidArgumentException(sprintf( 'The migration class name "%s" already exists', $className )); } // Compute the file path $fileName = Util::mapClassNameToFileName($className); $filePath = $path . DIRECTORY_SEPARATOR . $fileName; if (is_file($filePath)) { throw new \InvalidArgumentException(sprintf( 'The file "%s" already exists', $filePath )); } // Get the alternative template and static class options from the command line, but only allow one of them. $altTemplate = $options['template']; $creationClassName = $options['class']; if ($altTemplate && $creationClassName) { throw new \InvalidArgumentException('Cannot use --template and --class at the same time'); } // Verify the alternative template file's existence. if ($altTemplate && !is_file($altTemplate)) { throw new \InvalidArgumentException(sprintf( 'The alternative template file "%s" does not exist', $altTemplate )); } if ($creationClassName) { // Supplied class does not exist, is it aliased? if (!class_exists($creationClassName)) { throw new \InvalidArgumentException(sprintf( 'The class "%s" does not exist', $creationClassName )); } // Does the class implement the required interface? if (!is_subclass_of($creationClassName, self::CREATION_INTERFACE)) { throw new \InvalidArgumentException(sprintf( 'The class "%s" does not implement the required interface "%s"', $creationClassName, self::CREATION_INTERFACE )); } } // Determine the appropriate mechanism to get the template if ($creationClassName) { // Get the template from the creation class $creationClass = new $creationClassName(); $contents = $creationClass->getMigrationTemplate(); } else { // Load the alternative template if it is defined. $contents = file_get_contents($altTemplate ?: $this->getMigrationTemplateFilename()); } // inject the class names appropriate to this migration $classes = [ '$useClassName' => $this->getConfig()->getMigrationBaseClassName(false), '$className' => $className, '$version' => Util::getVersionFromFileName($fileName), '$baseClassName' => $this->getConfig()->getMigrationBaseClassName(true), ]; $contents = strtr($contents, $classes); if (false === file_put_contents($filePath, $contents)) { throw new \RuntimeException(sprintf( 'The file "%s" could not be written to', $path )); } // Do we need to do the post creation call to the creation class? if ($creationClassName) { $creationClass->postMigrationCreation($filePath, $className, $this->getConfig()->getMigrationBaseClassName()); } Output::writeln('using migration base class ' . Colour::colour($classes['$useClassName'], Colour::GREEN)); if (!empty($altTemplate)) { Output::writeln('using alternative template ' . Colour::colour($altTemplate, Colour::GREEN)); } elseif (!empty($creationClassName)) { Output::writeln('using template creation class ' . Colour::colour($creationClassName, Colour::GREEN)); } else { Output::writeln('using default template'); } Output::writeln('created ' . str_replace(Cml::getApplicationDir('secure_src'), '{secure_src}', $filePath)); }
创建一个迁移 @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->foregroundColors = $options['foregroundColors']; } if (isset($options['backgroundColors'])) { $this->backgroundColors = $options['backgroundColors']; } return $this; }
设置参数 @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_path') : Cml::getApplicationDir('apps_path') . '/' . ($global === false ? Cml::getContainer()->make('cml_route')->getAppName() : $global) . '/' . Cml::getApplicationDir('app_config_path_name') ) . '/' . ($global === true ? self::$isLocal . DIRECTORY_SEPARATOR : '') . $file . '.php'; if (!is_file($filePath)) { throw new ConfigNotFoundException(Lang::get('_NOT_FOUND_', $filePath)); } static::$_content[$global . $file] = Cml::requireFile($filePath); return static::$_content[$global . $file]; } }
从文件载入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->writeln($format->format("input 'command [options] [args]' to run command or input 'help command ' to display command help info")); $this->writeln(''); $options = $this->formatOptions(); $cmdList = $this->formatCommand(); $this->writeln("Options:"); $this->formatEcho($format, $options); $this->writeln(''); $this->writeln('Available commands:'); $this->formatEcho($format, $cmdList[0]); $this->formatEcho($format, $cmdList[1]); } else { $class = new \ReflectionClass($this->console->getCommand($args[0])); $property = $class->getDefaultProperties(); $description = isset($property['description']) ? $property['description'] : ''; $help = isset($property['help']) ? $property['help'] : false; $arguments = isset($property['arguments']) ? $property['arguments'] : []; $options = isset($property['options']) ? $property['options'] : []; $this->writeln("Usage:"); $this->writeln($format->format("{$args[0]} [options] [args]")); $this->writeln(''); count($arguments) > 0 && $arguments = $this->formatArguments($arguments); $options = $this->formatOptions($options, 'this'); $this->writeln("Options:"); $this->formatEcho($format, $options); $this->writeln(''); if (count($arguments)) { $this->writeln("Arguments"); $this->formatEcho($format, $arguments); $this->writeln(''); } $this->writeln("Help:"); $this->writeln($format->format($help ? $help : $description)); } $this->write("\n"); }
执行命令入口 @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(); $property = isset($property['description']) ? $property['description'] : ''; $hadGroup = strpos($name, ':'); $group = substr($name, 0, $hadGroup); $name = Colour::colour($name, Colour::GREEN); $this->commandLength > strlen($name) || $this->commandLength = strlen($name) + 3; if ($hadGroup) { $cmdGroup[$group][$name] = $property; } else { $noGroup[$name] = $property; } } } return [$noGroup, $cmdGroup]; }
格式化命令 @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); $optionsDump = []; foreach ($dumpOptions as $name => $desc) { $name = Colour::colour($name, Colour::GREEN); $this->commandLength > strlen($name) || $this->commandLength = strlen($name) + 3; $optionsDump[$name] = $desc; } return $optionsDump; }
格式化选项 @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) || $argsLength = strlen($argument); } return $echoArguments; }
格式化参数 @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_repeat(' ', $this->commandLength - 2 - strlen($name)) . $desc)); } } else { $this->writeln($format->format($group . str_repeat(' ', $this->commandLength - strlen($group)) . $list)); } } }
格式化输出 @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), new Criterion\LanguageCode($languages), ) ); $query->performCount = false; $searchResults = $this->searchService->findContentInfo($query); return $this->searchHelper->buildListFromSearchResult($searchResults); }
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 Criterion\LogicalAnd( array( new Criterion\ContentTypeIdentifier($contentTypes), new Criterion\Subtree($location->pathString), new Criterion\LanguageCode($languages), new Criterion\MapLocationDistance( 'location', Criterion\Operator::BETWEEN, array( $this->placeListMinDist, $maxDist, ), $latitude, $longitude ), ) ); $query->sortClauses = $sortClauses; $query->performCount = false; $searchResults = $this->searchService->findContentInfo($query); return $this->searchHelper->buildListFromSearchResult($searchResults); }
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 @param string|string[] $contentTypes to be retrieved @param int $maxDist Maximum distance for the search in km @param array $sortClauses @param string|string[] $languages to be retrieved @return \eZ\Publish\API\Repository\Values\Content\Content[]
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'); \Cml\dumpUsePHPConsole(Debug::getTipInfo(), 'tipInfo'); \Cml\dumpUsePHPConsole(Debug::getIncludeFiles(), 'includeFile'); } else { if (isset($sql[0])) { $this->args['sql'] = implode($sql, ', '); } } } else { $deBugLogData = \Cml\dump('', 1); if (!empty($deBugLogData)) { Config::get('dump_use_php_console') ? \Cml\dumpUsePHPConsole($deBugLogData, 'debug') : $this->args['cml_debug_info'] = $deBugLogData; } } exit(json_encode($this->args, JSON_UNESCAPED_UNICODE) ?: json_last_error_msg()); }
输出数据
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 + $notOperationAutoLogin : 0, 'ssosign' => $sso ? (string)Cml::$nowMicroTime : self::$ssoSign ]; $notOperationAutoLogin > 0 && $user['not_op'] = $notOperationAutoLogin; //Cookie::set本身有一重加密 这里再加一重 if ($sso) { Model::getInstance()->cache()->set("SSOSingleSignOn{$uid}", $user['ssosign'], 86400 + $cookieExpire); } else { //如果是刚刚从要单点切换成不要单点。这边要把ssosign置为cache中的 empty($user['ssosign']) && $user['ssosign'] = Model::getInstance()->cache()->get("SSOSingleSignOn{$uid}"); } Cookie::set(Config::get('userauthid'), Encry::encrypt(json_encode($user, JSON_UNESCAPED_UNICODE), self::$encryptKey), $cookieExpire, $cookiePath, $cookieDomain); }
保存当前登录用户的信息 @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); if ( empty(self::$authUser) || (self::$authUser['expire'] > 0 && self::$authUser['expire'] < Cml::$nowTime) || self::$authUser['ssosign'] != Model::getInstance()->cache() ->get("SSOSingleSignOn" . self::$authUser['uid']) ) { self::$authUser = false; self::$ssoSign = ''; } else { self::$ssoSign = self::$authUser['ssosign']; $user = Model::getInstance(self::$tables['users'])->where('status', 1)->getByColumn(self::$authUser['uid']); if (empty($user)) { self::$authUser = false; } else { $authUser = [ 'id' => $user['id'], 'username' => $user['username'], 'nickname' => $user['nickname'], 'groupid' => array_values(array_filter(explode(self::$multiGroupDeper, trim($user['groupid'], self::$multiGroupDeper)), function($v) { return !empty($v); })), 'from_type' => $user['from_type'] ]; $authUser['groupname'] = Model::getInstance(self::$tables['groups'])->mapDbAndTable() ->whereIn('id', $authUser['groupid']) ->where('status', 1) ->plunk('name'); $authUser['groupname'] = implode(',', $authUser['groupname']); //有操作登录超时时间重新设置为expire时间 if (self::$authUser['expire'] > 0 && ( (self::$authUser['expire'] - Cml::$nowTime) < (self::$authUser['not_op'] / 2) ) ) { self::setLoginStatus($user['id'], false, 0, self::$authUser['not_op']); } unset($user, $group); self::$authUser = $authUser; } } } return self::$authUser; }
获取当前登录用户的信息 @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')->getFullPathNotContainSubDir(); $checkAction = Cml::getContainer()->make('cml_route')->getActionName(); if (is_string($controller)) { $checkUrl = trim($controller, '/\\'); $controller = str_replace('/', '\\', $checkUrl); $actionPosition = strrpos($controller, '\\'); $checkAction = substr($controller, $actionPosition + 1); $offset = $appPosition = 0; for ($i = 0; $i < Config::get('route_app_hierarchy', 1); $i++) { $appPosition = strpos($controller, '\\', $offset); $offset = $appPosition + 1; } $appPosition = $offset - 1; $subString = substr($controller, 0, $appPosition) . '\\' . Cml::getApplicationDir('app_controller_path_name') . substr($controller, $appPosition, $actionPosition - $appPosition); $controller = "\\{$subString}" . Config::get('controller_suffix'); if (class_exists($controller)) { $controller = new $controller; } else { return false; } } $checkUrl = ltrim(str_replace('\\', '/', $checkUrl), '/'); $origUrl = $checkUrl; if (is_object($controller)) { //判断是否有标识 @noacl 不检查权限 $reflection = new \ReflectionClass($controller); $methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { if ($method->name == $checkAction) { $annotation = $method->getDocComment(); if (strpos($annotation, '@noacl') !== false) { return true; } $checkUrlArray = []; if (preg_match('/@acljump([^\n]+)/i', $annotation, $aclJump)) { if (isset($aclJump[1]) && $aclJump[1]) { $aclJump[1] = explode('|', $aclJump[1]); foreach ($aclJump[1] as $val) { $val = trim($val); substr($val, 0, 3) == '../' && $val = '../' . $val; if ($times = preg_match_all('#\./#i', $val)) { $origUrlArray = explode('/', $origUrl); $val = explode('./', $val); for ($i = 0; $i < $times; $i++) { array_pop($origUrlArray); array_shift($val); } $val = implode('/', array_merge($origUrlArray, $val)); } $val && $checkUrlArray[] = ltrim(str_replace('\\', '/', trim($val)), '/') . self::$otherAclParams; } } empty($checkUrlArray) || $checkUrl = $checkUrlArray; } } } } $acl = Model::getInstance()->table([self::$tables['access'] => 'a']) ->join([self::$tables['menus'] => 'm'], 'a.menuid=m.id') ->_and(function ($model) use ($authInfo) { $model->whereIn('a.groupid', $authInfo['groupid']) ->_or() ->where('a.userid', $authInfo['id']); })->when(self::$otherAclParams, function ($model) { $model->where('m.params', self::$otherAclParams); })->when(is_array($checkUrl), function ($model) use ($checkUrl) { $model->whereIn('m.url', $checkUrl); }, function ($model) use ($checkUrl) { $model->where('m.url', $checkUrl); })->count('1'); return $acl > 0; }
检查对应的权限 @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.pid', 'm.title', 'm.url', 'm.params' . ($columns ? " ,{$columns}" : '')]) ->when(!self::isSuperUser(), function ($model) use ($authInfo) {//当前登录用户是否为超级管理员 $model->join([self::$tables['access'] => 'a'], 'a.menuid=m.id') ->_and(function ($model) use ($authInfo) { $model->whereIn('a.groupid', $authInfo['groupid']) ->_or() ->where('a.userid', $authInfo['id']); }); })->where('m.isshow', 1) ->orderBy('m.sort', 'DESC') ->orderBy('m.id', 'ASC') ->select(0, 5000); $res = $format ? Tree::getTreeNoFormat($result, 0) : $result; return $res; }
获取有权限的菜单列表 @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($fileName, 'r+'); if ($this->lock) {//自增自减 上锁 $this->lock = $fp; if (flock($fp, LOCK_EX) === false) return false; } $data = fread($fp, filesize($fileName)); $this->lock || fclose($fp);//非自增自减操作时关闭文件 if ($data === false) { return false; } //缓存过期 $fileTime = substr($data, 13, 10); $pos = strpos($data, ')'); $cacheTime = substr($data, 24, $pos - 24); $data = substr($data, $pos + 1); if ($cacheTime == 0) return unserialize($data); if (Cml::$nowTime > (intval($fileTime) + intval($cacheTime))) { unlink($fileName); return false;//缓存过期 } return unserialize($data); }
获取缓存 @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->lock); $this->lock = false; } else { $fileName = $this->getFileName($key); $return = file_put_contents($fileName, $value, LOCK_EX); } $return && clearstatcache(); return $return; }
写入缓存 @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) { if ('.' === $file || '..' === $file) continue; $tmp = $fullDir . DIRECTORY_SEPARATOR . $file; if (is_dir($tmp)) { $this->cleanDir($dir . DIRECTORY_SEPARATOR . $file); } else { unlink($tmp); } } rmdir($fullDir); return true; }
清空文件夹 @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, 0700, true); return $dir . DIRECTORY_SEPARATOR . $md5Key . '.php'; }
获取缓存文件名 @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挂掉什么信息都没有 $file = new File(); $file->log($level, $message, $context); } return Model::getInstance($table, $tablePrefix, $db)->set([ 'level' => $level, 'message' => $message, 'context' => json_encode($context, JSON_UNESCAPED_UNICODE), 'ip' => $_SERVER['SERVER_ADDR'] ?: '', 'ctime' => Cml::$nowTime ]); }
任意等级的日志记录 @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'; $error['files'][0] = [ 'file' => $error['file'], 'line' => $error['line'] ]; } if (Request::isCli()) { Output::writeException(sprintf("%s\n[%s]\n%s", isset($error['files']) ? implode($error['files'][0], ':') : '', 'Fatal Error', $error['message'])); } else { header('HTTP/1.1 500 Internal Server Error'); View::getEngine('html')->reset()->assign('error', $error); Cml::showSystemTemplate(Config::get('html_exception')); } }
致命错误捕获 @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'][$key] = $val; } if (substr($e->getFile(), -20) !== '\Tools\functions.php' || $e->getLine() !== 90) { array_unshift($error['files'], ['file' => $e->getFile(), 'line' => $e->getLine(), 'type' => 'throw']); } if (!Cml::$debug) { //正式环境 只显示‘系统错误’并将错误信息记录到日志 Log::emergency($error['message'], [$error['files'][0]]); $error = []; $error['message'] = Lang::get('_CML_ERROR_'); } if (Request::isCli()) { Output::writeException(sprintf("%s\n[%s]\n%s", isset($error['files']) ? implode($error['files'][0], ':') : '', get_class($e), $error['message'])); } else { header('HTTP/1.1 500 Internal Server Error'); View::getEngine('html')->reset()->assign('error', $error); Cml::showSystemTemplate(Config::get('html_exception')); } }
自定义异常处理 @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: Low error correction } $qrcode = new QRcode($code, strtoupper($mode[1])); $this->barcode_array = $qrcode->getBarcodeArray(); break; } case 'RAW': case 'RAW2': { // RAW MODE // remove spaces $code = preg_replace('/[\s]*/si', '', $code); if (strlen($code) < 3) { break; } if ($qrtype == 'RAW') { // comma-separated rows $rows = explode(',', $code); } else { // rows enclosed in square parethesis $code = substr($code, 1, -1); $rows = explode('][', $code); } $this->barcode_array['num_rows'] = count($rows); $this->barcode_array['num_cols'] = strlen($rows[0]); $this->barcode_array['bcode'] = array(); foreach ($rows as $r) { $this->barcode_array['bcode'][] = str_split($r, 1); } break; } case 'TEST': { // TEST MODE $this->barcode_array['num_rows'] = 5; $this->barcode_array['num_cols'] = 15; $this->barcode_array['bcode'] = array( array(1,1,1,0,1,1,1,0,1,1,1,0,1,1,1), array(0,1,0,0,1,0,0,0,1,0,0,0,0,1,0), array(0,1,0,0,1,1,0,0,1,1,1,0,0,1,0), array(0,1,0,0,1,0,0,0,0,0,1,0,0,1,0), array(0,1,0,0,1,1,1,0,1,1,1,0,0,1,0)); break; } default: { $this->barcode_array = false; } } }
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>QRCODE,M : QR-CODE Medium error correction</li><li>QRCODE,Q : QR-CODE Better error correction</li><li>QRCODE,H : QR-CODE Best error correction</li></ul> @return array
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 = microtime(true); if (null !== $date) { $this->getManager()->migrateToDateTime(new \DateTime($date)); } else { $this->getManager()->migrate($version); } $end = microtime(true); Output::writeln(''); Output::writeln(Colour::colour('All Done. Took ' . sprintf('%.4fs', $end - $start), Colour::CYAN)); return 0; }
运行迁移 @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 be filled out for payment @param string $defaultValue the default value. This value will be editable for the client. @param string $name the name of the field, (this is only available for the fields custom_field_\d
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('create link start!', [Colour::GREEN, Colour::HIGHLIGHT])); Output::writeln(Colour::colour(" ROOT DIR >>>> {$rootDir}", [Colour::WHITE])); } else { echo "<br />**************************create link start!*********************<br />"; echo " ROOT DIR >>>> {$rootDir} <br />"; } //modules_static_path_name // 递归遍历目录 $createDirFunc = function ($distDir, $resourceDir, $fileName) use ($isCli) { $cmd = Request::operatingSystem() ? "rd /Q {$distDir}" : "rm -rf {$distDir}"; exec($cmd); $cmd = Request::operatingSystem() ? "mklink /d {$distDir} {$resourceDir}" : "ln -s {$resourceDir} {$distDir}"; is_dir($distDir) || exec($cmd, $result); $tip = " create link Application [{$fileName}] result : [" . (is_dir($distDir) ? 'true' : 'false') . "]"; if ($isCli) { Output::writeln(Colour::colour($tip, [Colour::WHITE, Colour::HIGHLIGHT])); } else { print_r('|<span style="color:blue">' . str_pad($tip, 64, ' ', STR_PAD_BOTH) . '</span>|'); } }; //创建系统静态文件目录映射 /* $createDirFunc( $rootDir . DIRECTORY_SEPARATOR . 'cmlphpstatic', __DIR__ . DIRECTORY_SEPARATOR . 'Static', 'cmlphpstatic' );*/ $dirIteratorFunc = function ($dir, $parentDirName = '') use ($rootDir, $createDirFunc, &$dirIteratorFunc) { $dirIterator = new \DirectoryIterator($dir); foreach ($dirIterator as $file) { if (!$file->isDot() && $file->isDir()) { $resourceDir = $file->getPathname() . DIRECTORY_SEPARATOR . Cml::getApplicationDir('app_static_path_name'); $currentDirName = ltrim($parentDirName, DIRECTORY_SEPARATOR); $currentDirName .= ($currentDirName ? DIRECTORY_SEPARATOR : '') . $file->getFilename(); if (is_dir($resourceDir)) { if ($file->getFilename() != $currentDirName) { $parentDir = trim(substr($currentDirName, 0, strpos($currentDirName, $file->getFilename())), DIRECTORY_SEPARATOR); is_dir($rootDir . DIRECTORY_SEPARATOR . $parentDir) || mkdir($rootDir . DIRECTORY_SEPARATOR . $parentDir, 0700, true); } $distDir = $rootDir . DIRECTORY_SEPARATOR . $currentDirName; $createDirFunc($distDir, $resourceDir, $currentDirName); } /*else if (!is_dir($file->getPathname() . DIRECTORY_SEPARATOR . Cml::getApplicationDir('app_controller_path_name'))) { $dirIteratorFunc($file->getPathname(), $currentDirName); }*/ $dirIteratorFunc($file->getPathname(), $currentDirName);//找到resource了还是继续迭代子目录 } } }; $dirIteratorFunc(Cml::getApplicationDir('apps_path')); if ($isCli) { Output::writeln(Colour::colour('create link end!', [Colour::GREEN, Colour::HIGHLIGHT])); } else { echo("<br />****************************create link end!**********************<br />"); } }
生成软链接 @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}", false); if (Config::get('url_model') == 2) { $file = str_replace(Config::get('url_html_suffix'), '', $file); } $isDir || $file .= (Config::get("url_model") == 3 ? "&v=" : "?v=") . 0;//Cml::$nowTime; } else { $file = rtrim(Config::get("static__path", Cml::getContainer()->make('cml_route')->getSubDirName()), '/') . '/' . $resource; $isDir || $file .= "?v=" . Config::get('static_file_version'); } if ($echo) { echo $file; return ''; } else { return $file; } }
解析一个静态资源的地址 @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 = __DIR__ . DIRECTORY_SEPARATOR . 'Static' . DIRECTORY_SEPARATOR; $file .= trim(implode('/', $pathInfo), '/'); strpos($file, '.') || $file .= Config::get('url_html_suffix'); } else { $resource = implode('/', $pathInfo); $appName = ''; $i = 0; //$routeAppHierarchy = Config::get('route_app_hierarchy', 1); while (true) { $resource = ltrim($resource, '/'); $pos = strpos($resource, '/'); $appName = ($appName == '' ? '' : $appName . DIRECTORY_SEPARATOR) . substr($resource, 0, $pos); $resource = substr($resource, $pos); $file = Cml::getApplicationDir('apps_path') . DIRECTORY_SEPARATOR . $appName . DIRECTORY_SEPARATOR . Cml::getApplicationDir('app_static_path_name') . $resource; strpos($file, '.') || $file .= Config::get('url_html_suffix'); if (is_file($file) || ++$i > 15/*|| ++$i >= $routeAppHierarchy*/) { break; } } } if (is_file($file)) { Response::sendContentTypeBySubFix(substr($file, strrpos($file, '.') + 1)); exit(file_get_contents($file)); } else { Response::sendHttpStatus(404); } } }
解析一个静态资源的内容
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) {//使进程成为会话组长。让进程摆脱原会话的控制;让进程摆脱原进程组的控制; die('could not detach'); } $pid = pcntl_fork(); if ($pid === -1) { die("can't fork2!"); } elseif ($pid > 0) { self::message('start success!'); exit; } defined('STDIN') && fclose(STDIN); defined('STDOUT') && fclose(STDOUT); defined('STDERR') && fclose(STDERR); $stdin = fopen(self::$log, 'r'); $stdout = fopen(self::$log, 'a'); $stderr = fopen(self::$log, 'a'); self::setUser(self::$user); file_put_contents(self::$pidFile, posix_getpid()) || die("can't create pid file"); self::setProcessName('master'); pcntl_signal(SIGINT, ['\\' . __CLASS__, 'signalHandler'], false); pcntl_signal(SIGUSR1, ['\\' . __CLASS__, 'signalHandler'], false); file_put_contents(self::$status, '<?php return ' . var_export([], true) . ';', LOCK_EX); self::createChildrenProcess(); while (true) { pcntl_signal_dispatch(); $pid = pcntl_wait($status, WUNTRACED); pcntl_signal_dispatch(); if ($pid > 0) { $status = self::getStatus(); if (isset($status['pid'][$pid])) { unset($status['pid'][$pid]); file_put_contents(self::$status, '<?php return ' . var_export($status, true) . ';', LOCK_EX); } self::createChildrenProcess(); } sleep(1); } return; }
初始化守护进程
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_setgid($gid); } return $result; }
设置运行的用户 @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(self::$status, '<?php return ' . var_export($status, true) . ';', LOCK_EX); } else { exit(posix_getpid() . 'reload...'); } }
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); unlink(self::$status); echo 'stoped' . PHP_EOL; } exit(posix_getpid() . 'exit...'); }
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($status['task'][$key]) || $status['task'][$key] = [ 'last_runtime' => 0,//上一次运行时间 'frequency' => $frequency,//执行的频率 'task' => $task ]; file_put_contents(self::$status, '<?php return ' . var_export($status, true) . ';', LOCK_EX); self::message('task nums (' . count($status['task']) . ') list [' . json_encode($status['task'], JSON_UNESCAPED_UNICODE) . ']'); }
添加任务 @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'); self::message('master pid is ' . self::getPid()); self::message('worker pid is [' . implode($status['pid'], ',') . ']'); self::message('task nums (' . count($status['task']) . ') list [' . json_encode($status['task'], JSON_UNESCAPED_UNICODE) . ']'); } else { echo 'not running' . PHP_EOL; } return null; }
检查脚本运气状态 @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'; self::$status = Cml::getApplicationDir('global_store_path') . DIRECTORY_SEPARATOR . 'DaemonProcessStatus.php'; self::checkExtension(); } }
初始化环境
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; case 'reload': self::reload(); break; case 'status': self::getStatus(true); break; case 'add-task': if (func_num_args() < 1) { self::message('please input task name'); break; } $args = func_get_args(); $frequency = isset($args[2]) ? intval($args[2]) : 60; self::addTask($args[1], $frequency); break; case 'rm-task': if (func_num_args() < 1) { self::message('please input task name'); break; } $args = func_get_args(); self::rmTask($args[1]); break; default: self::message('Usage: xxx.php cml.cmd DaemonWorker::run {start|stop|status|addtask|rmtask}'); 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_export($status, true) . ';', LOCK_EX); } elseif ($pid === 0) { self::setProcessName('worker'); while (true) { pcntl_signal_dispatch(); $status = self::getStatus(); if ($status['task']) { foreach ($status['task'] as $key => $task) { if (time() > ($task['last_runtime'] + $task['frequency'])) { $status['task'][$key]['last_runtime'] = time(); file_put_contents(self::$status, '<?php return ' . var_export($status, true) . ';', LOCK_EX); call_user_func($task['task']); } } sleep(3); } else { sleep(5); } } } else { exit('create process error'); } }
创建一个子进程
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_writable($filename)) return false; $handle = fopen($filename, 'a'); if (!$handle) return false; $result = fwrite($handle, $content); if (!$result) return false; fclose($handle); return true; } }
写文件 @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", filemtime($filename)), 'size' => filesize($filename), 'type' => filetype($filename) ]; }
获取文件信息 @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); if (!is_dir("$path/$fileName")){ if (!unlink("$path/$fileName")){ $succeed = false; break; } } else{ self::delDir("$path/$fileName"); } } } if (!readdir($objDir)){ closedir($objDir); if (!rmdir($path)){ $succeed = false; } } } return $succeed; }
删除目录 @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['ext']), '.')); return $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); $waterMarkImageInfo = self::getImageInfo($waterMarkImage); if ($sourceImageInfo['width'] < $waterMarkImageInfo['width'] || $sourceImageInfo['height'] < $waterMarkImageInfo['height'] || $sourceImageInfo['ext'] == 'bmp' || $waterMarkImageInfo['bmp']) return false; //创建图像 $sourceImageCreateFunc = "imagecreatefrom{$sourceImageInfo['ext']}"; $sourceCreateImage = $sourceImageCreateFunc($sourceImage); $waterMarkImageCreateFunc = "imagecreatefrom{$waterMarkImageInfo['ext']}"; $waterMarkCreateImage = $waterMarkImageCreateFunc($waterMarkImage); //设置混色模式 imagealphablending($waterMarkImage, true); $posX = is_null($positionW) ? $sourceImageInfo['width'] - $waterMarkImageInfo['width'] : $sourceImageInfo['width'] - $positionW; $posY = is_null($positionH) ? $sourceImageInfo['height'] - $waterMarkImageInfo['height'] : $sourceImageInfo['height'] - $positionH; //生成混合图像 imagecopymerge($sourceCreateImage, $waterMarkCreateImage, $posX, $posY, 0, 0, $waterMarkImageInfo['width'], $waterMarkImageInfo['height'], $alpha); //生成处理后的图像 if (is_null($saveName)) { $saveName = $sourceImage; @unlink($sourceImage); } self::output($sourceCreateImage, $sourceImageInfo['ext'], $saveName, $quality); return true; }
图片打水印 @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) ? strtolower($imageInfo['ext']) : strtolower(($type == 'jpg' ? 'jpeg' : $type)); if ($isAutoFix) { //根据比例缩放 $fixScale = min($width / $imageInfo['width'], $height / $imageInfo['height']);//缩放的比例 if ($fixScale > 1) { //缩略图超过原图大小 $width = $imageInfo['width']; $height = $imageInfo['height']; } else { $width = $imageInfo['width'] * $fixScale; $height = $imageInfo['height'] * $fixScale; } } else { ($width > $imageInfo['width']) && $width = $imageInfo['width']; ($height > $imageInfo['height']) && $height = $imageInfo['height']; } if (!in_array($type, ['jpeg', 'gif', 'png'])) { return false; } $createImageFunc = "imagecreatefrom{$type}"; $sourceCreateImage = $createImageFunc($image);//载入原图 //生成缩略图 if ($type == 'gif' || !function_exists('imagecreatetruecolor')) { $thumbImg = imagecreate($width, $height); } else { $thumbImg = imagecreatetruecolor($width, $height); } if ($type == 'png') { imagealphablending($thumbImg, false);//取消默认的混色模式(为解决阴影为绿色的问题) imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息(为解决阴影为绿色的问题) } elseif ($type == 'gif') { $transparentIndex = imagecolortransparent($sourceCreateImage); if ($transparentIndex >= 0) { $transparentColor = imagecolorsforindex($sourceCreateImage , $transparentIndex); $transparentIndex = imagecolorallocate($thumbImg, $transparentColor['red'], $transparentColor['green'], $transparentColor['blue']); imagefill($thumbImg, 0, 0, $transparentIndex); imagecolortransparent($thumbImg, $transparentIndex); } } //复制 function_exists('imagecopyresampled') ? imagecopyresampled($thumbImg, $sourceCreateImage, 0, 0, 0, 0, $width, $height, $imageInfo['width'], $imageInfo['height']) : imagecopyresized($thumbImg, $sourceCreateImage, 0, 0, 0, 0, $width, $height, $imageInfo['width'], $imageInfo['height']); self::output($thumbImg, $type, $thumbName); imagedestroy($sourceCreateImage); return $thumbName; }
生成缩略图 @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.simple_search'), $simpleSearch); $form->handleRequest($request); $pager = null; if ($form->isValid()) { /** @var SearchHelper $searchHelper */ $searchHelper = $this->get('ezdemo.search_helper'); if (!empty($simpleSearch->searchText)) { $searchText = $simpleSearch->searchText; $pager = $searchHelper->searchForPaginatedContent( $searchText, $request->get('page', 1), $this->getConfigResolver()->getParameter('languages') ); $searchCount = $pager->getNbResults(); } } return $this->render( 'eZDemoBundle:search:search.html.twig', array( 'searchText' => $searchText, 'searchCount' => $searchCount, 'pagerSearch' => $pager, 'form' => $form->createView(), ), $response ); }
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', array( 'form' => $form->createView(), ), $response ); }
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'], $error['line'])); } else { //正式环境 只显示‘系统错误’并将错误信息记录到日志 Log::emergency('fatal_error', [$error]); $error = []; $error['message'] = Lang::get('_CML_ERROR_'); if (Request::isCli()) { Output::writeException(sprintf("[%s]\n%s", 'Fatal Error', $error['message'])); } else { header('HTTP/1.1 500 Internal Server Error'); View::getEngine('html')->reset()->assign('error', $error); Cml::showSystemTemplate(Config::get('html_exception')); } } exit; }
致命错误捕获 @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->getMessage(); $trace = $e->getTrace(); $error['files'][0] = $trace[0]; if (substr($e->getFile(), -20) !== '\Tools\functions.php' || $e->getLine() !== 90) { array_unshift($error['files'], ['file' => $e->getFile(), 'line' => $e->getLine(), 'type' => 'throw']); } //正式环境 只显示‘系统错误’并将错误信息记录到日志 Log::emergency($error['message'], [$error['files'][0]]); $error = []; $error['message'] = Lang::get('_CML_ERROR_'); if (Request::isCli()) { \Cml\pd($error); } else { header('HTTP/1.1 500 Internal Server Error'); View::getEngine('html')->reset()->assign('error', $error); Cml::showSystemTemplate(Config::get('html_exception')); } } exit; }
自定义异常处理 @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 => true, CURLOPT_CAINFO => dirname(__DIR__) . '/certs/ca.pem', ); if (defined(PHP_QUERY_RFC3986)) { $paramString = http_build_query($params, null, '&', PHP_QUERY_RFC3986); } else { // legacy, because the $enc_type has been implemented with PHP 5.4 $paramString = str_replace( array('+', '%7E'), array('%20', '~'), http_build_query($params, null, '&') ); } if ($method == 'GET') { if (!empty($params)) { $curlOpts[CURLOPT_URL] .= strpos($curlOpts[CURLOPT_URL], '?') === false ? '?' : '&'; $curlOpts[CURLOPT_URL] .= $paramString; } } else { $curlOpts[CURLOPT_POSTFIELDS] = $paramString; $curlOpts[CURLOPT_URL] .= strpos($curlOpts[CURLOPT_URL], '?') === false ? '?' : '&'; $curlOpts[CURLOPT_URL] .= 'instance=' . $params['instance']; } $curl = curl_init(); curl_setopt_array($curl, $curlOpts); $responseBody = $this->curlExec($curl); $responseInfo = $this->curlInfo($curl); if ($responseBody === false) { $responseBody = array('status' => 'error', 'message' => $this->curlError($curl)); } curl_close($curl); if ($responseInfo['content_type'] === 'application/json') { $responseBody = json_decode($responseBody, true); } return array( 'info' => $responseInfo, 'body' => $responseBody ); }
{@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->filter($concrete); if (is_null($concrete)) { $concrete = $abstract; } $this->binds[$abstract] = compact('concrete', 'singleton'); return $this; }
绑定服务 @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])) { throw new \InvalidArgumentException(Lang::get('_CONTAINER_MAKE_PARAMS_ERROR_', $abstract)); } if ($this->binds[$abstract]['concrete'] instanceof \Closure) { array_unshift($parameters, $this); $instance = call_user_func_array($this->binds[$abstract]['concrete'], (array)$parameters); } else { $concrete = $this->binds[$abstract]['concrete']; $instance = new $concrete($parameters); } $this->binds[$abstract]['singleton'] && $this->instances[$abstract] = $instance; return $instance; }
实例化服务 @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); $value = preg_replace("/<script(.*?)>(.*?)<\/script>/si", $clear ? '' : "&ltscript\\1&gt\\2&lt/script&gt", $value); $value = preg_replace("/<iframe(.*?)>(.*?)<\/iframe>/si", $clear ? '' : "&ltiframe\\1&gt\\2&lt/iframe&gt", $value); $value = preg_replace("/<object.+<\/object>/isU", '', $value); return $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_replace(["%3E", '>'], '&gt;', $value); $value = str_replace(['"', "'", "\t", ' '], ['&quot;', '&#39;', ' ', '&nbsp;&nbsp;'], $value); return $value; }
过滤特殊字符 @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); } return $var; }
/* 加强型过滤 @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 \UnexpectedValueException(Lang::get('_ILLEGAL_REQUEST_')); } } else { Response::sendHttpStatus(403); throw new \UnexpectedValueException(Lang::get('_ILLEGAL_REQUEST_')); } } }
防止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); $title = substr($title, 0, 30); $this->tWorksheetTitle = $title; //文件名 //$filename = preg_replace('/[^aA-zZ0-9\_\-]/', '', $filename); $this->filename = $filename; }
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 '<body link=blue vlink=purple ><table width="100%" border="0" cellspacing="0" cellpadding="0">'; if (is_array($this->titleRow)) { echo "<thead><tr>\n" . $this->addRow($this->titleRow) . "</tr></thead>\n"; } echo '<tbody>'; foreach ($data as $val) { $rows = $this->addRow($val); echo "<tr>\n" . $rows . "</tr>\n"; } echo "</tbody></table></body></html>"; exit(); }
生成Excel文件 @param array $data @return void
entailment