PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/ThinkPHP/Lib/Core/Model.class.php

https://github.com/ycj/thinkphp
PHP | 1553 lines | 952 code | 79 blank | 522 comment | 214 complexity | 96320ca54e30e18444050d659b9a93d8 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. /**
  12. * ThinkPHP Model模型类
  13. * 实现了ORM和ActiveRecords模式
  14. * @category Think
  15. * @package Think
  16. * @subpackage Core
  17. * @author liu21st <liu21st@gmail.com>
  18. */
  19. class Model {
  20. // 操作状态
  21. const MODEL_INSERT = 1; // 插入模型数据
  22. const MODEL_UPDATE = 2; // 更新模型数据
  23. const MODEL_BOTH = 3; // 包含上面两种方式
  24. const MUST_VALIDATE = 1;// 必须验证
  25. const EXISTS_VALIDATE = 0;// 表单存在字段则验证
  26. const VALUE_VALIDATE = 2;// 表单值不为空则验证
  27. // 当前使用的扩展模型
  28. private $_extModel = null;
  29. // 当前数据库操作对象
  30. protected $db = null;
  31. // 主键名称
  32. protected $pk = 'id';
  33. // 数据表前缀
  34. protected $tablePrefix = '';
  35. // 模型名称
  36. protected $name = '';
  37. // 数据库名称
  38. protected $dbName = '';
  39. //数据库配置
  40. protected $connection = '';
  41. // 数据表名(不包含表前缀)
  42. protected $tableName = '';
  43. // 实际数据表名(包含表前缀)
  44. protected $trueTableName = '';
  45. // 最近错误信息
  46. protected $error = '';
  47. // 字段信息
  48. protected $fields = array();
  49. // 数据信息
  50. protected $data = array();
  51. // 查询表达式参数
  52. protected $options = array();
  53. protected $_validate = array(); // 自动验证定义
  54. protected $_auto = array(); // 自动完成定义
  55. protected $_map = array(); // 字段映射定义
  56. protected $_scope = array(); // 命名范围定义
  57. // 是否自动检测数据表字段信息
  58. protected $autoCheckFields = true;
  59. // 是否批处理验证
  60. protected $patchValidate = false;
  61. // 链操作方法列表
  62. protected $methods = array('table','order','alias','having','group','lock','distinct','auto','filter','validate');
  63. /**
  64. * 架构函数
  65. * 取得DB类的实例对象 字段检查
  66. * @access public
  67. * @param string $name 模型名称
  68. * @param string $tablePrefix 表前缀
  69. * @param mixed $connection 数据库连接信息
  70. */
  71. public function __construct($name='',$tablePrefix='',$connection='') {
  72. // 模型初始化
  73. $this->_initialize();
  74. // 获取模型名称
  75. if(!empty($name)) {
  76. if(strpos($name,'.')) { // 支持 数据库名.模型名的 定义
  77. list($this->dbName,$this->name) = explode('.',$name);
  78. }else{
  79. $this->name = $name;
  80. }
  81. }elseif(empty($this->name)){
  82. $this->name = $this->getModelName();
  83. }
  84. // 设置表前缀
  85. if(is_null($tablePrefix)) {// 前缀为Null表示没有前缀
  86. $this->tablePrefix = '';
  87. }elseif('' != $tablePrefix) {
  88. $this->tablePrefix = $tablePrefix;
  89. }else{
  90. $this->tablePrefix = $this->tablePrefix?$this->tablePrefix:C('DB_PREFIX');
  91. }
  92. // 数据库初始化操作
  93. // 获取数据库操作对象
  94. // 当前模型有独立的数据库连接信息
  95. $this->db(0,empty($this->connection)?$connection:$this->connection);
  96. }
  97. /**
  98. * 自动检测数据表信息
  99. * @access protected
  100. * @return void
  101. */
  102. protected function _checkTableInfo() {
  103. // 如果不是Model类 自动记录数据表信息
  104. // 只在第一次执行记录
  105. if(empty($this->fields)) {
  106. // 如果数据表字段没有定义则自动获取
  107. if(C('DB_FIELDS_CACHE')) {
  108. $db = $this->dbName?$this->dbName:C('DB_NAME');
  109. $fields = F('_fields/'.strtolower($db.'.'.$this->name));
  110. if($fields) {
  111. $version = C('DB_FIELD_VERISON');
  112. if(empty($version) || $fields['_version']== $version) {
  113. $this->fields = $fields;
  114. return ;
  115. }
  116. }
  117. }
  118. // 每次都会读取数据表信息
  119. $this->flush();
  120. }
  121. }
  122. /**
  123. * 获取字段信息并缓存
  124. * @access public
  125. * @return void
  126. */
  127. public function flush() {
  128. // 缓存不存在则查询数据表信息
  129. $this->db->setModel($this->name);
  130. $fields = $this->db->getFields($this->getTableName());
  131. if(!$fields) { // 无法获取字段信息
  132. return false;
  133. }
  134. $this->fields = array_keys($fields);
  135. $this->fields['_autoinc'] = false;
  136. foreach ($fields as $key=>$val){
  137. // 记录字段类型
  138. $type[$key] = $val['type'];
  139. if($val['primary']) {
  140. $this->fields['_pk'] = $key;
  141. if($val['autoinc']) $this->fields['_autoinc'] = true;
  142. }
  143. }
  144. // 记录字段类型信息
  145. $this->fields['_type'] = $type;
  146. if(C('DB_FIELD_VERISON')) $this->fields['_version'] = C('DB_FIELD_VERISON');
  147. // 2008-3-7 增加缓存开关控制
  148. if(C('DB_FIELDS_CACHE')){
  149. // 永久缓存数据表信息
  150. $db = $this->dbName?$this->dbName:C('DB_NAME');
  151. F('_fields/'.strtolower($db.'.'.$this->name),$this->fields);
  152. }
  153. }
  154. /**
  155. * 动态切换扩展模型
  156. * @access public
  157. * @param string $type 模型类型名称
  158. * @param mixed $vars 要传入扩展模型的属性变量
  159. * @return Model
  160. */
  161. public function switchModel($type,$vars=array()) {
  162. $class = ucwords(strtolower($type)).'Model';
  163. if(!class_exists($class))
  164. throw_exception($class.L('_MODEL_NOT_EXIST_'));
  165. // 实例化扩展模型
  166. $this->_extModel = new $class($this->name);
  167. if(!empty($vars)) {
  168. // 传入当前模型的属性到扩展模型
  169. foreach ($vars as $var)
  170. $this->_extModel->setProperty($var,$this->$var);
  171. }
  172. return $this->_extModel;
  173. }
  174. /**
  175. * 设置数据对象的值
  176. * @access public
  177. * @param string $name 名称
  178. * @param mixed $value 值
  179. * @return void
  180. */
  181. public function __set($name,$value) {
  182. // 设置数据对象属性
  183. $this->data[$name] = $value;
  184. }
  185. /**
  186. * 获取数据对象的值
  187. * @access public
  188. * @param string $name 名称
  189. * @return mixed
  190. */
  191. public function __get($name) {
  192. return isset($this->data[$name])?$this->data[$name]:null;
  193. }
  194. /**
  195. * 检测数据对象的值
  196. * @access public
  197. * @param string $name 名称
  198. * @return boolean
  199. */
  200. public function __isset($name) {
  201. return isset($this->data[$name]);
  202. }
  203. /**
  204. * 销毁数据对象的值
  205. * @access public
  206. * @param string $name 名称
  207. * @return void
  208. */
  209. public function __unset($name) {
  210. unset($this->data[$name]);
  211. }
  212. /**
  213. * 利用__call方法实现一些特殊的Model方法
  214. * @access public
  215. * @param string $method 方法名称
  216. * @param array $args 调用参数
  217. * @return mixed
  218. */
  219. public function __call($method,$args) {
  220. if(in_array(strtolower($method),$this->methods,true)) {
  221. // 连贯操作的实现
  222. $this->options[strtolower($method)] = $args[0];
  223. return $this;
  224. }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
  225. // 统计查询的实现
  226. $field = isset($args[0])?$args[0]:'*';
  227. return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method);
  228. }elseif(strtolower(substr($method,0,5))=='getby') {
  229. // 根据某个字段获取记录
  230. $field = parse_name(substr($method,5));
  231. $where[$field] = $args[0];
  232. return $this->where($where)->find();
  233. }elseif(strtolower(substr($method,0,10))=='getfieldby') {
  234. // 根据某个字段获取记录的某个值
  235. $name = parse_name(substr($method,10));
  236. $where[$name] =$args[0];
  237. return $this->where($where)->getField($args[1]);
  238. }elseif(isset($this->_scope[$method])){// 命名范围的单独调用支持
  239. return $this->scope($method,$args[0]);
  240. }else{
  241. throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
  242. return;
  243. }
  244. }
  245. // 回调方法 初始化模型
  246. protected function _initialize() {}
  247. /**
  248. * 对保存到数据库的数据进行处理
  249. * @access protected
  250. * @param mixed $data 要操作的数据
  251. * @return boolean
  252. */
  253. protected function _facade($data) {
  254. // 检查非数据字段
  255. if(!empty($this->fields)) {
  256. foreach ($data as $key=>$val){
  257. if(!in_array($key,$this->fields,true)){
  258. unset($data[$key]);
  259. }elseif(is_scalar($val)) {
  260. // 字段类型检查
  261. $this->_parseType($data,$key);
  262. }
  263. }
  264. }
  265. // 安全过滤
  266. if(!empty($this->options['filter'])) {
  267. $data = array_map($this->options['filter'],$data);
  268. unset($this->options['filter']);
  269. }
  270. $this->_before_write($data);
  271. return $data;
  272. }
  273. // 写入数据前的回调方法 包括新增和更新
  274. protected function _before_write(&$data) {}
  275. /**
  276. * 新增数据
  277. * @access public
  278. * @param mixed $data 数据
  279. * @param array $options 表达式
  280. * @param boolean $replace 是否replace
  281. * @return mixed
  282. */
  283. public function add($data='',$options=array(),$replace=false) {
  284. if(empty($data)) {
  285. // 没有传递数据,获取当前数据对象的值
  286. if(!empty($this->data)) {
  287. $data = $this->data;
  288. // 重置数据
  289. $this->data = array();
  290. }else{
  291. $this->error = L('_DATA_TYPE_INVALID_');
  292. return false;
  293. }
  294. }
  295. // 分析表达式
  296. $options = $this->_parseOptions($options);
  297. // 数据处理
  298. $data = $this->_facade($data);
  299. if(false === $this->_before_insert($data,$options)) {
  300. return false;
  301. }
  302. // 写入数据到数据库
  303. $result = $this->db->insert($data,$options,$replace);
  304. if(false !== $result ) {
  305. $insertId = $this->getLastInsID();
  306. if($insertId) {
  307. // 自增主键返回插入ID
  308. $data[$this->getPk()] = $insertId;
  309. $this->_after_insert($data,$options);
  310. return $insertId;
  311. }
  312. $this->_after_insert($data,$options);
  313. }
  314. return $result;
  315. }
  316. // 插入数据前的回调方法
  317. protected function _before_insert(&$data,$options) {}
  318. // 插入成功后的回调方法
  319. protected function _after_insert($data,$options) {}
  320. public function addAll($dataList,$options=array(),$replace=false){
  321. if(empty($dataList)) {
  322. $this->error = L('_DATA_TYPE_INVALID_');
  323. return false;
  324. }
  325. // 分析表达式
  326. $options = $this->_parseOptions($options);
  327. // 数据处理
  328. foreach ($dataList as $key=>$data){
  329. $dataList[$key] = $this->_facade($data);
  330. }
  331. // 写入数据到数据库
  332. $result = $this->db->insertAll($dataList,$options,$replace);
  333. if(false !== $result ) {
  334. $insertId = $this->getLastInsID();
  335. if($insertId) {
  336. return $insertId;
  337. }
  338. }
  339. return $result;
  340. }
  341. /**
  342. * 通过Select方式添加记录
  343. * @access public
  344. * @param string $fields 要插入的数据表字段名
  345. * @param string $table 要插入的数据表名
  346. * @param array $options 表达式
  347. * @return boolean
  348. */
  349. public function selectAdd($fields='',$table='',$options=array()) {
  350. // 分析表达式
  351. $options = $this->_parseOptions($options);
  352. // 写入数据到数据库
  353. if(false === $result = $this->db->selectInsert($fields?$fields:$options['field'],$table?$table:$this->getTableName(),$options)){
  354. // 数据库插入操作失败
  355. $this->error = L('_OPERATION_WRONG_');
  356. return false;
  357. }else {
  358. // 插入成功
  359. return $result;
  360. }
  361. }
  362. /**
  363. * 保存数据
  364. * @access public
  365. * @param mixed $data 数据
  366. * @param array $options 表达式
  367. * @return boolean
  368. */
  369. public function save($data='',$options=array()) {
  370. if(empty($data)) {
  371. // 没有传递数据,获取当前数据对象的值
  372. if(!empty($this->data)) {
  373. $data = $this->data;
  374. // 重置数据
  375. $this->data = array();
  376. }else{
  377. $this->error = L('_DATA_TYPE_INVALID_');
  378. return false;
  379. }
  380. }
  381. // 数据处理
  382. $data = $this->_facade($data);
  383. // 分析表达式
  384. $options = $this->_parseOptions($options);
  385. if(false === $this->_before_update($data,$options)) {
  386. return false;
  387. }
  388. if(!isset($options['where']) ) {
  389. // 如果存在主键数据 则自动作为更新条件
  390. if(isset($data[$this->getPk()])) {
  391. $pk = $this->getPk();
  392. $where[$pk] = $data[$pk];
  393. $options['where'] = $where;
  394. $pkValue = $data[$pk];
  395. unset($data[$pk]);
  396. }else{
  397. // 如果没有任何更新条件则不执行
  398. $this->error = L('_OPERATION_WRONG_');
  399. return false;
  400. }
  401. }
  402. $result = $this->db->update($data,$options);
  403. if(false !== $result) {
  404. if(isset($pkValue)) $data[$pk] = $pkValue;
  405. $this->_after_update($data,$options);
  406. }
  407. return $result;
  408. }
  409. // 更新数据前的回调方法
  410. protected function _before_update(&$data,$options) {}
  411. // 更新成功后的回调方法
  412. protected function _after_update($data,$options) {}
  413. /**
  414. * 删除数据
  415. * @access public
  416. * @param mixed $options 表达式
  417. * @return mixed
  418. */
  419. public function delete($options=array()) {
  420. if(empty($options) && empty($this->options['where'])) {
  421. // 如果删除条件为空 则删除当前数据对象所对应的记录
  422. if(!empty($this->data) && isset($this->data[$this->getPk()]))
  423. return $this->delete($this->data[$this->getPk()]);
  424. else
  425. return false;
  426. }
  427. if(is_numeric($options) || is_string($options)) {
  428. // 根据主键删除记录
  429. $pk = $this->getPk();
  430. if(strpos($options,',')) {
  431. $where[$pk] = array('IN', $options);
  432. }else{
  433. $where[$pk] = $options;
  434. }
  435. $pkValue = $where[$pk];
  436. $options = array();
  437. $options['where'] = $where;
  438. }
  439. // 分析表达式
  440. $options = $this->_parseOptions($options);
  441. $result= $this->db->delete($options);
  442. if(false !== $result) {
  443. $data = array();
  444. if(isset($pkValue)) $data[$pk] = $pkValue;
  445. $this->_after_delete($data,$options);
  446. }
  447. // 返回删除记录个数
  448. return $result;
  449. }
  450. // 删除成功后的回调方法
  451. protected function _after_delete($data,$options) {}
  452. /**
  453. * 查询数据集
  454. * @access public
  455. * @param array $options 表达式参数
  456. * @return mixed
  457. */
  458. public function select($options=array()) {
  459. if(is_string($options) || is_numeric($options)) {
  460. // 根据主键查询
  461. $pk = $this->getPk();
  462. if(strpos($options,',')) {
  463. $where[$pk] = array('IN',$options);
  464. }else{
  465. $where[$pk] = $options;
  466. }
  467. $options = array();
  468. $options['where'] = $where;
  469. }elseif(false === $options){ // 用于子查询 不查询只返回SQL
  470. $options = array();
  471. // 分析表达式
  472. $options = $this->_parseOptions($options);
  473. return '( '.$this->db->buildSelectSql($options).' )';
  474. }
  475. // 分析表达式
  476. $options = $this->_parseOptions($options);
  477. $resultSet = $this->db->select($options);
  478. if(false === $resultSet) {
  479. return false;
  480. }
  481. if(empty($resultSet)) { // 查询结果为空
  482. return null;
  483. }
  484. $this->_after_select($resultSet,$options);
  485. return $resultSet;
  486. }
  487. // 查询成功后的回调方法
  488. protected function _after_select(&$resultSet,$options) {}
  489. /**
  490. * 生成查询SQL 可用于子查询
  491. * @access public
  492. * @param array $options 表达式参数
  493. * @return string
  494. */
  495. public function buildSql($options=array()) {
  496. // 分析表达式
  497. $options = $this->_parseOptions($options);
  498. return '( '.$this->db->buildSelectSql($options).' )';
  499. }
  500. /**
  501. * 分析表达式
  502. * @access protected
  503. * @param array $options 表达式参数
  504. * @return array
  505. */
  506. protected function _parseOptions($options=array()) {
  507. if(is_array($options))
  508. $options = array_merge($this->options,$options);
  509. // 查询过后清空sql表达式组装 避免影响下次查询
  510. $this->options = array();
  511. if(!isset($options['table'])){
  512. // 自动获取表名
  513. $options['table'] = $this->getTableName();
  514. $fields = $this->fields;
  515. }else{
  516. // 指定数据表 则重新获取字段列表 但不支持类型检测
  517. $fields = $this->getDbFields();
  518. }
  519. if(!empty($options['alias'])) {
  520. $options['table'] .= ' '.$options['alias'];
  521. }
  522. // 记录操作的模型名称
  523. $options['model'] = $this->name;
  524. // 字段类型验证
  525. if(isset($options['where']) && is_array($options['where']) && !empty($fields) && !isset($options['join'])) {
  526. // 对数组查询条件进行字段类型检查
  527. foreach ($options['where'] as $key=>$val){
  528. $key = trim($key);
  529. if(in_array($key,$fields,true)){
  530. if(is_scalar($val)) {
  531. $this->_parseType($options['where'],$key);
  532. }
  533. }elseif('_' != substr($key,0,1) && false === strpos($key,'.') && false === strpos($key,'(') && false === strpos($key,'|') && false === strpos($key,'&')){
  534. unset($options['where'][$key]);
  535. }
  536. }
  537. }
  538. // 表达式过滤
  539. $this->_options_filter($options);
  540. return $options;
  541. }
  542. // 表达式过滤回调方法
  543. protected function _options_filter(&$options) {}
  544. /**
  545. * 数据类型检测
  546. * @access protected
  547. * @param mixed $data 数据
  548. * @param string $key 字段名
  549. * @return void
  550. */
  551. protected function _parseType(&$data,$key) {
  552. $fieldType = strtolower($this->fields['_type'][$key]);
  553. if(false === strpos($fieldType,'bigint') && false !== strpos($fieldType,'int')) {
  554. $data[$key] = intval($data[$key]);
  555. }elseif(false !== strpos($fieldType,'float') || false !== strpos($fieldType,'double')){
  556. $data[$key] = floatval($data[$key]);
  557. }elseif(false !== strpos($fieldType,'bool')){
  558. $data[$key] = (bool)$data[$key];
  559. }
  560. }
  561. /**
  562. * 查询数据
  563. * @access public
  564. * @param mixed $options 表达式参数
  565. * @return mixed
  566. */
  567. public function find($options=array()) {
  568. if(is_numeric($options) || is_string($options)) {
  569. $where[$this->getPk()] = $options;
  570. $options = array();
  571. $options['where'] = $where;
  572. }
  573. // 总是查找一条记录
  574. $options['limit'] = 1;
  575. // 分析表达式
  576. $options = $this->_parseOptions($options);
  577. $resultSet = $this->db->select($options);
  578. if(false === $resultSet) {
  579. return false;
  580. }
  581. if(empty($resultSet)) {// 查询结果为空
  582. return null;
  583. }
  584. $this->data = $resultSet[0];
  585. $this->_after_find($this->data,$options);
  586. return $this->returnResult($this->data);
  587. }
  588. // 查询成功的回调方法
  589. protected function _after_find(&$result,$options) {}
  590. protected function returnResult($data,$type=''){
  591. $type = $type?$type:$this->options['result'];
  592. if ($type){
  593. if(is_array($type)){
  594. $handler = $type[1];
  595. return $handler($data);
  596. }
  597. switch (strtolower($type)){
  598. case 'json':
  599. return json_encode($data);
  600. case 'xml':
  601. return xml_encode($data);
  602. }
  603. }
  604. return $data;
  605. }
  606. /**
  607. * 处理字段映射
  608. * @access public
  609. * @param array $data 当前数据
  610. * @param integer $type 类型 0 写入 1 读取
  611. * @return array
  612. */
  613. public function parseFieldsMap($data,$type=1) {
  614. // 检查字段映射
  615. if(!empty($this->_map)) {
  616. foreach ($this->_map as $key=>$val){
  617. if($type==1) { // 读取
  618. if(isset($data[$val])) {
  619. $data[$key] = $data[$val];
  620. unset($data[$val]);
  621. }
  622. }else{
  623. if(isset($data[$key])) {
  624. $data[$val] = $data[$key];
  625. unset($data[$key]);
  626. }
  627. }
  628. }
  629. }
  630. return $data;
  631. }
  632. /**
  633. * 设置记录的某个字段值
  634. * 支持使用数据库字段和方法
  635. * @access public
  636. * @param string|array $field 字段名
  637. * @param string $value 字段值
  638. * @return boolean
  639. */
  640. public function setField($field,$value='') {
  641. if(is_array($field)) {
  642. $data = $field;
  643. }else{
  644. $data[$field] = $value;
  645. }
  646. return $this->save($data);
  647. }
  648. /**
  649. * 字段值增长
  650. * @access public
  651. * @param string $field 字段名
  652. * @param integer $step 增长值
  653. * @return boolean
  654. */
  655. public function setInc($field,$step=1) {
  656. return $this->setField($field,array('exp',$field.'+'.$step));
  657. }
  658. /**
  659. * 字段值减少
  660. * @access public
  661. * @param string $field 字段名
  662. * @param integer $step 减少值
  663. * @return boolean
  664. */
  665. public function setDec($field,$step=1) {
  666. return $this->setField($field,array('exp',$field.'-'.$step));
  667. }
  668. /**
  669. * 获取一条记录的某个字段值
  670. * @access public
  671. * @param string $field 字段名
  672. * @param string $spea 字段数据间隔符号 NULL返回数组
  673. * @return mixed
  674. */
  675. public function getField($field,$sepa=null) {
  676. $options['field'] = $field;
  677. $options = $this->_parseOptions($options);
  678. $field = trim($field);
  679. if(strpos($field,',')) { // 多字段
  680. if(!isset($options['limit'])){
  681. $options['limit'] = is_numeric($sepa)?$sepa:'';
  682. }
  683. $resultSet = $this->db->select($options);
  684. if(!empty($resultSet)) {
  685. $_field = explode(',', $field);
  686. $field = array_keys($resultSet[0]);
  687. $key = array_shift($field);
  688. $key2 = array_shift($field);
  689. $cols = array();
  690. $count = count($_field);
  691. foreach ($resultSet as $result){
  692. $name = $result[$key];
  693. if(2==$count) {
  694. $cols[$name] = $result[$key2];
  695. }else{
  696. $cols[$name] = is_string($sepa)?implode($sepa,$result):$result;
  697. }
  698. }
  699. return $cols;
  700. }
  701. }else{ // 查找一条记录
  702. // 返回数据个数
  703. if(true !== $sepa) {// 当sepa指定为true的时候 返回所有数据
  704. $options['limit'] = is_numeric($sepa)?$sepa:1;
  705. }
  706. $result = $this->db->select($options);
  707. if(!empty($result)) {
  708. if(true !== $sepa && 1==$options['limit']) return reset($result[0]);
  709. foreach ($result as $val){
  710. $array[] = $val[$field];
  711. }
  712. return $array;
  713. }
  714. }
  715. return null;
  716. }
  717. /**
  718. * 创建数据对象 但不保存到数据库
  719. * @access public
  720. * @param mixed $data 创建数据
  721. * @param string $type 状态
  722. * @return mixed
  723. */
  724. public function create($data='',$type='') {
  725. // 如果没有传值默认取POST数据
  726. if(empty($data)) {
  727. $data = $_POST;
  728. }elseif(is_object($data)){
  729. $data = get_object_vars($data);
  730. }
  731. // 验证数据
  732. if(empty($data) || !is_array($data)) {
  733. $this->error = L('_DATA_TYPE_INVALID_');
  734. return false;
  735. }
  736. // 检查字段映射
  737. $data = $this->parseFieldsMap($data,0);
  738. // 状态
  739. $type = $type?$type:(!empty($data[$this->getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT);
  740. // 检测提交字段的合法性
  741. if(isset($this->options['field'])) { // $this->field('field1,field2...')->create()
  742. $fields = $this->options['field'];
  743. unset($this->options['field']);
  744. }elseif($type == self::MODEL_INSERT && isset($this->insertFields)) {
  745. $fields = $this->insertFields;
  746. }elseif($type == self::MODEL_UPDATE && isset($this->updateFields)) {
  747. $fields = $this->updateFields;
  748. }
  749. if(isset($fields)) {
  750. if(is_string($fields)) {
  751. $fields = explode(',',$fields);
  752. }
  753. // 判断令牌验证字段
  754. if(C('TOKEN_ON')) $fields[] = C('TOKEN_NAME');
  755. foreach ($data as $key=>$val){
  756. if(!in_array($key,$fields)) {
  757. unset($data[$key]);
  758. }
  759. }
  760. }
  761. // 数据自动验证
  762. if(!$this->autoValidation($data,$type)) return false;
  763. // 表单令牌验证
  764. if(C('TOKEN_ON') && !$this->autoCheckToken($data)) {
  765. $this->error = L('_TOKEN_ERROR_');
  766. return false;
  767. }
  768. // 验证完成生成数据对象
  769. if($this->autoCheckFields) { // 开启字段检测 则过滤非法字段数据
  770. $fields = $this->getDbFields();
  771. foreach ($data as $key=>$val){
  772. if(!in_array($key,$fields)) {
  773. unset($data[$key]);
  774. }elseif(MAGIC_QUOTES_GPC && is_string($val)){
  775. $data[$key] = stripslashes($val);
  776. }
  777. }
  778. }
  779. // 创建完成对数据进行自动处理
  780. $this->autoOperation($data,$type);
  781. // 赋值当前数据对象
  782. $this->data = $data;
  783. // 返回创建的数据以供其他调用
  784. return $data;
  785. }
  786. // 自动表单令牌验证
  787. // TODO ajax无刷新多次提交暂不能满足
  788. public function autoCheckToken($data) {
  789. if(C('TOKEN_ON')){
  790. $name = C('TOKEN_NAME');
  791. if(!isset($data[$name]) || !isset($_SESSION[$name])) { // 令牌数据无效
  792. return false;
  793. }
  794. // 令牌验证
  795. list($key,$value) = explode('_',$data[$name]);
  796. if($value && $_SESSION[$name][$key] === $value) { // 防止重复提交
  797. unset($_SESSION[$name][$key]); // 验证完成销毁session
  798. return true;
  799. }
  800. // 开启TOKEN重置
  801. if(C('TOKEN_RESET')) unset($_SESSION[$name][$key]);
  802. return false;
  803. }
  804. return true;
  805. }
  806. /**
  807. * 使用正则验证数据
  808. * @access public
  809. * @param string $value 要验证的数据
  810. * @param string $rule 验证规则
  811. * @return boolean
  812. */
  813. public function regex($value,$rule) {
  814. $validate = array(
  815. 'require' => '/.+/',
  816. 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
  817. 'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
  818. 'currency' => '/^\d+(\.\d+)?$/',
  819. 'number' => '/^\d+$/',
  820. 'zip' => '/^\d{6}$/',
  821. 'integer' => '/^[-\+]?\d+$/',
  822. 'double' => '/^[-\+]?\d+(\.\d+)?$/',
  823. 'english' => '/^[A-Za-z]+$/',
  824. );
  825. // 检查是否有内置的正则表达式
  826. if(isset($validate[strtolower($rule)]))
  827. $rule = $validate[strtolower($rule)];
  828. return preg_match($rule,$value)===1;
  829. }
  830. /**
  831. * 自动表单处理
  832. * @access public
  833. * @param array $data 创建数据
  834. * @param string $type 创建类型
  835. * @return mixed
  836. */
  837. private function autoOperation(&$data,$type) {
  838. if(!empty($this->options['auto'])) {
  839. $_auto = $this->options['auto'];
  840. unset($this->options['auto']);
  841. }elseif(!empty($this->_auto)){
  842. $_auto = $this->_auto;
  843. }
  844. // 自动填充
  845. if(isset($_auto)) {
  846. foreach ($_auto as $auto){
  847. // 填充因子定义格式
  848. // array('field','填充内容','填充条件','附加规则',[额外参数])
  849. if(empty($auto[2])) $auto[2] = self::MODEL_INSERT; // 默认为新增的时候自动填充
  850. if( $type == $auto[2] || $auto[2] == self::MODEL_BOTH) {
  851. switch(trim($auto[3])) {
  852. case 'function': // 使用函数进行填充 字段的值作为参数
  853. case 'callback': // 使用回调方法
  854. $args = isset($auto[4])?(array)$auto[4]:array();
  855. if(isset($data[$auto[0]])) {
  856. array_unshift($args,$data[$auto[0]]);
  857. }
  858. if('function'==$auto[3]) {
  859. $data[$auto[0]] = call_user_func_array($auto[1], $args);
  860. }else{
  861. $data[$auto[0]] = call_user_func_array(array(&$this,$auto[1]), $args);
  862. }
  863. break;
  864. case 'field': // 用其它字段的值进行填充
  865. $data[$auto[0]] = $data[$auto[1]];
  866. break;
  867. case 'ignore': // 为空忽略
  868. if(''===$data[$auto[0]])
  869. unset($data[$auto[0]]);
  870. break;
  871. case 'string':
  872. default: // 默认作为字符串填充
  873. $data[$auto[0]] = $auto[1];
  874. }
  875. if(false === $data[$auto[0]] ) unset($data[$auto[0]]);
  876. }
  877. }
  878. }
  879. return $data;
  880. }
  881. /**
  882. * 自动表单验证
  883. * @access protected
  884. * @param array $data 创建数据
  885. * @param string $type 创建类型
  886. * @return boolean
  887. */
  888. protected function autoValidation($data,$type) {
  889. if(!empty($this->options['validate'])) {
  890. $_validate = $this->options['validate'];
  891. unset($this->options['validate']);
  892. }elseif(!empty($this->_validate)){
  893. $_validate = $this->_validate;
  894. }
  895. // 属性验证
  896. if(isset($_validate)) { // 如果设置了数据自动验证则进行数据验证
  897. if($this->patchValidate) { // 重置验证错误信息
  898. $this->error = array();
  899. }
  900. foreach($_validate as $key=>$val) {
  901. // 验证因子定义格式
  902. // array(field,rule,message,condition,type,when,params)
  903. // 判断是否需要执行验证
  904. if(empty($val[5]) || $val[5]== self::MODEL_BOTH || $val[5]== $type ) {
  905. if(0==strpos($val[2],'{%') && strpos($val[2],'}'))
  906. // 支持提示信息的多语言 使用 {%语言定义} 方式
  907. $val[2] = L(substr($val[2],2,-1));
  908. $val[3] = isset($val[3])?$val[3]:self::EXISTS_VALIDATE;
  909. $val[4] = isset($val[4])?$val[4]:'regex';
  910. // 判断验证条件
  911. switch($val[3]) {
  912. case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段
  913. if(false === $this->_validationField($data,$val))
  914. return false;
  915. break;
  916. case self::VALUE_VALIDATE: // 值不为空的时候才验证
  917. if('' != trim($data[$val[0]]))
  918. if(false === $this->_validationField($data,$val))
  919. return false;
  920. break;
  921. default: // 默认表单存在该字段就验证
  922. if(isset($data[$val[0]]))
  923. if(false === $this->_validationField($data,$val))
  924. return false;
  925. }
  926. }
  927. }
  928. // 批量验证的时候最后返回错误
  929. if(!empty($this->error)) return false;
  930. }
  931. return true;
  932. }
  933. /**
  934. * 验证表单字段 支持批量验证
  935. * 如果批量验证返回错误的数组信息
  936. * @access protected
  937. * @param array $data 创建数据
  938. * @param array $val 验证因子
  939. * @return boolean
  940. */
  941. protected function _validationField($data,$val) {
  942. if(false === $this->_validationFieldItem($data,$val)){
  943. if($this->patchValidate) {
  944. $this->error[$val[0]] = $val[2];
  945. }else{
  946. $this->error = $val[2];
  947. return false;
  948. }
  949. }
  950. return ;
  951. }
  952. /**
  953. * 根据验证因子验证字段
  954. * @access protected
  955. * @param array $data 创建数据
  956. * @param array $val 验证因子
  957. * @return boolean
  958. */
  959. protected function _validationFieldItem($data,$val) {
  960. switch(strtolower(trim($val[4]))) {
  961. case 'function':// 使用函数进行验证
  962. case 'callback':// 调用方法进行验证
  963. $args = isset($val[6])?(array)$val[6]:array();
  964. if(is_string($val[0]) && strpos($val[0], ','))
  965. $val[0] = explode(',', $val[0]);
  966. if(is_array($val[0])){
  967. // 支持多个字段验证
  968. foreach($val[0] as $field)
  969. $_data[$field] = $data[$field];
  970. array_unshift($args, $_data);
  971. }else{
  972. array_unshift($args, $data[$val[0]]);
  973. }
  974. if('function'==$val[4]) {
  975. return call_user_func_array($val[1], $args);
  976. }else{
  977. return call_user_func_array(array(&$this, $val[1]), $args);
  978. }
  979. case 'confirm': // 验证两个字段是否相同
  980. return $data[$val[0]] == $data[$val[1]];
  981. case 'unique': // 验证某个值是否唯一
  982. if(is_string($val[0]) && strpos($val[0],','))
  983. $val[0] = explode(',',$val[0]);
  984. $map = array();
  985. if(is_array($val[0])) {
  986. // 支持多个字段验证
  987. foreach ($val[0] as $field)
  988. $map[$field] = $data[$field];
  989. }else{
  990. $map[$val[0]] = $data[$val[0]];
  991. }
  992. if(!empty($data[$this->getPk()])) { // 完善编辑的时候验证唯一
  993. $map[$this->getPk()] = array('neq',$data[$this->getPk()]);
  994. }
  995. if($this->where($map)->find()) return false;
  996. return true;
  997. default: // 检查附加规则
  998. return $this->check($data[$val[0]],$val[1],$val[4]);
  999. }
  1000. }
  1001. /**
  1002. * 验证数据 支持 in between equal length regex expire ip_allow ip_deny
  1003. * @access public
  1004. * @param string $value 验证数据
  1005. * @param mixed $rule 验证表达式
  1006. * @param string $type 验证方式 默认为正则验证
  1007. * @return boolean
  1008. */
  1009. public function check($value,$rule,$type='regex'){
  1010. $type = strtolower(trim($type));
  1011. switch($type) {
  1012. case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
  1013. case 'notin':
  1014. $range = is_array($rule)? $rule : explode(',',$rule);
  1015. return $type == 'in' ? in_array($value ,$range) : !in_array($value ,$range);
  1016. case 'between': // 验证是否在某个范围
  1017. case 'notbetween': // 验证是否不在某个范围
  1018. if (is_array($rule)){
  1019. $min = $rule[0];
  1020. $max = $rule[1];
  1021. }else{
  1022. list($min,$max) = explode(',',$rule);
  1023. }
  1024. return $type == 'between' ? $value>=$min && $value<=$max : $value<$min || $value>$max;
  1025. case 'equal': // 验证是否等于某个值
  1026. case 'notequal': // 验证是否等于某个值
  1027. return $type == 'equal' ? $value == $rule : $value != $rule;
  1028. case 'length': // 验证长度
  1029. $length = mb_strlen($value,'utf-8'); // 当前数据长度
  1030. if(strpos($rule,',')) { // 长度区间
  1031. list($min,$max) = explode(',',$rule);
  1032. return $length >= $min && $length <= $max;
  1033. }else{// 指定长度
  1034. return $length == $rule;
  1035. }
  1036. case 'expire':
  1037. list($start,$end) = explode(',',$rule);
  1038. if(!is_numeric($start)) $start = strtotime($start);
  1039. if(!is_numeric($end)) $end = strtotime($end);
  1040. return NOW_TIME >= $start && NOW_TIME <= $end;
  1041. case 'ip_allow': // IP 操作许可验证
  1042. return in_array(get_client_ip(),explode(',',$rule));
  1043. case 'ip_deny': // IP 操作禁止验证
  1044. return !in_array(get_client_ip(),explode(',',$rule));
  1045. case 'regex':
  1046. default: // 默认使用正则验证 可以使用验证类中定义的验证名称
  1047. // 检查附加规则
  1048. return $this->regex($value,$rule);
  1049. }
  1050. }
  1051. /**
  1052. * SQL查询
  1053. * @access public
  1054. * @param string $sql SQL指令
  1055. * @param mixed $parse 是否需要解析SQL
  1056. * @return mixed
  1057. */
  1058. public function query($sql,$parse=false) {
  1059. if(!is_bool($parse) && !is_array($parse)) {
  1060. $parse = func_get_args();
  1061. array_shift($parse);
  1062. }
  1063. $sql = $this->parseSql($sql,$parse);
  1064. return $this->db->query($sql);
  1065. }
  1066. /**
  1067. * 执行SQL语句
  1068. * @access public
  1069. * @param string $sql SQL指令
  1070. * @param mixed $parse 是否需要解析SQL
  1071. * @return false | integer
  1072. */
  1073. public function execute($sql,$parse=false) {
  1074. if(!is_bool($parse) && !is_array($parse)) {
  1075. $parse = func_get_args();
  1076. array_shift($parse);
  1077. }
  1078. $sql = $this->parseSql($sql,$parse);
  1079. return $this->db->execute($sql);
  1080. }
  1081. /**
  1082. * 解析SQL语句
  1083. * @access public
  1084. * @param string $sql SQL指令
  1085. * @param boolean $parse 是否需要解析SQL
  1086. * @return string
  1087. */
  1088. protected function parseSql($sql,$parse) {
  1089. // 分析表达式
  1090. if(true === $parse) {
  1091. $options = $this->_parseOptions();
  1092. $sql = $this->db->parseSql($sql,$options);
  1093. }elseif(is_array($parse)){ // SQL预处理
  1094. $sql = vsprintf($sql,$parse);
  1095. }else{
  1096. $sql = strtr($sql,array('__TABLE__'=>$this->getTableName(),'__PREFIX__'=>C('DB_PREFIX')));
  1097. }
  1098. $this->db->setModel($this->name);
  1099. return $sql;
  1100. }
  1101. /**
  1102. * 切换当前的数据库连接
  1103. * @access public
  1104. * @param integer $linkNum 连接序号
  1105. * @param mixed $config 数据库连接信息
  1106. * @param array $params 模型参数
  1107. * @return Model
  1108. */
  1109. public function db($linkNum='',$config='',$params=array()){
  1110. if(''===$linkNum && $this->db) {
  1111. return $this->db;
  1112. }
  1113. static $_linkNum = array();
  1114. static $_db = array();
  1115. if(!isset($_db[$linkNum]) || (isset($_db[$linkNum]) && $config && $_linkNum[$linkNum]!=$config) ) {
  1116. // 创建一个新的实例
  1117. if(!empty($config) && is_string($config) && false === strpos($config,'/')) { // 支持读取配置参数
  1118. $config = C($config);
  1119. }
  1120. $_db[$linkNum] = Db::getInstance($config);
  1121. }elseif(NULL === $config){
  1122. $_db[$linkNum]->close(); // 关闭数据库连接
  1123. unset($_db[$linkNum]);
  1124. return ;
  1125. }
  1126. if(!empty($params)) {
  1127. if(is_string($params)) parse_str($params,$params);
  1128. foreach ($params as $name=>$value){
  1129. $this->setProperty($name,$value);
  1130. }
  1131. }
  1132. // 记录连接信息
  1133. $_linkNum[$linkNum] = $config;
  1134. // 切换数据库连接
  1135. $this->db = $_db[$linkNum];
  1136. $this->_after_db();
  1137. // 字段检测
  1138. if(!empty($this->name) && $this->autoCheckFields) $this->_checkTableInfo();
  1139. return $this;
  1140. }
  1141. // 数据库切换后回调方法
  1142. protected function _after_db() {}
  1143. /**
  1144. * 得到当前的数据对象名称
  1145. * @access public
  1146. * @return string
  1147. */
  1148. public function getModelName() {
  1149. if(empty($this->name))
  1150. $this->name = substr(get_class($this),0,-5);
  1151. return $this->name;
  1152. }
  1153. /**
  1154. * 得到完整的数据表名
  1155. * @access public
  1156. * @return string
  1157. */
  1158. public function getTableName() {
  1159. if(empty($this->trueTableName)) {
  1160. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  1161. if(!empty($this->tableName)) {
  1162. $tableName .= $this->tableName;
  1163. }else{
  1164. $tableName .= parse_name($this->name);
  1165. }
  1166. $this->trueTableName = strtolower($tableName);
  1167. }
  1168. return (!empty($this->dbName)?$this->dbName.'.':'').$this->trueTableName;
  1169. }
  1170. /**
  1171. * 启动事务
  1172. * @access public
  1173. * @return void
  1174. */
  1175. public function startTrans() {
  1176. $this->commit();
  1177. $this->db->startTrans();
  1178. return ;
  1179. }
  1180. /**
  1181. * 提交事务
  1182. * @access public
  1183. * @return boolean
  1184. */
  1185. public function commit() {
  1186. return $this->db->commit();
  1187. }
  1188. /**
  1189. * 事务回滚
  1190. * @access public
  1191. * @return boolean
  1192. */
  1193. public function rollback() {
  1194. return $this->db->rollback();
  1195. }
  1196. /**
  1197. * 返回模型的错误信息
  1198. * @access public
  1199. * @return string
  1200. */
  1201. public function getError(){
  1202. return $this->error;
  1203. }
  1204. /**
  1205. * 返回数据库的错误信息
  1206. * @access public
  1207. * @return string
  1208. */
  1209. public function getDbError() {
  1210. return $this->db->getError();
  1211. }
  1212. /**
  1213. * 返回最后插入的ID
  1214. * @access public
  1215. * @return string
  1216. */
  1217. public function getLastInsID() {
  1218. return $this->db->getLastInsID();
  1219. }
  1220. /**
  1221. * 返回最后执行的sql语句
  1222. * @access public
  1223. * @return string
  1224. */
  1225. public function getLastSql() {
  1226. return $this->db->getLastSql($this->name);
  1227. }
  1228. // 鉴于getLastSql比较常用 增加_sql 别名
  1229. public function _sql(){
  1230. return $this->getLastSql();
  1231. }
  1232. /**
  1233. * 获取主键名称
  1234. * @access public
  1235. * @return string
  1236. */
  1237. public function getPk() {
  1238. return isset($this->fields['_pk'])?$this->fields['_pk']:$this->pk;
  1239. }
  1240. /**
  1241. * 获取数据表字段信息
  1242. * @access public
  1243. * @return array
  1244. */
  1245. public function getDbFields(){
  1246. if(isset($this->options['table'])) {// 动态指定表名
  1247. $fields = $this->db->getFields($this->options['table']);
  1248. return $fields?array_keys($fields):false;
  1249. }
  1250. if($this->fields) {
  1251. $fields = $this->fields;
  1252. unset($fields['_autoinc'],$fields['_pk'],$fields['_type'],$fields['_version']);
  1253. return $fields;
  1254. }
  1255. return false;
  1256. }
  1257. /**
  1258. * 设置数据对象值
  1259. * @access public
  1260. * @param mixed $data 数据
  1261. * @return Model
  1262. */
  1263. public function data($data=''){
  1264. if('' === $data && !empty($this->data)) {
  1265. return $this->data;
  1266. }
  1267. if(is_object($data)){
  1268. $data = get_object_vars($data);
  1269. }elseif(is_string($data)){
  1270. parse_str($data,$data);
  1271. }elseif(!is_array($data)){
  1272. throw_exception(L('_DATA_TYPE_INVALID_'));
  1273. }
  1274. $this->data = $data;
  1275. return $this;
  1276. }
  1277. /**
  1278. * 查询SQL组装 join
  1279. * @access public
  1280. * @param mixed $join
  1281. * @return Model
  1282. */
  1283. public function join($join) {
  1284. if(is_array($join)) {
  1285. $this->options['join'] = $join;
  1286. }elseif(!empty($join)) {
  1287. $this->options['join'][] = $join;
  1288. }
  1289. return $this;
  1290. }
  1291. /**
  1292. * 查询SQL组装 union
  1293. * @access public
  1294. * @param mixed $union
  1295. * @param boolean $all
  1296. * @return Model
  1297. */
  1298. public function union($union,$all=false) {
  1299. if(empty($union)) return $this;
  1300. if($all) {
  1301. $this->options['union']['_all'] = true;
  1302. }
  1303. if(is_object($union)) {
  1304. $union = get_object_vars($union);
  1305. }
  1306. // 转换union表达式
  1307. if(is_string($union) ) {
  1308. $options = $union;
  1309. }elseif(is_array($union)){
  1310. if(isset($union[0])) {
  1311. $this->options['union'] = array_merge($this->options['union'],$union);
  1312. return $this;
  1313. }else{
  1314. $options = $union;
  1315. }
  1316. }else{
  1317. throw_exception(L('_DATA_TYPE_INVALID_'));
  1318. }
  1319. $this->options['union'][] = $options;
  1320. return $this;
  1321. }
  1322. /**
  1323. * 查询缓存
  1324. * @access public
  1325. * @param mixed $key
  1326. * @param integer $expire
  1327. * @param string $type
  1328. * @return Model
  1329. */
  1330. public function cache($key=true,$expire=null,$type=''){
  1331. if(false !== $key)
  1332. $this->options['cache'] = array('key'=>$key,'expire'=>$expire,'type'=>$type);
  1333. return $this;
  1334. }
  1335. /**
  1336. * 指定查询字段 支持字段排除
  1337. * @access public
  1338. * @param mixed $field
  1339. * @param boolean $except 是否排除
  1340. * @return Model
  1341. */
  1342. public function field($field,$except=false){
  1343. if(true === $field) {// 获取全部字段
  1344. $fields = $this->getDbFields();
  1345. $field = $fields?$fields:'*';
  1346. }elseif($except) {// 字段排除
  1347. if(is_string($field)) {
  1348. $field = explode(',',$field);
  1349. }
  1350. $fields = $this->getDbFields();
  1351. $field = $fields?array_diff($fields,$field):$field;
  1352. }
  1353. $this->options['field'] = $field;
  1354. return $this;
  1355. }
  1356. /**
  1357. * 调用命名范围
  1358. * @access public
  1359. * @param mixed $scope 命名范围名称 支持多个 …

Large files files are truncated, but you can click here to view the full file