sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function setMulti($field, $data, $tableName = null, $tablePrefix = null, $openTransAction = true)
{
is_null($tableName) && $tableName = $this->getTableName();
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
return $this->db($this->getDbConf())->setMulti($tableName, $field, $data, $tablePrefix, $openTransAction);
} | 增加多条数据-快捷方法
@param array $field 要插入的字段 eg: ['title', 'msg', 'status', 'ctime’]
@param array $data 多条数据的值 eg: [['标题1', '内容1', 1, '2017'], ['标题2', '内容2', 1, '2017']]
@param string $tableName 表名 不传会自动从当前Model中$table属性获取
@param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀
@param bool $openTransAction 是否开启事务 默认开启
@return bool | array | entailment |
public function upSet(array $data, array $up = [], $tableName = null, $tablePrefix = null)
{
is_null($tableName) && $tableName = $this->getTableName();
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
return $this->db($this->getDbConf())->upSet($tableName, $data, $up, $tablePrefix);
} | 插入或更新一条记录,当UNIQUE index or PRIMARY KEY存在的时候更新,不存在的时候插入
若AUTO_INCREMENT存在则返回 AUTO_INCREMENT 的值.
@param array $data 插入的值 eg: ['username'=>'admin', 'email'=>'[email protected]']
@param array $up 更新的值-会自动merge $data中的数据
@param string $tableName 表名 不传会自动从当前Model中$table属性获取
@param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀
@return int | entailment |
public function updateByColumn($val, $data, $column = null, $tableName = null, $tablePrefix = null)
{
is_null($tableName) && $tableName = $this->getTableName();
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
is_null($column) && $column = $this->db($this->getDbConf())->getPk($tableName, $tablePrefix);
return $this->db($this->getDbConf())->where($column, $val)
->update($tableName, $data, true, $tablePrefix);
} | 通过字段更新数据-快捷方法
@param int $val 字段值
@param array $data 更新的数据
@param string $column 字段名 不传会自动分析表结构获取主键
@param string $tableName 表名 不传会自动从当前Model中$table属性获取
@param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀
@return bool | entailment |
public function delByColumn($val, $column = null, $tableName = null, $tablePrefix = null)
{
is_null($tableName) && $tableName = $this->getTableName();
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
is_null($column) && $column = $this->db($this->getDbConf())->getPk($tableName, $tablePrefix);
return $this->db($this->getDbConf())->where($column, $val)
->delete($tableName, true, $tablePrefix);
} | 通过主键删除数据-快捷方法
@param mixed $val
@param string $column 字段名 不传会自动分析表结构获取主键
@param string $tableName 表名 不传会自动从当前Model中$table属性获取
@param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀
@return bool | entailment |
public function getTotalNums($pkField = null, $tableName = null, $tablePrefix = null)
{
is_null($tableName) && $tableName = $this->getTableName();
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
is_null($pkField) && $pkField = $this->db($this->getDbConf())->getPk($tableName, $tablePrefix);
return $this->db($this->getDbConf())->table($tableName, $tablePrefix)->count($pkField, false, $this->useMaster);
} | 获取数据的总数
@param null $pkField 主键的字段名
@param string $tableName 表名 不传会自动从当前Model中$table属性获取
@param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀
@return mixed | entailment |
public function getList($offset = 0, $limit = 20, $order = 'DESC', $tableName = null, $tablePrefix = null)
{
is_null($tableName) && $tableName = $this->getTableName();
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
is_array($order) || $order = [$this->db($this->getDbConf())->getPk($tableName, $tablePrefix) => $order];
$dbInstance = $this->db($this->getDbConf())->table($tableName, $tablePrefix);
foreach ($order as $key => $val) {
$dbInstance->orderBy($key, $val);
}
return $dbInstance->limit($offset, $limit)
->select(null, null, $this->useMaster);
} | 获取数据列表
@param int $offset 偏移量
@param int $limit 返回的条数
@param string|array $order 传asc 或 desc 自动取主键 或 ['id'=>'desc', 'status' => 'asc']
@param string $tableName 表名 不传会自动从当前Model中$table属性获取
@param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀
@return array | entailment |
public function getListByPaginate($limit = 20, $order = 'DESC', $tableName = null, $tablePrefix = null)
{
is_null($tableName) && $tableName = $this->getTableName();
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
is_array($order) || $order = [$this->db($this->getDbConf())->getPk($tableName, $tablePrefix) => $order];
$dbInstance = $this->db($this->getDbConf())->table($tableName, $tablePrefix);
foreach ($order as $key => $val) {
$dbInstance->orderBy($key, $val);
}
return $dbInstance->paginate($limit, $this->useMaster);
} | 以分页的方式获取数据列表
@param int $limit 每页返回的条数
@param string|array $order 传asc 或 desc 自动取主键 或 ['id'=>'desc', 'status' => 'asc']
@param string $tableName 表名 不传会自动从当前Model中$table属性获取
@param mixed $tablePrefix 表前缀 不传会自动从当前Model中$tablePrefix属性获取再没有则获取配置中配置的前缀
@return array | entailment |
public function mapDbAndTable()
{
return $this->db($this->getDbConf())->table($this->getTableName(), $this->tablePrefix);
} | 自动根据 db属性执行$this->db(xxx)方法; table/tablePrefix属性执行$this->db('xxx')->table('tablename', 'tablePrefix')方法
@return \Cml\Db\MySql\Pdo | \Cml\Db\MongoDB\MongoDB | \Cml\Db\Base | entailment |
public static function getInstanceAndRunMapDbAndTable($table = null, $tablePrefix = null)
{
return self::getInstance($table, $tablePrefix)->mapDbAndTable();
} | 获取model实例并同时执行mapDbAndTable
@param null|string $table 表名
@param null|string $tablePrefix 表前缀
@return \Cml\Db\MySql\Pdo | \Cml\Db\MongoDB\MongoDB | \Cml\Db\Base | entailment |
public function when($condition, callable $trueCallback, callable $falseCallback = null)
{
if ($condition) {
call_user_func($trueCallback, $this);
} else {
is_callable($falseCallback) && call_user_func($falseCallback, $this);
}
return $this;
} | 根据条件是否成立执行对应的闭包
@param bool $condition 条件
@param callable $trueCallback 条件成立执行的闭包
@param callable|null $falseCallback 条件不成立执行的闭包
@return Db | \Cml\Db\MySql\Pdo | \Cml\Db\MongoDB\MongoDB | $this | entailment |
public static function catcherPhpError($errorType, $errorTip, $errorFile, $errorLine)
{
$logLevel = Cml::getWarningLogLevel();
if (in_array($errorType, $logLevel)) {
return;//只记录warning以上级别日志
}
self::getLogger()->log(self::getLogger()->phpErrorToLevel[$errorType], $errorTip, ['file' => $errorFile, 'line' => $errorLine]);
return;
} | 错误日志handler
@param int $errorType 错误类型 分运行时警告、运行时提醒、自定义错误、自定义提醒、未知等
@param string $errorTip 错误提示
@param string $errorFile 发生错误的文件
@param int $errorLine 错误所在行数
@return void | entailment |
public function setConfig($name, $value)
{
isset($this->config[$name]) && ($this->config[$name] = $value);
} | 配置参数
@param string $name 配置项
@param string $value 配置的值
@return void | entailment |
public function show()
{
if ($this->totalRows == 0) return '';
$nowCoolPage = ceil($this->nowPage/$this->barShowPage);
$delimiter = Config::get('url_pathinfo_depr');
$params = array_merge($this->param, [$this->pageShowVarName => '__PAGE__']);
$paramsString = '';
foreach($params as $key => $val) {
$paramsString == '' || $paramsString .= '/';
$paramsString .= $key . '/' . $val;
}
if ($this->url) {
$url = rtrim(Response::url($this->url . '/' . $paramsString, false), $delimiter);
} else {
$url = rtrim(Response::url(Cml::getContainer()->make('cml_route')->getFullPathNotContainSubDir() . '/' . $paramsString, false), $delimiter);
}
$upRow = $this->nowPage - 1;
$downRow = $this->nowPage + 1;
$upPage = $upRow > 0 ? '<li><a href = "'.str_replace('__PAGE__', $upRow, $url).'">'.$this->config['prev'].'</a></li>' : '';
$downPage = $downRow <= $this->totalPages ? '<li><a href="'.str_replace('__PAGE__', $downRow, $url).'">'.$this->config['next'].'</a></li>' : '';
// << < > >>
if ($nowCoolPage == 1) {
$theFirst = $prePage = '';
} else {
$preRow = $this->nowPage - $this->barShowPage;
$prePage = '<li><a href="'.str_replace('__PAGE__', $preRow, $url).'">上'.$this->barShowPage.'页</a></li>';
$theFirst = '<li><a href="'.str_replace('__PAGE__', 1, $url).'">'.$this->config['first'].'</a></li>';
}
if ($nowCoolPage == $this->coolPages) {
$nextPage = $theEnd = '';
} else {
$nextRow = $this->nowPage + $this->barShowPage;
$theEndRow = $this->totalPages;
$nextPage = '<li><a href="'.str_replace('__PAGE__', $nextRow, $url).'">下'.$this->barShowPage.'页</a></li>';
$theEnd = '<li><a href="'.str_replace('__PAGE__', $theEndRow, $url).'">'.$this->config['last'].'</a></li>';
}
//1 2 3 4 5
$linkPage = '';
for ($i = 1; $i <= $this->barShowPage; $i++) {
$page = ($nowCoolPage -1) * $this->barShowPage + $i;
if ($page != $this->nowPage) {
if ($page <= $this->totalPages) {
$linkPage .= ' <li><a href="'.str_replace('__PAGE__', $page, $url).'"> '.$page.' </a></li>';
} else {
break;
}
} else {
if ($this->totalPages != 1) {
$linkPage .= ' <li class="active"><a>'.$page.'</a></li>';
}
}
}
$pageStr = str_replace(
['%header%','%nowPage%','%totalRow%','%totalPage%','%upPage%','%downPage%','%first%','%prePage%','%linkPage%','%nextPage%','%end%'],
[$this->config['header'],$this->nowPage,$this->totalRows,$this->totalPages,$upPage,$downPage,$theFirst,$prePage,$linkPage,$nextPage,$theEnd],
$this->config['theme']
);
return '<ul>'.$pageStr.'</ul>';
} | 输出分页 | entailment |
public function display($filename = '', array $titleRaw = [])
{
$filename == '' && $filename = 'excel';
$excel = new \Cml\Vendor\Excel();
$excel->config('utf-8', false, 'default', $filename);
$titleRaw && $excel->setTitleRow($titleRaw);
$excel->excelXls($this->args);
} | 生成Excel文件
@param string $filename 文件名
@param array $titleRaw 标题行
@return void | entailment |
public function sample_basic()
{
$data = '<h2>Sample Basic</h2>
<hr>
<p>This is a simple basic mail message in <strong>HTML</strong> string format</p>
<p>Lorem ipsum dolor sit amharum<br /> quod deserunt id dolores.</p>';
$mail = new Mail();
$mail->setMailBody($data);
$mail->sendMail('Test Sample Basic');
exit('Message Sent!');
} | /* -----------------------------------------------------
Message without HTML template as inline HTML format
----------------------------------------------------- | entailment |
public function sample_array()
{
$data = array(
'Juliet & Romeo',
'[email protected]',
'This is an example using an Array as a message, without an external template HTML',
date('Y-m-d H:i:s'),
);
$mail = new Mail();
$mail->setMailBody($data);
$mail->sendMail('Test Sample Array');
exit('Message Sent!');
} | /* -----------------------------------------------------
Message as an Array with no HTML template
----------------------------------------------------- | entailment |
public function sample1()
{
$data = null;
$template_html = 'sample-1.html';
$mail = new Mail();
$mail->setMailBody($data, $template_html);
$mail->sendMail('Test Sample 1 - external HTML template');
exit('Message Sent!');
} | /* -----------------------------------------------------
Message using a external HTML template
----------------------------------------------------- | entailment |
public function sample2()
{
$data = array(
"NAME" => 'Juliet & Romeo',
"EMAIL" => '[email protected]',
"MESSAGE" => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt, ad labore iusto quibusdam totam. Repellendus, architecto quos temporibus dolores assumenda amet veritatis quisquam!',
"DATE" => date('Y-m-d H:i:s'),
"SMALL_TEXT" => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Sapiente, fugiat consequatur illo eaque ipsam expedita sint itaque quibusdam porro fugit quas quae placeat
qui fuga sequi aspernatur nam quo quis.',
);
$template_html = 'sample-2.html';
$mail = new Mail();
$mail->setMailBody($data, $template_html);
$mail->sendMail('Test Sample 2 Assoc Array with an external template and plain-text file');
exit('Message Sent!');
} | /* -----------------------------------------------------
Message as an associative array with external HTML template
----------------------------------------------------- | entailment |
public function sample3()
{
$data = array(
'John',
'[email protected]',
'Sydney, NSW',
'Australia',
12,06,1980,
'02 123 45678',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
);
$template_html = 'sample-3.txt';
$mail = new Mail();
$mail->setMailBody($data, $template_html, 'TEXT');
$mail->sendMail('Test Sample 3 Text Plain Template Format');
exit('Email Sample 3');
} | /* -----------------------------------------------------
Message as a plain-text format using external template
----------------------------------------------------- | entailment |
public static function ip()
{
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
return strip_tags($_SERVER['HTTP_CLIENT_IP']);
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return strip_tags($_SERVER['HTTP_X_FORWARDED_FOR']);
}
if (isset($_SERVER['REMOTE_ADDR'])) {
return strip_tags($_SERVER['REMOTE_ADDR']);
}
return 'unknown';
} | 获取IP地址
@return string | entailment |
public static function host($joinPort = true)
{
$host = strip_tags(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST']);
$joinPort && $host = $host . (in_array($_SERVER['SERVER_PORT'], [80, 443]) ? '' : ':' . $_SERVER['SERVER_PORT']);
return $host;
} | 获取主机名称
@param bool $joinPort 是否带上端口
@return string | entailment |
public static function baseUrl($joinPort = true)
{
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
return $protocol . self::host($joinPort);
} | 获取基本地址
@param bool $joinPort 是否带上端口
@return string | entailment |
public static function fullUrl($addSufFix = true, $joinParams = true)
{
$params = '';
if ($joinParams) {
$get = $_GET;
unset($get[Config::get('var_pathinfo')]);
$params = http_build_query($get);
$params && $params = '?' . $params;
}
return Request::baseUrl() . '/' . implode('/', Route::getPathInfo()) . ($addSufFix ? Config::get('url_html_suffix') : '') . $params;
} | 获取带全参数的url地址
@param bool $addSufFix 是否添加伪静态后缀
@param bool $joinParams 是否带上GET请求参数
@return string | entailment |
public static function isMobile()
{
if ($_GET['mobile'] === 'yes') {
setcookie('ismobile', 'yes', 3600);
return true;
} elseif ($_GET['mobile'] === 'no') {
setcookie('ismobile', 'no', 3600);
return false;
}
$cookie = $_COOKIE('ismobile');
if ($cookie === 'yes') {
return true;
} elseif ($cookie === 'no') {
return false;
} else {
$cookie = null;
static $mobileBrowserList = ['iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
'benq', 'haier', '^lct', '320x320', '240x320', '176x220'];
foreach ($mobileBrowserList as $val) {
$result = strpos(strtolower($_SERVER['HTTP_USER_AGENT']), $val);
if (false !== $result) {
setcookie('ismobile', 'yes', 3600);
return true;
}
}
setcookie('ismobile', 'no', 3600);
return false;
}
} | 判断是否为手机浏览器
@return bool | entailment |
public static function isAjax($checkAccess = false)
{
if (
self::getService('HTTP_X_REQUESTED_WITH')
&& strtolower(self::getService('HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest'
) {
return true;
}
if ($checkAccess) {
return self::acceptJson();
}
return false;
} | 判断是否为AJAX请求
@param bool $checkAccess 是否检测HTTP_ACCESS头
@return bool | entailment |
public static function acceptJson()
{
$accept = self::getService('HTTP_ACCEPT');
if (false !== strpos($accept, 'json') || false !== strpos($accept, 'javascript')) {
return true;
}
return false;
} | 判断请求类型是否为json
@return bool | entailment |
public static function getService($name = '')
{
if ($name == '') return $_SERVER;
return (isset($_SERVER[$name])) ? strip_tags($_SERVER[$name]) : '';
} | 获取SERVICE信息
@param string $name SERVER的键值名称
@return string | entailment |
public static function getBinaryData($formatJson = false, $jsonField = '')
{
if (isset($GLOBALS['HTTP_RAW_POST_DATA']) && !empty($GLOBALS['HTTP_RAW_POST_DATA'])) {
$data = $GLOBALS['HTTP_RAW_POST_DATA'];
} else {
$data = file_get_contents('php://input');
}
if ($formatJson) {
$data = json_decode($data, true);
$jsonField && $data = Cml::doteToArr($jsonField, $data);
}
return $data;
} | 获取POST过来的二进制数据,与手机端交互
@param bool $formatJson 获取的数据是否为json并格式化为数组
@param string $jsonField 获取json格式化为数组的字段多维数组用.分隔 如top.son.son2
@return bool|mixed|null|string | entailment |
public static function curl($url, $parameter = [], $header = [], $type = 'json', $connectTimeout = 10, $execTimeout = 30)
{
$ssl = substr($url, 0, 8) == "https://" ? true : false;
$ch = curl_init();
if ($ssl) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //检查证书中是否设置域名
}
if ($type == 'json' || $type == 'raw') {
$type == 'json' && ($parameter = json_encode($parameter, JSON_UNESCAPED_UNICODE)) && ($header[] = 'Content-Type: application/json');
//$queryStr = str_replace(['\/','[]'], ['/','{}'], $queryStr);//兼容
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter);
} else if ($type == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameter));
} else if ($type == 'file') {
$isOld = substr($parameter['file'], 0, 1) == '@';
if (function_exists('curl_file_create')) {
$parameter['file'] = curl_file_create($isOld ? substr($parameter['file'], 1) : $parameter['file'], '');
} else {
$isOld || $parameter['file'] = '@' . $parameter['file'];
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter);
} else {
$queryStr = '';
if (is_array($parameter)) {
foreach ($parameter as $key => $val) {
$queryStr .= $key . '=' . $val . '&';
}
$queryStr = substr($queryStr, 0, -1);
$queryStr && $url .= '?' . $queryStr;
}
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connectTimeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $execTimeout);
if (!empty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
$ret = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if (!$ret || !empty($error)) {
return false;
} else {
return $ret;
}
} | 发起curl请求
@param string $url 要请求的url
@param array $parameter 请求参数
@param array $header header头信息
@param string $type 请求的数据类型 json/post/file/get/raw
@param int $connectTimeout 请求的连接超时时间默认10s
@param int $execTimeout 等待执行输出的超时时间默认30s
@return bool|mixed | entailment |
public static function addRule($name, $callback, $message = 'error param')
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException('param $callback must can callable');
}
self::$errorTip[strtolower($name)] = $message;
static::$rules[$name] = $callback;
} | 添加一个自定义的验证规则
@param string $name
@param mixed $callback
@param string $message
@throws \InvalidArgumentException | entailment |
public function rule($rule, $field)
{
$ruleMethod = 'is' . ucfirst($rule);
if (!isset(static::$rules[$rule]) && !method_exists($this, $ruleMethod)) {
throw new \InvalidArgumentException(Lang::get('_NOT_FOUND_', 'validate rule [' . $rule . ']'));
}
$params = array_slice(func_get_args(), 2);
$this->dateBindRule[] = [
'rule' => $rule,
'field' => (array)$field,
'params' => (array)$params
];
return $this;
} | 绑定校验规则到字段
@param string $rule
@param array|string $field
@return $this | entailment |
public function rules($rules)
{
foreach ($rules as $rule => $field) {
if (is_array($field) && is_array($field[0])) {
foreach ($field as $params) {
array_unshift($params, $rule);
call_user_func_array([$this, 'rule'], $params);
}
} else {
$this->rule($rule, $field);
}
}
return $this;
} | 批量绑定校验规则到字段
@param array $rules
@return $this | entailment |
public function validate()
{
foreach ($this->dateBindRule as $bind) {
foreach ($bind['field'] as $field) {
if (strpos($field, '.')) {
$values = Cml::doteToArr($field, $this->data);
} else {
$values = isset($this->data[$field]) ? $this->data[$field] : null;
}
if (isset(static::$rules[$bind['rule']])) {
$callback = static::$rules[$bind['rule']];
} else {
$callback = [$this, 'is' . ucfirst($bind['rule'])];
}
$result = true;
if ($bind['rule'] == 'arr') {
$result = call_user_func($callback, $values, $bind['params'], $field);
} else {
is_array($values) || $values = [$values];// GET|POST的值为数组的时候每个值都进行校验
foreach ($values as $value) {
$result = $result && call_user_func($callback, $value, $bind['params'], $field);
if (!$result) {
break;
}
}
}
if (!$result) {
$this->error($field, $bind);
}
}
}
return count($this->getErrors()) === 0;
} | 执行校验并返回布尔值
@return boolean | entailment |
private function error($field, &$bind)
{
$label = (isset($this->label[$field]) && !empty($this->label[$field])) ? $this->label[$field] : $field;
$this->errorMsg[$field][] = vsprintf(str_replace('{field}', $label, (isset($bind['message']) ? $bind['message'] : '{field} ' . self::$errorTip[strtolower($bind['rule'])])), $bind['params']);
} | 添加一条错误信息
@param string $field
@param array $bind | entailment |
public function label($label)
{
if (is_array($label)) {
$this->label = array_merge($this->label, $label);
} else {
$this->label[$this->dateBindRule[count($this->dateBindRule) - 1]['field'][0]] = $label;
}
return $this;
} | 设置字段显示别名
@param string|array $label
@return $this | entailment |
public function getErrors($format = 0, $delimiter = ', ')
{
switch ($format) {
case 1:
return json_encode($this->errorMsg, JSON_UNESCAPED_UNICODE);
case 2:
$return = '';
foreach ($this->errorMsg as $val) {
$return .= ($return == '' ? '' : $delimiter) . implode($delimiter, $val);
}
return $return;
}
return $this->errorMsg;
} | 获取所有错误信息
@param int $format 返回的格式 0返回数组,1返回json,2返回字符串
@param string $delimiter format为2时分隔符
@return array|string | entailment |
public static function isRequire($value)
{
if (is_null($value)) {
return false;
} elseif (is_string($value) && trim($value) === '') {
return false;
}
return true;
} | 数据基础验证-是否必须填写的参数
@param string $value 需要验证的值
@return bool | entailment |
public static function isGt($value, $max)
{
is_array($max) && $max = $max[0];
if (!is_numeric($value)) {
return false;
} elseif (function_exists('bccomp')) {
return bccomp($value, $max, 14) == 1;
} else {
return $value > $max;
}
} | 数据基础验证-是否大于
@param int $value 要比较的值
@param int $max 要大于的长度
@return bool | entailment |
public static function isLt($value, $min)
{
is_array($min) && $min = $min[0];
if (!is_numeric($value)) {
return false;
} elseif (function_exists('bccomp')) {
return bccomp($min, $value, 14) == 1;
} else {
return $value < $min;
}
} | 数据基础验证-是否小于
@param int $value 要比较的值
@param int $min 要小于的长度
@return bool | entailment |
public static function isGte($value, $max)
{
is_array($max) && $max = $max[0];
if (!is_numeric($value)) {
return false;
} else {
return $value >= $max;
}
} | 数据基础验证-是否大于等于
@param int $value 要比较的值
@param int $max 要大于的长度
@return bool | entailment |
public static function isLte($value, $min)
{
is_array($min) && $min = $min[0];
if (!is_numeric($value)) {
return false;
} else {
return $value <= $min;
}
} | 数据基础验证-是否小于等于
@param int $value 要比较的值
@param int $min 要小于的长度
@return bool | entailment |
public static function isBetween($value, $start, $end)
{
if (is_array($start)) {
$end = $start[1];
$start = $start[0];
}
if ($value > $end || $value < $start) {
return false;
} else {
return true;
}
} | 数据基础验证-数字的值是否在区间内
@param string $value 字符串
@param int $start 起始数字
@param int $end 结束数字
@return bool | entailment |
public static function isLengthGt($value, $max)
{
$value = trim($value);
if (!is_string($value)) {
return false;
}
$length = function_exists('mb_strlen') ? mb_strlen($value, 'UTF-8') : strlen($value);
is_array($max) && $max = $max[0];
if ($max != 0 && $length <= $max) return false;
return true;
} | 数据基础验证-字符串长度是否大于
@param string $value 字符串
@param int $max 要大于的长度
@return bool | entailment |
public static function isLengthLt($value, $min)
{
$value = trim($value);
if (!is_string($value)) {
return false;
}
$length = function_exists('mb_strlen') ? mb_strlen($value, 'UTF-8') : strlen($value);
is_array($min) && $min = $min[0];
if ($min != 0 && $length >= $min) return false;
return true;
} | 数据基础验证-字符串长度是否小于
@param string $value 字符串
@param int $min 要小于的长度
@return bool | entailment |
public static function isLengthBetween($value, $min, $max)
{
if (is_array($min)) {
$max = $min[1];
$min = $min[0];
}
if (self::isLengthGte($value, $min) && self::isLengthLte($value, $max)) {
return true;
}
return false;
} | 长度是否在某区间内(包含边界)
@param string $value 字符串
@param int $min 要小于等于的长度
@param int $max 要大于等于的长度
@return bool | entailment |
public static function isLengthGte($value, $max)
{
is_array($max) && $max = $max[0];
return self::isLength($value, $max);
} | 数据基础验证-字符串长度是否大于等于
@param string $value 字符串
@param int $max 要大于的长度
@return bool | entailment |
public static function isLengthLte($value, $min)
{
is_array($min) && $min = $min[0];
return self::isLength($value, 0, $min);
} | 数据基础验证-字符串长度是否小于等于
@param string $value 字符串
@param int $min 要小于的长度
@return bool | entailment |
public static function isLength($value, $min = 0, $max = 0)
{
$value = trim($value);
if (!is_string($value)) {
return false;
}
$length = function_exists('mb_strlen') ? mb_strlen($value, 'UTF-8') : strlen($value);
if (is_array($min)) {
$max = $min[1];
$min = $min[0];
}
if ($min != 0 && $length < $min) return false;
if ($max != 0 && $length > $max) return false;
return true;
} | 数据基础验证-检测字符串长度
@param string $value 需要验证的值
@param int $min 字符串最小长度
@param int $max 字符串最大长度
@return bool | entailment |
protected function isEquals($value, $compareField, $field)
{
is_array($compareField) && $compareField = $compareField[0];
return isset($this->data[$field]) && isset($this->data[$compareField]) && $this->data[$field] == $this->data[$compareField];
} | 验证两个字段相等
@param string $compareField
@param string $field
@return bool | entailment |
protected function isDifferent($value, $compareField, $field)
{
is_array($compareField) && $compareField = $compareField[0];
return isset($this->data[$field]) && isset($this->data[$compareField]) && $this->data[$field] != $this->data[$compareField];
} | 验证两个字段不等
@param string $compareField
@param string $field
@return bool | entailment |
public static function isSafePassword($str)
{
if (preg_match('/[\x80-\xff]./', $str) || preg_match('/\'|"|\"/', $str) || strlen($str) < 6 || strlen($str) > 20) {
return false;
}
return true;
} | 检查是否是安全的密码
@param string $str
@return bool | entailment |
public function lock($key, $wouldBlock = false)
{
if (empty($key)) {
return false;
}
if (isset($this->lockCache[$key])) {//FileLock不支持设置过期时间
return true;
}
$fileName = $this->getFileName($key);
if (!$fp = fopen($fileName, 'w+')) {
return false;
}
if (flock($fp, LOCK_EX | LOCK_NB)) {
$this->lockCache[$fileName] = $fp;
return true;
}
//非堵塞模式
if (!$wouldBlock) {
return false;
}
//堵塞模式
do {
usleep(200);
} while (!flock($fp, LOCK_EX | LOCK_NB));
$this->lockCache[$fileName] = $fp;
return true;
} | 上锁
@param string $key 要上的锁的key
@param bool $wouldBlock 是否堵塞
@return mixed | entailment |
public function unlock($key)
{
$fileName = $this->getFileName($key);
if (isset($this->lockCache[$fileName])) {
flock($this->lockCache[$fileName], LOCK_UN);//5.3.2 在文件资源句柄关闭时不再自动解锁。现在要解锁必须手动进行。
fclose($this->lockCache[$fileName]);
is_file($fileName) && unlink($fileName);
$this->lockCache[$fileName] = null;
unset($this->lockCache[$fileName]);
}
} | 解锁
@param string $key 要解锁的锁的key | entailment |
private function getFileName($key)
{
$md5Key = md5($this->getKey($key));
$dir = Cml::getApplicationDir('runtime_cache_path') . DIRECTORY_SEPARATOR . 'LockFileCache' . DIRECTORY_SEPARATOR . 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 static function set($key, $value = '')
{
empty(self::$prefix) && self::$prefix = Config::get('session_prefix');
if (!is_array($key)) {
$_SESSION[self::$prefix . $key] = $value;
} else {
foreach ($key as $k => $v) {
$_SESSION[self::$prefix . $k] = $v;
}
}
return true;
} | 设置session值
@param string $key 可以为单个key值,也可以为数组
@param string $value value值
@return string | entailment |
public static function get($key)
{
empty(self::$prefix) && self::$prefix = Config::get('session_prefix');
return (isset($_SESSION[self::$prefix . $key])) ? $_SESSION[self::$prefix . $key] : null;
} | 获取session值
@param string $key 要获取的session的key
@return string | entailment |
public static function delete($key)
{
empty(self::$prefix) && self::$prefix = Config::get('session_prefix');
if (is_array($key)) {
foreach ($key as $k) {
if (isset($_SESSION[self::$prefix . $k])) unset($_SESSION[self::$prefix . $k]);
}
} else {
if (isset($_SESSION[self::$prefix . $key])) unset($_SESSION[self::$prefix . $key]);
}
return true;
} | 删除session值
@param string $key 要删除的session的key
@return string | entailment |
public function addCommands(array $commands)
{
foreach ($commands as $name => $command) {
$this->addCommand($command, is_numeric($name) ? null : $name);
}
return $this;
} | 批量添加命令
@param array $commands 命令列表
@return $this | entailment |
public function addCommand($class, $alias = null)
{
$name = $class;
$name = substr($name, 0, -7);
$name = self::dashToCamelCase(basename(str_replace('\\', '/', $name)));
$name = $alias ?: $name;
$this->commands[$name] = $class;
return $this;
} | 注册一个命令
@param string $class 类名
@param null $alias 命令别名
@return $this | entailment |
public function getCommand($name)
{
if (!isset($this->commands[$name])) {
throw new \InvalidArgumentException("Command '$name' does not exist");
}
return $this->commands[$name];
} | 获取某个命令
@param string $name 命令的别名
@return mixed | entailment |
public function run(array $argv = null)
{
try {
if ($argv === null) {
$argv = isset($_SERVER['argv']) ? array_slice($_SERVER['argv'], 1) : [];
}
list($args, $options) = Input::parse($argv);
$command = count($args) ? array_shift($args) : 'help';
if (!isset($this->commands[$command])) {
throw new \InvalidArgumentException("Command '$command' does not exist");
}
isset($options['no-ansi']) && Colour::setNoAnsi();
if (isset($options['h']) || isset($options['help'])) {
$help = new Help($this);
$help->execute([$command]);
exit(0);
}
$command = explode('::', $this->commands[$command]);
return call_user_func_array([new $command[0]($this), isset($command[1]) ? $command[1] : 'execute'], [$args, $options]);
} catch (\Exception $e) {
Output::writeException($e);
exit(1);
}
} | 运行命令
@param array|null $argv
@return mixed | entailment |
private function hash($key)
{
$serverNum = count($this->conf['server']);
$success = sprintf('%u', crc32($key)) % $serverNum;
if (!isset($this->redis[$success]) || !is_object($this->redis[$success])) {
$instance = new \Redis();
$connectToRedisFunction = function ($host, $port, $isPersistentConnect) use ($instance) {
if ($isPersistentConnect) {
return $instance->pconnect($host, $port, 1.5);
} else {
return $instance->connect($host, $port, 1.5);
}
};
$isPersistentConnect = !(isset($this->conf['server'][$success]['pconnect']) && $this->conf['server'][$success]['pconnect'] === false);
$connectResult = $connectToRedisFunction($this->conf['server'][$success]['host'], $this->conf['server'][$success]['port'], $isPersistentConnect);
$failOver = null;
if (!$connectResult && !empty($this->conf['back'])) {
$failOver = $this->conf['back'];
$isPersistentConnect = !(isset($failOver['pconnect']) && $failOver['pconnect'] === false);
$connectResult = $connectToRedisFunction($failOver['host'], $failOver['port'], $isPersistentConnect);
}
if (!$connectResult && $serverNum > 1) {
$failOver = $success + 1;
$failOver >= $serverNum && $failOver = $success - 1;
$failOver = $this->conf['server'][$failOver];
$isPersistentConnect = !(isset($failOver['pconnect']) && $failOver['pconnect'] === false);
$connectResult = $connectToRedisFunction($failOver['host'], $failOver['port'], $isPersistentConnect);
}
if (!$connectResult) {
Plugin::hook('cml.cache_server_down', [$this->conf['server'][$success]]);
throw new CacheConnectFailException(Lang::get('_CACHE_CONNECT_FAIL_', 'Redis',
$this->conf['server'][$success]['host'] . ':' . $this->conf['server'][$success]['port']
));
}
$password = false;
if (is_null($failOver)) {
if (isset($this->conf['server'][$success]['password']) && !empty($this->conf['server'][$success]['password'])) {
$password = $this->conf['server'][$success]['password'];
}
if ($password && !$instance->auth($password)) {
throw new \RuntimeException('redis password error!');
}
isset($this->conf['server'][$success]['db']) && $instance->select($this->conf['server'][$success]['db']);
} else {
if (isset($failOver['password']) && !empty($failOver['password'])) {
$password = $failOver['password'];
}
if ($password && !$instance->auth($password)) {
throw new \RuntimeException('redis password error!');
}
isset($failOver['db']) && $instance->select($failOver['db']);
Log::emergency('redis server down', ['downServer' => $this->conf['server'][$success], 'failOverTo' => $failOver]);
Plugin::hook('cml.redis_server_down_fail_over', ['downServer' => $this->conf['server'][$success], 'failOverTo' => $failOver]);
}
$instance->setOption(\Redis::OPT_PREFIX, $this->conf['prefix']);
$this->redis[$success] = $instance;
}
return $this->redis[$success];
} | 根据key获取redis实例
这边还是用取模的方式,一致性hash用php实现性能开销过大。取模的方式对只有几台机器的情况足够用了
如果有集群需要,直接使用redis3.0+自带的集群功能就好了。不管是可用性还是性能都比用php自己实现好
@param $key
@return \Redis | entailment |
public function get($key)
{
$return = json_decode($this->hash($key)->get($key), true);
is_null($return) && $return = false;
return $return; //orm层做判断用
} | 根据key取值
@param mixed $key 要获取的缓存key
@return bool | array | entailment |
public function set($key, $value, $expire = 0)
{
$value = json_encode($value, JSON_UNESCAPED_UNICODE);
if ($expire > 0) {
return $this->hash($key)->setex($key, $expire, $value);
} else {
return $this->hash($key)->set($key, $value);
}
} | 存储对象
@param mixed $key 要缓存的数据的key
@param mixed $value 要缓存的值,除resource类型外的数据类型
@param int $expire 缓存的有效时间 0为不过期
@return bool | entailment |
public function truncate()
{
foreach ($this->conf['server'] as $key => $val) {
if (!isset($this->redis[$key]) || !is_object($this->redis[$key])) {
$instance = new \Redis();
if ($instance->pconnect($val['host'], $val['port'], 1.5)) {
$this->redis[$key] = $instance;
} else {
throw new \RuntimeException(Lang::get('_CACHE_NEW_INSTANCE_ERROR_', 'Redis'));
}
}
$this->redis[$key]->flushDB();
}
return true;
} | 清洗已经存储的所有元素 | entailment |
public function increment($key, $val = 1)
{
return $this->hash($key)->incrBy($key, abs(intval($val)));
} | 自增
@param mixed $key 要自增的缓存的数据的key
@param int $val 自增的进步值,默认为1
@return bool | entailment |
public function decrement($key, $val = 1)
{
return $this->hash($key)->decrBy($key, abs(intval($val)));
} | 自减
@param mixed $key 要自减的缓存的数据的key
@param int $val 自减的进步值,默认为1
@return bool | entailment |
public function execute(array $args, array $options = [])
{
if (!isset($args[0])) {
throw new \InvalidArgumentException('arg action must be input');
}
$action = explode('::', $args[0]);
if (!class_exists($action[0])) {
throw new \InvalidArgumentException('action not not found!');
}
ProcessManage::rmTask($action);
} | 添加一个后台任务
@param array $args 传递给命令的参数
@param array $options 传递给命令的选项
@throws \InvalidArgumentException | entailment |
public function showFolderListAsideViewAction(ContentView $view)
{
$subContentCriteria = $this->get('ezdemo.criteria_helper')->generateSubContentCriterion(
$view->getLocation(),
$this->container->getParameter('ezdemo.folder.folder_tree.included_content_types'),
$this->getConfigResolver()->getParameter('languages')
);
$subContentQuery = new LocationQuery();
$subContentQuery->query = $subContentCriteria;
$subContentQuery->sortClauses = array(
new SortClause\ContentName(),
);
$subContentQuery->performCount = false;
$searchService = $this->getRepository()->getSearchService();
$subContent = $searchService->findLocations($subContentQuery);
$treeChildItems = array();
foreach ($subContent->searchHits as $hit) {
$treeChildItems[] = $hit->valueObject;
}
$view->addParameters(['treeChildItems' => $treeChildItems]);
return $view;
} | Displays the sub folder if it exists.
@param \eZ\Publish\Core\MVC\Symfony\View\ContentView $view
@return \Symfony\Component\HttpFoundation\Response $location is flagged as invisible | entailment |
public function showFolderListAction(Request $request, ContentView $view)
{
$languages = $this->getConfigResolver()->getParameter('languages');
// Using the criteria helper (a demobundle custom service) to generate our query's criteria.
// This is a good practice in order to have less code in your controller.
$criteria = $this->get('ezdemo.criteria_helper')->generateListFolderCriterion(
$view->getLocation(),
$this->container->getParameter('ezdemo.folder.folder_view.excluded_content_types'),
$languages
);
// Generating query
$query = new LocationQuery();
$query->query = $criteria;
$query->sortClauses = array(
new SortClause\DatePublished(),
);
// Initialize pagination.
$pager = new Pagerfanta(
new ContentSearchAdapter($query, $this->getRepository()->getSearchService())
);
$pager->setMaxPerPage($this->container->getParameter('ezdemo.folder.folder_list.limit'));
$pager->setCurrentPage($request->get('page', 1));
$includedContentTypeIdentifiers = $this->container->getParameter('ezdemo.folder.folder_tree.included_content_types');
// Get sub folder structure
$subContentCriteria = $this->get('ezdemo.criteria_helper')->generateSubContentCriterion(
$view->getLocation(), $includedContentTypeIdentifiers, $languages
);
$subContentQuery = new LocationQuery();
$subContentQuery->query = $subContentCriteria;
$subContentQuery->sortClauses = array(
new SortClause\ContentName(),
);
$searchService = $this->getRepository()->getSearchService();
$subContent = $searchService->findLocations($subContentQuery);
$treeItems = array();
foreach ($subContent->searchHits as $hit) {
$treeItems[] = $hit->valueObject;
}
$view->addParameters(['pagerFolder' => $pager, 'treeItems' => $treeItems]);
return $view;
} | Displays the list of article.
@param \Symfony\Component\HttpFoundation\Request $request request object
@param \eZ\Publish\Core\MVC\Symfony\View\ContentView $view
@return \Symfony\Component\HttpFoundation\Response $location is flagged as invisible | entailment |
public function sendFeebackMessage(Feedback $feedback, $feedbackEmailFrom, $feedbackEmailTo)
{
$message = Swift_Message::newInstance();
$message->setSubject($this->translator->trans('eZ Demobundle Feedback form'))
->setFrom($feedbackEmailFrom)
->setTo($feedbackEmailTo)
->setBody(
// Using template engine to generate the message based on a template
$this->templating->render(
'eZDemoBundle:email:feedback_form.txt.twig',
array(
'firstname' => $feedback->firstName,
'lastname' => $feedback->lastName,
'email' => $feedback->email,
'subject' => $feedback->subject,
'country' => $feedback->country,
'message' => $feedback->message,
)
)
);
$this->mailer->send($message);
} | Sends an email based on a feedback form.
@param \EzSystems\DemoBundle\Entity\Feedback $feedback
@param string $feedbackEmailFrom Email address sending feedback form
@param string $feedbackEmailTo Email address feedback forms will be sent to | entailment |
public function execute(array $args, array $options = [])
{
$this->bootstrap($args, $options);
$format = isset($options['format']) ? $options['format'] : $options['f'];
if (null !== $format) {
Output::writeln('using format ' . $format);
}
$this->getManager()->printStatus($format);
} | 获取迁移信息
@param array $args 参数
@param array $options 选项 | entailment |
public function renderFeedBlockAction($feedUrl, $offset = 0, $limit = 5)
{
$response = new Response();
try {
// Keep response in cache. TTL is configured in default_settings.yml
$response->setSharedMaxAge($this->container->getParameter('ezdemo.cache.feed_reader_ttl'));
return $this->render(
'eZDemoBundle:frontpage:feed_block.html.twig',
array(
'feed' => ezcFeed::parse($feedUrl),
'offset' => $offset,
'limit' => $limit,
),
$response
);
}
// In the case of exception raised in ezcFeed, return the empty response to fail nicely.
catch (Exception $e) {
$this->get('logger')->error("An exception has been raised when fetching RSS feed: {$e->getMessage()}");
return $response;
}
} | Renders an RSS feed into HTML.
Response is cached for 1 hour.
@param string $feedUrl
@param int $offset
@param int $limit
@return Response | entailment |
public function upload($savePath = null)
{
is_null($savePath) && $savePath = $this->config['savePath'];
$savePath = $savePath.'/';
$fileInfo = [];
$isUpload = false;
//获取上传的文件信息
$files = $this->workingFiles($_FILES);
foreach ($files as $key => $file) {
//过滤无效的选框
if (!empty($file['name'])) {
//登记上传文件的扩展信息
!isset($file['key']) && $file['key'] = $key;
$pathinfo = pathinfo($file['name']);
$file['extension'] = $pathinfo['extension'];
$file['savepath'] = $savePath;
$saveName = $this->getSaveName($savePath, $file);
$file['savename'] = $saveName;//取得文件名
//创建目录
if (is_dir($file['savepath'])) {
if (!is_writable($file['savepath'])) {
$this->errorInfo = "上传目录{$savePath}不可写";
return false;
}
} else {
if (!mkdir($file['savepath'], 0700, true)) {
$this->errorInfo = "上传目录{$savePath}不可写";
return false;
}
}
//自动查检附件
if (!$this->secureCheck($file)) return false;
//保存上传文件
if (!$this->save($file)) return false;
unset($file['tmp_name'], $file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if ($isUpload) {
$this->successInfo = $fileInfo;
return true;
} else {
$this->errorInfo = '没有选择上传文件';
return false;
}
} | 上传所有文件
@param null|string $savePath 上传文件的保存路径
@return bool | entailment |
private function getSaveName($savepath, $filename)
{
//重命名
$saveName = $this->config['rename'] ? \Cml\createUnique().'.'.$filename['extension'] : $filename['name'];
if ($this->config['subDir']) {
//使用子目录保存文件
switch ($this->config['subDirType']) {
case 'date':
$dir = date($this->config['dateFormat'], Cml::$nowTime).'/';
break;
case 'hash':
default:
$name = md5($saveName);
$dir = '';
for ($i = 0; $i < $this->config['hashLevel']; $i++) {
$dir .= $name{$i}.'/';
}
break;
}
if (!is_dir($savepath.$dir)) {
mkdir($savepath.$dir,0700, true);
}
$saveName = $dir.$saveName;
}
return $saveName;
} | 根据上传文件命名规则取得保存文件名
@param string $savepath
@param string $filename
@return string | entailment |
private function save($file)
{
$filename = $file['savepath'].$file['savename'];
if (!$this->config['replace'] && is_file($filename)) { //不覆盖同名文件
$this->errorInfo = "文件已经存在{$filename}";
return false;
}
//如果是图片,检查格式
if ( in_array(strtolower($file['extension']), ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])
&& false === getimagesize($file['tmp_name']) ) {
$this->errorInfo = '非法图像文件';
return false;
}
if (!move_uploaded_file($file['tmp_name'], $filename)) {
$this->errorInfo = '文件上传错误!';
return false;
}
if ($this->config['thumb'] && in_array(strtolower($file['extension']), ['gif', 'jpg', 'jpeg', 'bmp', 'png'])) {
if ($image = getimagesize($filename)) {
//生成缩略图
$thumbPath = $this->config['thumbPath'] ? $this->config['thumbPath'] : dirname($filename);
$thunbName = $this->config['thumbFile'] ? $this->config['thumbFile'] : $this->config['thumbPrefix'].basename($filename);
Image::makeThumb($filename, $thumbPath.'/'.$thunbName, null, $this->config['thumbMaxWidth'], $this->config['thumbMaxHeight']);
}
}
return true;
} | 保存
@param array $file
@return bool | entailment |
private function secureCheck($file)
{
//文件上传失败,检查错误码
if ($file['error'] != 0) {
switch ($file['error']) {
case 1:
$this->errorInfo = '上传的文件大小超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
$this->errorInfo = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
break;
case 3:
$this->errorInfo = '文件只有部分被上传';
break;
case 4:
$this->errorInfo = '没有文件被上传';
break;
case 6:
$this->errorInfo = '找不到临时文件夹';
break;
case 7:
$this->errorInfo = '文件写入失败';
break;
default:
$this->errorInfo = '未知上传错误!';
}
return false;
}
//文件上传成功,进行自定义检查
if ( (-1 != $this->config['maxSize']) && ($file['size'] > $this->config['maxSize']) ) {
$this->errorInfo = '上传文件大小不符';
return false;
}
//检查文件Mime类型
if (!$this->checkType($file['type'])) {
$this->errorInfo = '上传文件mime类型允许';
return false;
}
//检查文件类型
if (!$this->checkExt($file['extension'])) {
$this->errorInfo ='上传文件类型不允许';
return false;
}
//检查是否合法上传
if (!is_uploaded_file($file['tmp_name'])) {
$this->errorInfo = '非法的上传文件!';
return false;
}
return true;
} | 检查上传的文件有没上传成功是否合法
@param array $file 上传的单个文件
@return bool | entailment |
private function checkType($type)
{
if (!empty($this->allowTypes)) {
return in_array(strtolower($type), $this->allowTypes);
}
return true;
} | 查检文件的mime类型是否合法
@param string $type
@return bool | entailment |
private function checkExt($ext)
{
if (!empty($this->allowExts)) {
return in_array(strtolower($ext), $this->allowExts, true);
}
return true;
} | 检查上传的文件后缀是否合法
@param string $ext
@return bool | entailment |
public static function parse(array $argv)
{
$args = [];
$options = [];
for ($i = 0, $num = count($argv); $i < $num; $i++) {
$arg = $argv[$i];
if ($arg === '--') {//后缀所有内容都为参数
$args[] = implode(' ', array_slice($argv, $i + 1));
break;
}
if (substr($arg, 0, 2) === '--') {
$key = substr($arg, 2);
$value = true;
if (($hadValue = strpos($arg, '=')) !== false) {
$key = substr($arg, 2, $hadValue - 2);
$value = substr($arg, $hadValue + 1);
}
if (array_key_exists($key, $options)) {
if (!is_array($options[$key])) {
$options[$key] = [$options[$key]];
}
$options[$key][] = $value;
} else {
$options[$key] = $value;
}
} else if (substr($arg, 0, 1) === '-') {
foreach (str_split(substr($arg, 1)) as $key) {
$options[$key] = true;
}
} else {
$args[] = $arg;
}
}
return [$args, $options];
} | 解析参数
@param array $argv
@return array | entailment |
public function create($path)
{
if (preg_match('{^([a-zA-Z]):}', $path)) {
return $this->windowsFactory()->create($path);
}
return $this->unixFactory()->create($path);
} | Creates a new path instance from its string representation.
@param string $path The string representation of the path.
@return PathInterface The newly created path instance. | entailment |
public function createFromAtoms(
$atoms,
$isAbsolute = null,
$hasTrailingSeparator = null
) {
return $this->unixFactory()->createFromAtoms(
$atoms,
$isAbsolute,
$hasTrailingSeparator
);
} | Creates a new path instance from a set of path atoms.
@param mixed<string> $atoms The path atoms.
@param boolean|null $isAbsolute True if the path is absolute.
@param boolean|null $hasTrailingSeparator True if the path has a trailing separator.
@return PathInterface The newly created path instance.
@throws InvalidPathAtomExceptionInterface If any of the supplied atoms are invalid.
@throws InvalidPathStateException If the supplied arguments would produce an invalid path. | entailment |
public static function indexArrayByValue($input, $value)
{
$output = [];
foreach ($input as $row) {
$output[$row->$value] = $row;
}
return $output;
} | Reindex an existing array by a value from the array.
@param $input
@param $value
@return array | entailment |
public static function orderArrayByValue($input, $value)
{
$output = [];
foreach ($input as $row) {
$output[$row->$value][] = $row;
}
return $output;
} | @param $input
@param $value
@return array | entailment |
public static function numVerify($length = 4, $type = 'png', $width = 150, $height = 35, $verifyName = 'verifyCode', $font = 'tahoma.ttf')
{
$randNum = substr(str_shuffle(str_repeat('0123456789', 5)), 0, $length);
$authKey = md5(mt_rand() . microtime());
Cookie::set($verifyName, $authKey);
Model::getInstance()->cache()->set($authKey, $randNum, 1800);
$width = ($length * 33 + 20) > $width ? $length * 33 + 20 : $width;
$height = $length < 35 ? 35 : $height;
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = imagecreatetruecolor($width, $height);
} else {
$im = imagecreate($width, $height);
}
$r = Array(225, 255, 255, 223);
$g = Array(225, 236, 237, 255);
$b = Array(225, 236, 166, 125);
$key = mt_rand(0, 3);
$backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]);//背景色(随机)
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
$stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
// 干扰
for ($i = 0; $i < 10; $i++) {
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $stringColor);
}
for ($i = 0; $i < 25; $i++) {
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $stringColor);
}
for ($i = 0; $i < $length; $i++) {
$x = $i === 0 ? 15 : $i * 35;
$stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
imagettftext($im, 28, mt_rand(0, 60), $x, 35, $stringColor, CML_EXTEND_PATH . DIRECTORY_SEPARATOR . $font, $randNum[$i]);
}
self::output($im, $type);
} | 生成图像数字验证码
@param int $length 位数
@param string $type 图像格式
@param int $width 宽度
@param int $height 高度
@param string $verifyName Cookie中保存的名称
@param string $font 字体名
@return void | entailment |
public static function CnVerify($length = 4, $type = 'png', $width = 180, $height = 50, $font = 'tahoma.ttf', $verifyName = 'verifyCode')
{
$code = StringProcess::randString($length, 4);
$width = ($length * 45) > $width ? $length * 45 : $width;
$authKey = md5(mt_rand() . microtime());
Cookie::set($verifyName, $authKey);
Model::getInstance()->cache()->set($authKey, md5($code), 1800);
$im = imagecreatetruecolor($width, $height);
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
$bkcolor = imagecolorallocate($im, 250, 250, 250);
imagefill($im, 0, 0, $bkcolor);
imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
// 干扰
for ($i = 0; $i < 15; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor);
}
for ($i = 0; $i < 255; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor);
}
if (!is_file($font)) {
$font = CML_EXTEND_PATH . DIRECTORY_SEPARATOR . $font;
}
for ($i = 0; $i < $length; $i++) {
$fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
$codex = StringProcess::substrCn($code, $i, 1);
imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $font, $codex);
}
self::output($im, $type);
} | 中文验证码
@param int $length
@param string $type
@param int $width
@param int $height
@param string $font
@param string $verifyName
@return void | entailment |
public static function calocVerify($type = 'png', $width = 170, $height = 45, $font = 'tahoma.ttf', $verifyName = 'verifyCode')
{
$la = $ba = 0;
$calcType = mt_rand(1, 3);
$createNumber = function () use (&$la, &$ba, $calcType) {
$la = mt_rand(1, 9);
$ba = mt_rand(1, 9);
};
$createNumber();
if ($calcType == 3) {
while ($la == $ba) {
$createNumber();
}
if ($la < $ba) {
$tmp = $la;
$la = $ba;
$ba = $tmp;
}
}
$calcTypeArr = [
1 => $la + $ba,
2 => $la * $ba,
3 => $la - $ba
// 4 => $la / $ba,
];
$randStr = $calcTypeArr[$calcType];
$randResult = [
1 => $la . '+' . $ba . '=?',
2 => $la . '*' . $ba . '=?',
3 => $la . '-' . $ba . '=?'
// 4 => $la .'/'. $ba.'='. $randarr[4],
];
$calcResult = $randResult[$calcType];
$authKey = md5(mt_rand() . microtime());
Cookie::set($verifyName, $authKey);
Model::getInstance()->cache()->set($authKey, $randStr, 1800);
//$width = ($length * 10 + 10) > $width ? $length * 10 + 10 : $width;
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = imagecreatetruecolor($width, $height);
} else {
$im = imagecreate($width, $height);
}
$r = Array(225, 255, 255, 223);
$g = Array(225, 236, 237, 255);
$b = Array(225, 236, 166, 125);
$key = mt_rand(0, 3);
$backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]); //背景色(随机)
$borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
$stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
// 干扰
for ($i = 0; $i < 10; $i++) {
imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $stringColor);
}
for ($i = 0; $i < 25; $i++) {
imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $stringColor);
}
for ($i = 0; $i < 5; $i++) {
// imagestring($im, 5, $i * 10 + 5, mt_rand(1, 8), $calcResult{$i}, $stringColor);
$x = $i === 0 ? 20 : $i * 50;
$stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
if ($i == 1 || $i == 3 || $i == 4) {
$fontSize = $calcType == 3 ? 50 : 28;
if ($i == 1) {
imagettftext($im, $fontSize, 0, $x, 35, $stringColor, CML_EXTEND_PATH . DIRECTORY_SEPARATOR . $font, $calcResult[$i]);
} else {
$decNum = $i == 3 ? 30 : 55;
imagettftext($im, 25, 0, $x - $decNum, 35, $stringColor, CML_EXTEND_PATH . DIRECTORY_SEPARATOR . $font, $calcResult[$i]);
}
} else {
imagettftext($im, 28, mt_rand(0, 60), $x, 35, $stringColor, CML_EXTEND_PATH . DIRECTORY_SEPARATOR . $font, $calcResult[$i]);
}
}
self::output($im, $type);
} | 生成数字计算题验证码
@param string $type
@param int $width
@param int $height
@param string $font
@param string $verifyName
@return void | entailment |
public static function checkCode($input, $isCn = false, $verifyName = 'verifyCode')
{
$key = Cookie::get($verifyName);
if (!$key) return false;
$code = Model::getInstance()->cache()->get($key);
Model::getInstance()->cache()->delete($key);
$isCn && $input = md5(urldecode($input));
if ($code === false || $code != $input) {
return false;
} else {
return true;
}
} | 校验验证码
@param string $input 用户输入
@param bool $isCn 是否为中文验证码
@param string $verifyName 生成验证码时的字段
@return bool 正确返回true,错误返回false | entailment |
public static function output(&$image, $type = 'png', $filename = null, $quality = 100)
{
$type == 'jpg' && $type = 'jpeg';
$imageFun = "image{$type}";
if (is_null($filename)) { //输出到浏览器
header("Content-type: image/{$type}");
($type == 'jpeg') ? $imageFun($image, null, $quality) : $imageFun($image);
} else { //保存到文件
($type == 'jpeg') ? $imageFun($image, $filename, $quality) : $imageFun($image, $filename);
}
imagedestroy($image);
exit();
} | 输出图片
@param resource $image 被载入的图片
@param string $type 输出的类型
@param string $filename 保存的文件名
@param int $quality jpeg保存的质量
@return void | entailment |
public static function getEngine($engine = null)
{
is_null($engine) && $engine = Config::get('view_render_engine');
return Cml::getContainer()->make('view_' . strtolower($engine));
} | 获取渲染引擎
@param string $engine 视图引擎 内置html/json/xml/excel
@return \Cml\View\Html | entailment |
public function performApiRequest($method, \Payrexx\Models\Base $model)
{
$params = $model->toArray($method);
$params['ApiSignature'] =
base64_encode(hash_hmac('sha256', http_build_query($params, null, '&'), $this->apiSecret, true));
$params['instance'] = $this->instance;
$id = isset($params['id']) ? $params['id'] : 0;
$apiUrl = sprintf(self::API_URL_FORMAT, $this->apiBaseDomain, self::VERSION, $params['model'], $id);
$response = $this->communicationHandler->requestApi(
$apiUrl,
$params,
$this->getHttpMethod($method)
);
$convertedResponse = array();
if (!isset($response['body']['data']) || !is_array($response['body']['data'])) {
if (!isset($response['body']['message'])) {
throw new \Payrexx\PayrexxException('Payrexx PHP: Configuration is wrong! Check instance name and API secret', $response['info']['http_code']);
}
throw new \Payrexx\PayrexxException($response['body']['message'], $response['info']['http_code']);
}
foreach ($response['body']['data'] as $object) {
$responseModel = $model->getResponseModel();
$convertedResponse[] = $responseModel->fromArray($object);
}
if (
strpos($method, 'One') !== false ||
strpos($method, 'create') !== false
) {
$convertedResponse = current($convertedResponse);
}
return $convertedResponse;
} | Perform a simple API request by method name and Request model.
@param string $method The name of the API method to call
@param \Payrexx\Models\Base $model The model which has the same functionality like a filter.
@return \Payrexx\Models\Base[]|\Payrexx\Models\Base An array of models or just one model which
is the result of the API call
@throws \Payrexx\PayrexxException An error occurred during the Payrexx Request | entailment |
protected function getHttpMethod($method)
{
if (!$this->methodAvailable($method)) {
throw new \Payrexx\PayrexxException('Method ' . $method . ' not implemented');
}
return self::$methods[$method];
} | Gets the HTTP method to use for a specific API method
@param string $method The API method to check for
@return string The HTTP method to use for the queried API method
@throws \Payrexx\PayrexxException The method is not implemented yet. | entailment |
public function getTables()
{
$tables = [];
if ($this->serverSupportFeature(3)) {
$result = $this->runMongoCommand(['listCollections' => 1]);
foreach ($result as $val) {
$tables[] = $val['name'];
}
} else {
$result = $this->runMongoQuery('system.namespaces');
foreach ($result as $val) {
if (strpos($val['name'], '$') === false) {
$tables[] = substr($val['name'], strpos($val['name'], '.') + 1);
}
}
}
return $tables;
} | 获取当前db所有表名
@return array | entailment |
public function getAllTableStatus()
{
$return = [];
$collections = $this->getTables();
foreach ($collections as $collection) {
$res = $this->runMongoCommand(['collStats' => $collection]);
$return[substr($res[0]['ns'], strrpos($res[0]['ns'], '.') + 1)] = $res[0];
}
return $return;
} | 获取当前数据库中所有表的信息
@return array | entailment |
public function getDbFields($table, $tablePrefix = null, $filter = 0)
{
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
$one = $this->runMongoQuery($tablePrefix . $table, [], ['limit' => 1]);
return empty($one) ? [] : array_keys($one[0]);
} | 获取表字段-因为mongodb中collection对字段是没有做强制一制的。这边默认获取第一条数据的所有字段返回
@param string $table 表名
@param mixed $tablePrefix 表前缀,不传则获取配置中配置的前缀
@param int $filter 在MongoDB中此选项无效
@return mixed | entailment |
protected function parseKey($key, $and = true, $noCondition = false, $noTable = false)
{
$keys = explode('-', $key);
$table = strtolower(array_shift($keys));
$len = count($keys);
$condition = [];
for ($i = 0; $i < $len; $i += 2) {
$val = is_numeric($keys[$i + 1]) ? intval($keys[$i + 1]) : $keys[$i + 1];
$and ? $condition[$keys[$i]] = $val : $condition['$or'][][$keys[$i]] = $val;
}
if (empty($table) && !$noTable) {
throw new \InvalidArgumentException(Lang::get('_DB_PARAM_ERROR_PARSE_KEY_', $key, 'table'));
}
if (empty($condition) && !$noCondition) {
throw new \InvalidArgumentException(Lang::get('_DB_PARAM_ERROR_PARSE_KEY_', $key, 'condition'));
}
return [$table, $condition];
} | 查询语句条件组装
@param string $key eg: 'forum-fid-1-uid-2'
@param bool $and 多个条件之间是否为and true为and false为or
@param bool $noCondition 是否为无条件操作 set/delete/update操作的时候 condition为空是正常的不报异常
@param bool $noTable 是否可以没有数据表 当delete/update等操作的时候已经执行了table() table为空是正常的
@return array eg: ['forum', "`fid` = '1' AND `uid` = '2'"] | entailment |
public function get($key, $and = true, $useMaster = false, $tablePrefix = null)
{
if (is_string($useMaster) && is_null($tablePrefix)) {
$tablePrefix = $useMaster;
$useMaster = false;
}
is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
list($tableName, $condition) = $this->parseKey($key, $and);
$filter = [];
isset($this->sql['limit'][0]) && $filter['skip'] = $this->sql['limit'][0];
isset($this->sql['limit'][1]) && $filter['limit'] = $this->sql['limit'][1];
return $this->runMongoQuery($tablePrefix . $tableName, $condition, $filter, $useMaster);
} | 根据key取出数据
@param string $key get('user-uid-123');
@param bool $and 多个条件之间是否为and true为and false为or
@param bool|string $useMaster 是否使用主库,此选项为字符串时为表前缀$tablePrefix
@param null|string $tablePrefix 表前缀
@return array | entailment |
public function runMongoQuery($tableName, $condition = [], $queryOptions = [], $useMaster = false)
{
Cml::$debug && $this->debugLogSql('Query', $tableName, $condition, $queryOptions);
$this->reset();
$db = $useMaster ?
$this->getMaster()->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY_PREFERRED))
: $this->getSlave()->selectServer(new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED));
$cursor = $db->executeQuery($this->getDbName() . ".{$tableName}", new Query($condition, $queryOptions));
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
$result = [];
foreach ($cursor as $collection) {
$result[] = $collection;
}
return $result;
} | 执行mongoQuery命令
@param string $tableName 执行的mongoCollection名称
@param array $condition 查询条件
@param array $queryOptions 查询的参数
@param bool|string $useMaster 是否使用主库
@return array | entailment |
public function reset($must = false)
{
$must && $this->paramsAutoReset();
if (!$this->paramsAutoReset) {
$this->alwaysClearColumns && $this->sql['columns'] = [];
if ($this->alwaysClearTable) {
$this->table = []; //操作的表
$this->join = []; //是否内联
$this->leftJoin = []; //是否左联结
$this->rightJoin = []; //是否右联
}
return;
}
$this->sql = [
'where' => [],
'columns' => [],
'limit' => [],
'orderBy' => [],
'groupBy' => '',
'having' => '',
];
$this->table = []; //操作的表
$this->join = []; //是否内联
$this->leftJoin = []; //是否左联结
$this->rightJoin = []; //是否右联
$this->whereNeedAddAndOrOr = 0;
$this->opIsAnd = true;
} | orm参数重置
@param bool $must 是否强制重置 | entailment |
public function runMongoBulkWrite($tableName, BulkWrite $bulk)
{
$this->reset();
$return = false;
try {
$return = $this->getMaster()->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY_PREFERRED))
->executeBulkWrite($this->getDbName() . ".{$tableName}", $bulk);
} catch (BulkWriteException $e) {
$result = $e->getWriteResult();
// Check if the write concern could not be fulfilled
if ($writeConcernError = $result->getWriteConcernError()) {
throw new \RuntimeException(sprintf("%s (%d): %s\n",
$writeConcernError->getMessage(),
$writeConcernError->getCode(),
var_export($writeConcernError->getInfo(), true)
), 0, $e);
}
$errors = [];
// Check if any write operations did not complete at all
foreach ($result->getWriteErrors() as $writeError) {
$errors[] = sprintf("Operation#%d: %s (%d)\n",
$writeError->getIndex(),
$writeError->getMessage(),
$writeError->getCode()
);
}
throw new \RuntimeException(var_export($errors, true), 0, $e);
} catch (MongoDBDriverException $e) {
throw new \UnexpectedValueException(sprintf("Other error: %s\n", $e->getMessage()), 0, $e);
}
return $return;
} | 执行mongoBulkWrite命令
@param string $tableName 执行的mongoCollection名称
@param BulkWrite $bulk The MongoDB\Driver\BulkWrite to execute.
@return \MongoDB\Driver\WriteResult | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.