You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2124 line
67 KiB

3 年之前
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2014 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. namespace Think;
  12. /**
  13. * ThinkPHP Model模型类
  14. * 实现了ORM和ActiveRecords模式
  15. */
  16. class Model
  17. {
  18. // 操作状态
  19. const MODEL_INSERT = 1; // 插入模型数据
  20. const MODEL_UPDATE = 2; // 更新模型数据
  21. const MODEL_BOTH = 3; // 包含上面两种方式
  22. const MUST_VALIDATE = 1; // 必须验证
  23. const EXISTS_VALIDATE = 0; // 表单存在字段则验证
  24. const VALUE_VALIDATE = 2; // 表单值不为空则验证
  25. // 当前数据库操作对象
  26. protected $db = null;
  27. // 数据库对象池
  28. private $_db = array();
  29. // 主键名称
  30. protected $pk = 'id';
  31. // 主键是否自动增长
  32. protected $autoinc = false;
  33. // 数据表前缀
  34. protected $tablePrefix = null;
  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('strict', 'order', 'alias', 'having', 'group', 'lock', 'distinct', 'auto', 'filter', 'validate', 'result', 'token', 'index', 'force', 'master');
  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. // 模型初始化
  74. $this->_initialize();
  75. // 获取模型名称
  76. if (!empty($name)) {
  77. if (strpos($name, '.')) {
  78. // 支持 数据库名.模型名的 定义
  79. list($this->dbName, $this->name) = explode('.', $name);
  80. } else {
  81. $this->name = $name;
  82. }
  83. } elseif (empty($this->name)) {
  84. $this->name = $this->getModelName();
  85. }
  86. // 设置表前缀
  87. if (is_null($tablePrefix)) {
  88. // 前缀为Null表示没有前缀
  89. $this->tablePrefix = '';
  90. } elseif ('' != $tablePrefix) {
  91. $this->tablePrefix = $tablePrefix;
  92. } elseif (!isset($this->tablePrefix)) {
  93. $this->tablePrefix = !empty($this->connection) && !is_null(C($this->connection . '.DB_PREFIX')) ? C($this->connection . '.DB_PREFIX') : C('DB_PREFIX');
  94. }
  95. // 数据库初始化操作
  96. // 获取数据库操作对象
  97. // 当前模型有独立的数据库连接信息
  98. $this->db(0, empty($this->connection) ? $connection : $this->connection, true);
  99. }
  100. /**
  101. * 自动检测数据表信息
  102. * @access protected
  103. * @return void
  104. */
  105. protected function _checkTableInfo()
  106. {
  107. // 如果不是Model类 自动记录数据表信息
  108. // 只在第一次执行记录
  109. if (empty($this->fields)) {
  110. // 如果数据表字段没有定义则自动获取
  111. if (C('DB_FIELDS_CACHE')) {
  112. $fields = F('_fields/' . strtolower($this->getTableName()));
  113. if ($fields) {
  114. $this->fields = $fields;
  115. if (!empty($fields['_pk'])) {
  116. $this->pk = $fields['_pk'];
  117. }
  118. return;
  119. }
  120. }
  121. // 每次都会读取数据表信息
  122. $this->flush();
  123. }
  124. }
  125. /**
  126. * 获取字段信息并缓存
  127. * @access public
  128. * @return void
  129. */
  130. public function flush()
  131. {
  132. // 缓存不存在则查询数据表信息
  133. $this->db->setModel($this->name);
  134. $tableName = $this->getTableName();
  135. $fields = $this->db->getFields($tableName);
  136. if (!$fields) {
  137. // 无法获取字段信息
  138. return false;
  139. }
  140. $this->fields = array_keys($fields);
  141. unset($this->fields['_pk']);
  142. foreach ($fields as $key => $val) {
  143. // 记录字段类型
  144. $type[$key] = $val['type'];
  145. if ($val['primary']) {
  146. // 增加复合主键支持
  147. if (isset($this->fields['_pk']) && null != $this->fields['_pk']) {
  148. if (is_string($this->fields['_pk'])) {
  149. $this->pk = array($this->fields['_pk']);
  150. $this->fields['_pk'] = $this->pk;
  151. }
  152. $this->pk[] = $key;
  153. $this->fields['_pk'][] = $key;
  154. } else {
  155. $this->pk = $key;
  156. $this->fields['_pk'] = $key;
  157. }
  158. if ($val['autoinc']) {
  159. $this->autoinc = true;
  160. }
  161. }
  162. }
  163. // 记录字段类型信息
  164. $this->fields['_type'] = $type;
  165. // 2008-3-7 增加缓存开关控制
  166. if (C('DB_FIELDS_CACHE')) {
  167. // 永久缓存数据表信息
  168. F('_fields/' . strtolower($tableName), $this->fields);
  169. }
  170. }
  171. /**
  172. * 设置数据对象的值
  173. * @access public
  174. * @param string $name 名称
  175. * @param mixed $value
  176. * @return void
  177. */
  178. public function __set($name, $value)
  179. {
  180. // 设置数据对象属性
  181. $this->data[$name] = $value;
  182. }
  183. /**
  184. * 获取数据对象的值
  185. * @access public
  186. * @param string $name 名称
  187. * @return mixed
  188. */
  189. public function __get($name)
  190. {
  191. return isset($this->data[$name]) ? $this->data[$name] : null;
  192. }
  193. /**
  194. * 检测数据对象的值
  195. * @access public
  196. * @param string $name 名称
  197. * @return boolean
  198. */
  199. public function __isset($name)
  200. {
  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. {
  211. unset($this->data[$name]);
  212. }
  213. /**
  214. * 利用__call方法实现一些特殊的Model方法
  215. * @access public
  216. * @param string $method 方法名称
  217. * @param array $args 调用参数
  218. * @return mixed
  219. */
  220. public function __call($method, $args)
  221. {
  222. if (in_array(strtolower($method), $this->methods, true)) {
  223. // 连贯操作的实现
  224. $this->options[strtolower($method)] = $args[0];
  225. return $this;
  226. } elseif (in_array(strtolower($method), array('count', 'sum', 'min', 'max', 'avg'), true)) {
  227. // 统计查询的实现
  228. $field = isset($args[0]) ? $args[0] : '*';
  229. return $this->getField(strtoupper($method) . '(' . $this->db->parseKey($field, true) . ') AS tp_' . $method);
  230. } elseif (strtolower(substr($method, 0, 5)) == 'getby') {
  231. // 根据某个字段获取记录
  232. $field = parse_name(substr($method, 5));
  233. $where[$field] = $args[0];
  234. return $this->where($where)->find();
  235. } elseif (strtolower(substr($method, 0, 10)) == 'getfieldby') {
  236. // 根据某个字段获取记录的某个值
  237. $name = parse_name(substr($method, 10));
  238. $where[$name] = $args[0];
  239. return $this->where($where)->getField($args[1]);
  240. } elseif (isset($this->_scope[$method])) {
  241. // 命名范围的单独调用支持
  242. return $this->scope($method, $args[0]);
  243. } else {
  244. E(__CLASS__ . ':' . $method . L('_METHOD_NOT_EXIST_'));
  245. return;
  246. }
  247. }
  248. // 回调方法 初始化模型
  249. protected function _initialize()
  250. {}
  251. /**
  252. * 对保存到数据库的数据进行处理
  253. * @access protected
  254. * @param mixed $data 要操作的数据
  255. * @return boolean
  256. */
  257. protected function _facade($data)
  258. {
  259. // 检查数据字段合法性
  260. if (!empty($this->fields)) {
  261. if (!empty($this->options['field'])) {
  262. $fields = $this->options['field'];
  263. unset($this->options['field']);
  264. if (is_string($fields)) {
  265. $fields = explode(',', $fields);
  266. }
  267. } else {
  268. $fields = $this->fields;
  269. }
  270. foreach ($data as $key => $val) {
  271. if (!in_array($key, $fields, true)) {
  272. if (!empty($this->options['strict'])) {
  273. E(L('_DATA_TYPE_INVALID_') . ':[' . $key . '=>' . $val . ']');
  274. }
  275. unset($data[$key]);
  276. } elseif (is_scalar($val)) {
  277. // 字段类型检查 和 强制转换
  278. $this->_parseType($data, $key);
  279. }
  280. }
  281. }
  282. // 安全过滤
  283. if (!empty($this->options['filter'])) {
  284. $data = array_map($this->options['filter'], $data);
  285. unset($this->options['filter']);
  286. }
  287. $this->_before_write($data);
  288. return $data;
  289. }
  290. // 写入数据前的回调方法 包括新增和更新
  291. protected function _before_write(&$data)
  292. {}
  293. /**
  294. * 新增数据
  295. * @access public
  296. * @param mixed $data 数据
  297. * @param array $options 表达式
  298. * @param boolean $replace 是否replace
  299. * @return mixed
  300. */
  301. public function add($data = '', $options = array(), $replace = false)
  302. {
  303. if (empty($data)) {
  304. // 没有传递数据,获取当前数据对象的值
  305. if (!empty($this->data)) {
  306. $data = $this->data;
  307. // 重置数据
  308. $this->data = array();
  309. } else {
  310. $this->error = L('_DATA_TYPE_INVALID_');
  311. return false;
  312. }
  313. }
  314. // 数据处理
  315. $data = $this->_facade($data);
  316. // 分析表达式
  317. $options = $this->_parseOptions($options);
  318. if (false === $this->_before_insert($data, $options)) {
  319. return false;
  320. }
  321. // 写入数据到数据库
  322. $result = $this->db->insert($data, $options, $replace);
  323. if (false !== $result && is_numeric($result)) {
  324. $pk = $this->getPk();
  325. // 增加复合主键支持
  326. if (is_array($pk)) {
  327. return $result;
  328. }
  329. $insertId = $this->getLastInsID();
  330. if ($insertId) {
  331. // 自增主键返回插入ID
  332. $data[$pk] = $insertId;
  333. if (false === $this->_after_insert($data, $options)) {
  334. return false;
  335. }
  336. return $insertId;
  337. }
  338. if (false === $this->_after_insert($data, $options)) {
  339. return false;
  340. }
  341. }
  342. return $result;
  343. }
  344. // 插入数据前的回调方法
  345. protected function _before_insert(&$data, $options)
  346. {}
  347. // 插入成功后的回调方法
  348. protected function _after_insert($data, $options)
  349. {}
  350. public function addAll($dataList, $options = array(), $replace = false)
  351. {
  352. if (empty($dataList)) {
  353. $this->error = L('_DATA_TYPE_INVALID_');
  354. return false;
  355. }
  356. // 数据处理
  357. foreach ($dataList as $key => $data) {
  358. $dataList[$key] = $this->_facade($data);
  359. }
  360. // 分析表达式
  361. $options = $this->_parseOptions($options);
  362. // 写入数据到数据库
  363. $result = $this->db->insertAll($dataList, $options, $replace);
  364. if (false !== $result) {
  365. $insertId = $this->getLastInsID();
  366. if ($insertId) {
  367. return $insertId;
  368. }
  369. }
  370. return $result;
  371. }
  372. /**
  373. * 通过Select方式添加记录
  374. * @access public
  375. * @param string $fields 要插入的数据表字段名
  376. * @param string $table 要插入的数据表名
  377. * @param array $options 表达式
  378. * @return boolean
  379. */
  380. public function selectAdd($fields = '', $table = '', $options = array())
  381. {
  382. // 分析表达式
  383. $options = $this->_parseOptions($options);
  384. // 写入数据到数据库
  385. if (false === $result = $this->db->selectInsert($fields ?: $options['field'], $table ?: $this->getTableName(), $options)) {
  386. // 数据库插入操作失败
  387. $this->error = L('_OPERATION_WRONG_');
  388. return false;
  389. } else {
  390. // 插入成功
  391. return $result;
  392. }
  393. }
  394. /**
  395. * 保存数据
  396. * @access public
  397. * @param mixed $data 数据
  398. * @param array $options 表达式
  399. * @return boolean
  400. */
  401. public function save($data = '', $options = array())
  402. {
  403. if (empty($data)) {
  404. // 没有传递数据,获取当前数据对象的值
  405. if (!empty($this->data)) {
  406. $data = $this->data;
  407. // 重置数据
  408. $this->data = array();
  409. } else {
  410. $this->error = L('_DATA_TYPE_INVALID_');
  411. return false;
  412. }
  413. }
  414. // 数据处理
  415. $data = $this->_facade($data);
  416. if (empty($data)) {
  417. // 没有数据则不执行
  418. $this->error = L('_DATA_TYPE_INVALID_');
  419. return false;
  420. }
  421. // 分析表达式
  422. $options = $this->_parseOptions($options);
  423. $pk = $this->getPk();
  424. if (!isset($options['where'])) {
  425. // 如果存在主键数据 则自动作为更新条件
  426. if (is_string($pk) && isset($data[$pk])) {
  427. $where[$pk] = $data[$pk];
  428. unset($data[$pk]);
  429. } elseif (is_array($pk)) {
  430. // 增加复合主键支持
  431. foreach ($pk as $field) {
  432. if (isset($data[$field])) {
  433. $where[$field] = $data[$field];
  434. } else {
  435. // 如果缺少复合主键数据则不执行
  436. $this->error = L('_OPERATION_WRONG_');
  437. return false;
  438. }
  439. unset($data[$field]);
  440. }
  441. }
  442. if (!isset($where)) {
  443. // 如果没有任何更新条件则不执行
  444. $this->error = L('_OPERATION_WRONG_');
  445. return false;
  446. } else {
  447. $options['where'] = $where;
  448. }
  449. }
  450. if (is_array($options['where']) && isset($options['where'][$pk])) {
  451. $pkValue = $options['where'][$pk];
  452. }
  453. if (false === $this->_before_update($data, $options)) {
  454. return false;
  455. }
  456. $result = $this->db->update($data, $options);
  457. if (false !== $result && is_numeric($result)) {
  458. if (isset($pkValue)) {
  459. $data[$pk] = $pkValue;
  460. }
  461. $this->_after_update($data, $options);
  462. }
  463. return $result;
  464. }
  465. // 更新数据前的回调方法
  466. protected function _before_update(&$data, $options)
  467. {}
  468. // 更新成功后的回调方法
  469. protected function _after_update($data, $options)
  470. {}
  471. /**
  472. * 删除数据
  473. * @access public
  474. * @param mixed $options 表达式
  475. * @return mixed
  476. */
  477. public function delete($options = array())
  478. {
  479. $pk = $this->getPk();
  480. if (empty($options) && empty($this->options['where'])) {
  481. // 如果删除条件为空 则删除当前数据对象所对应的记录
  482. if (!empty($this->data) && isset($this->data[$pk])) {
  483. return $this->delete($this->data[$pk]);
  484. } else {
  485. return false;
  486. }
  487. }
  488. if (is_numeric($options) || is_string($options)) {
  489. // 根据主键删除记录
  490. if (strpos($options, ',')) {
  491. $where[$pk] = array('IN', $options);
  492. } else {
  493. $where[$pk] = $options;
  494. }
  495. $this->options['where'] = $where;
  496. }
  497. // 根据复合主键删除记录
  498. if (is_array($options) && (count($options) > 0) && is_array($pk)) {
  499. $count = 0;
  500. foreach (array_keys($options) as $key) {
  501. if (is_int($key)) {
  502. $count++;
  503. }
  504. }
  505. if (count($pk) == $count) {
  506. $i = 0;
  507. foreach ($pk as $field) {
  508. $where[$field] = $options[$i];
  509. unset($options[$i++]);
  510. }
  511. $this->options['where'] = $where;
  512. } else {
  513. return false;
  514. }
  515. }
  516. // 分析表达式
  517. $options = $this->_parseOptions();
  518. if (empty($options['where'])) {
  519. // 如果条件为空 不进行删除操作 除非设置 1=1
  520. return false;
  521. }
  522. if (is_array($options['where']) && isset($options['where'][$pk])) {
  523. $pkValue = $options['where'][$pk];
  524. }
  525. if (false === $this->_before_delete($options)) {
  526. return false;
  527. }
  528. $result = $this->db->delete($options);
  529. if (false !== $result && is_numeric($result)) {
  530. $data = array();
  531. if (isset($pkValue)) {
  532. $data[$pk] = $pkValue;
  533. }
  534. $this->_after_delete($data, $options);
  535. }
  536. // 返回删除记录个数
  537. return $result;
  538. }
  539. // 删除数据前的回调方法
  540. protected function _before_delete($options)
  541. {}
  542. // 删除成功后的回调方法
  543. protected function _after_delete($data, $options)
  544. {}
  545. /**
  546. * 查询数据集
  547. * @access public
  548. * @param array $options 表达式参数
  549. * @return mixed
  550. */
  551. public function select($options = array())
  552. {
  553. $pk = $this->getPk();
  554. if (is_string($options) || is_numeric($options)) {
  555. // 根据主键查询
  556. if (strpos($options, ',')) {
  557. $where[$pk] = array('IN', $options);
  558. } else {
  559. $where[$pk] = $options;
  560. }
  561. $this->options['where'] = $where;
  562. } elseif (is_array($options) && (count($options) > 0) && is_array($pk)) {
  563. // 根据复合主键查询
  564. $count = 0;
  565. foreach (array_keys($options) as $key) {
  566. if (is_int($key)) {
  567. $count++;
  568. }
  569. }
  570. if (count($pk) == $count) {
  571. $i = 0;
  572. foreach ($pk as $field) {
  573. $where[$field] = $options[$i];
  574. unset($options[$i++]);
  575. }
  576. $this->options['where'] = $where;
  577. } else {
  578. return false;
  579. }
  580. } elseif (false === $options) {
  581. // 用于子查询 不查询只返回SQL
  582. $this->options['fetch_sql'] = true;
  583. }
  584. // 分析表达式
  585. $options = $this->_parseOptions();
  586. // 判断查询缓存
  587. if (isset($options['cache'])) {
  588. $cache = $options['cache'];
  589. $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
  590. $data = S($key, '', $cache);
  591. if (false !== $data) {
  592. return $data;
  593. }
  594. }
  595. $resultSet = $this->db->select($options);
  596. if (false === $resultSet) {
  597. return false;
  598. }
  599. if (!empty($resultSet)) {
  600. // 有查询结果
  601. if (is_string($resultSet)) {
  602. return $resultSet;
  603. }
  604. $resultSet = array_map(array($this, '_read_data'), $resultSet);
  605. $this->_after_select($resultSet, $options);
  606. if (isset($options['index'])) {
  607. // 对数据集进行索引
  608. $index = explode(',', $options['index']);
  609. foreach ($resultSet as $result) {
  610. $_key = $result[$index[0]];
  611. if (isset($index[1]) && isset($result[$index[1]])) {
  612. $cols[$_key] = $result[$index[1]];
  613. } else {
  614. $cols[$_key] = $result;
  615. }
  616. }
  617. $resultSet = $cols;
  618. }
  619. }
  620. if (isset($cache)) {
  621. S($key, $resultSet, $cache);
  622. }
  623. return $resultSet;
  624. }
  625. // 查询成功后的回调方法
  626. protected function _after_select(&$resultSet, $options)
  627. {}
  628. /**
  629. * 生成查询SQL 可用于子查询
  630. * @access public
  631. * @return string
  632. */
  633. public function buildSql()
  634. {
  635. return '( ' . $this->fetchSql(true)->select() . ' )';
  636. }
  637. /**
  638. * 分析表达式
  639. * @access protected
  640. * @param array $options 表达式参数
  641. * @return array
  642. */
  643. protected function _parseOptions($options = array())
  644. {
  645. if (is_array($options)) {
  646. $options = array_merge($this->options, $options);
  647. }
  648. if (!isset($options['table'])) {
  649. // 自动获取表名
  650. $options['table'] = $this->getTableName();
  651. $fields = $this->fields;
  652. } else {
  653. // 指定数据表 则重新获取字段列表 但不支持类型检测
  654. $fields = $this->getDbFields();
  655. }
  656. // 数据表别名
  657. if (!empty($options['alias'])) {
  658. $options['table'] .= ' ' . $options['alias'];
  659. }
  660. // 记录操作的模型名称
  661. $options['model'] = $this->name;
  662. // 字段类型验证
  663. if (isset($options['where']) && is_array($options['where']) && !empty($fields) && !isset($options['join'])) {
  664. // 对数组查询条件进行字段类型检查
  665. foreach ($options['where'] as $key => $val) {
  666. $key = trim($key);
  667. if (in_array($key, $fields, true)) {
  668. if (is_scalar($val)) {
  669. $this->_parseType($options['where'], $key);
  670. }
  671. }
  672. }
  673. }
  674. // 查询过后清空sql表达式组装 避免影响下次查询
  675. $this->options = array();
  676. // 表达式过滤
  677. $this->_options_filter($options);
  678. return $options;
  679. }
  680. // 表达式过滤回调方法
  681. protected function _options_filter(&$options)
  682. {}
  683. /**
  684. * 数据类型检测
  685. * @access protected
  686. * @param mixed $data 数据
  687. * @param string $key 字段名
  688. * @return void
  689. */
  690. protected function _parseType(&$data, $key)
  691. {
  692. if (!isset($this->options['bind'][':' . $key]) && isset($this->fields['_type'][$key])) {
  693. $fieldType = strtolower($this->fields['_type'][$key]);
  694. if (false !== strpos($fieldType, 'enum')) {
  695. // 支持ENUM类型优先检测
  696. } elseif (false === strpos($fieldType, 'bigint') && false !== strpos($fieldType, 'int')) {
  697. $data[$key] = intval($data[$key]);
  698. } elseif (false !== strpos($fieldType, 'float') || false !== strpos($fieldType, 'double')) {
  699. $data[$key] = floatval($data[$key]);
  700. } elseif (false !== strpos($fieldType, 'bool')) {
  701. $data[$key] = (bool) $data[$key];
  702. }
  703. }
  704. }
  705. /**
  706. * 数据读取后的处理
  707. * @access protected
  708. * @param array $data 当前数据
  709. * @return array
  710. */
  711. protected function _read_data($data)
  712. {
  713. // 检查字段映射
  714. if (!empty($this->_map) && C('READ_DATA_MAP')) {
  715. foreach ($this->_map as $key => $val) {
  716. if (isset($data[$val])) {
  717. $data[$key] = $data[$val];
  718. unset($data[$val]);
  719. }
  720. }
  721. }
  722. return $data;
  723. }
  724. /**
  725. * 查询数据
  726. * @access public
  727. * @param mixed $options 表达式参数
  728. * @return mixed
  729. */
  730. public function find($options = array())
  731. {
  732. if (is_numeric($options) || is_string($options)) {
  733. $where[$this->getPk()] = $options;
  734. $this->options['where'] = $where;
  735. }
  736. // 根据复合主键查找记录
  737. $pk = $this->getPk();
  738. if (is_array($options) && (count($options) > 0) && is_array($pk)) {
  739. // 根据复合主键查询
  740. $count = 0;
  741. foreach (array_keys($options) as $key) {
  742. if (is_int($key)) {
  743. $count++;
  744. }
  745. }
  746. if (count($pk) == $count) {
  747. $i = 0;
  748. foreach ($pk as $field) {
  749. $where[$field] = $options[$i];
  750. unset($options[$i++]);
  751. }
  752. $this->options['where'] = $where;
  753. } else {
  754. return false;
  755. }
  756. }
  757. // 总是查找一条记录
  758. $this->options['limit'] = 1;
  759. // 分析表达式
  760. $options = $this->_parseOptions();
  761. // 判断查询缓存
  762. if (isset($options['cache'])) {
  763. $cache = $options['cache'];
  764. $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
  765. $data = S($key, '', $cache);
  766. if (false !== $data) {
  767. $this->data = $data;
  768. return $data;
  769. }
  770. }
  771. $resultSet = $this->db->select($options);
  772. if (false === $resultSet) {
  773. return false;
  774. }
  775. if (empty($resultSet)) {
  776. // 查询结果为空
  777. return null;
  778. }
  779. if (is_string($resultSet)) {
  780. return $resultSet;
  781. }
  782. // 读取数据后的处理
  783. $data = $this->_read_data($resultSet[0]);
  784. $this->_after_find($data, $options);
  785. if (!empty($options['result'])) {
  786. return $this->returnResult($data, $options['result']);
  787. }
  788. $this->data = $data;
  789. if (isset($cache)) {
  790. S($key, $data, $cache);
  791. }
  792. return $this->data;
  793. }
  794. // 查询成功的回调方法
  795. protected function _after_find(&$result, $options)
  796. {}
  797. protected function returnResult($data, $type = '')
  798. {
  799. if ($type) {
  800. if (is_callable($type)) {
  801. return call_user_func($type, $data);
  802. }
  803. switch (strtolower($type)) {
  804. case 'json':
  805. return json_encode($data);
  806. case 'xml':
  807. return xml_encode($data);
  808. }
  809. }
  810. return $data;
  811. }
  812. /**
  813. * 处理字段映射
  814. * @access public
  815. * @param array $data 当前数据
  816. * @param integer $type 类型 0 写入 1 读取
  817. * @return array
  818. */
  819. public function parseFieldsMap($data, $type = 1)
  820. {
  821. // 检查字段映射
  822. if (!empty($this->_map)) {
  823. foreach ($this->_map as $key => $val) {
  824. if (1 == $type) {
  825. // 读取
  826. if (isset($data[$val])) {
  827. $data[$key] = $data[$val];
  828. unset($data[$val]);
  829. }
  830. } else {
  831. if (isset($data[$key])) {
  832. $data[$val] = $data[$key];
  833. unset($data[$key]);
  834. }
  835. }
  836. }
  837. }
  838. return $data;
  839. }
  840. /**
  841. * 设置记录的某个字段值
  842. * 支持使用数据库字段和方法
  843. * @access public
  844. * @param string|array $field 字段名
  845. * @param string $value 字段值
  846. * @return boolean
  847. */
  848. public function setField($field, $value = '')
  849. {
  850. if (is_array($field)) {
  851. $data = $field;
  852. } else {
  853. $data[$field] = $value;
  854. }
  855. return $this->save($data);
  856. }
  857. /**
  858. * 字段值增长
  859. * @access public
  860. * @param string $field 字段名
  861. * @param integer $step 增长值
  862. * @param integer $lazyTime 延时时间(s)
  863. * @return boolean
  864. */
  865. public function setInc($field, $step = 1, $lazyTime = 0)
  866. {
  867. if ($lazyTime > 0) {
  868. // 延迟写入
  869. $condition = $this->options['where'];
  870. $guid = md5($this->name . '_' . $field . '_' . serialize($condition));
  871. $step = $this->lazyWrite($guid, $step, $lazyTime);
  872. if (empty($step)) {
  873. return true; // 等待下次写入
  874. } elseif ($step < 0) {
  875. $step = '-' . $step;
  876. }
  877. }
  878. return $this->setField($field, array('exp', $field . '+' . $step));
  879. }
  880. /**
  881. * 字段值减少
  882. * @access public
  883. * @param string $field 字段名
  884. * @param integer $step 减少值
  885. * @param integer $lazyTime 延时时间(s)
  886. * @return boolean
  887. */
  888. public function setDec($field, $step = 1, $lazyTime = 0)
  889. {
  890. if ($lazyTime > 0) {
  891. // 延迟写入
  892. $condition = $this->options['where'];
  893. $guid = md5($this->name . '_' . $field . '_' . serialize($condition));
  894. $step = $this->lazyWrite($guid, -$step, $lazyTime);
  895. if (empty($step)) {
  896. return true; // 等待下次写入
  897. } elseif ($step > 0) {
  898. $step = '-' . $step;
  899. }
  900. }
  901. return $this->setField($field, array('exp', $field . '-' . $step));
  902. }
  903. /**
  904. * 延时更新检查 返回false表示需要延时
  905. * 否则返回实际写入的数值
  906. * @access public
  907. * @param string $guid 写入标识
  908. * @param integer $step 写入步进值
  909. * @param integer $lazyTime 延时时间(s)
  910. * @return false|integer
  911. */
  912. protected function lazyWrite($guid, $step, $lazyTime)
  913. {
  914. if (false !== ($value = S($guid))) {
  915. // 存在缓存写入数据
  916. if (NOW_TIME > S($guid . '_time') + $lazyTime) {
  917. // 延时更新时间到了,删除缓存数据 并实际写入数据库
  918. S($guid, null);
  919. S($guid . '_time', null);
  920. return $value + $step;
  921. } else {
  922. // 追加数据到缓存
  923. S($guid, $value + $step, 0);
  924. return false;
  925. }
  926. } else {
  927. // 没有缓存数据
  928. S($guid, $step, 0);
  929. // 计时开始
  930. S($guid . '_time', NOW_TIME, 0);
  931. return false;
  932. }
  933. }
  934. /**
  935. * 获取一条记录的某个字段值
  936. * @access public
  937. * @param string $field 字段名
  938. * @param string $spea 字段数据间隔符号 NULL返回数组
  939. * @return mixed
  940. */
  941. public function getField($field, $sepa = null)
  942. {
  943. $options['field'] = $field;
  944. $options = $this->_parseOptions($options);
  945. // 判断查询缓存
  946. if (isset($options['cache'])) {
  947. $cache = $options['cache'];
  948. $key = is_string($cache['key']) ? $cache['key'] : md5($sepa . serialize($options));
  949. $data = S($key, '', $cache);
  950. if (false !== $data) {
  951. return $data;
  952. }
  953. }
  954. $field = trim($field);
  955. if (strpos($field, ',') && false !== $sepa) {
  956. // 多字段
  957. if (!isset($options['limit'])) {
  958. $options['limit'] = is_numeric($sepa) ? $sepa : '';
  959. }
  960. $resultSet = $this->db->select($options);
  961. if (!empty($resultSet)) {
  962. if (is_string($resultSet)) {
  963. return $resultSet;
  964. }
  965. $_field = explode(',', $field);
  966. $field = array_keys($resultSet[0]);
  967. $key1 = array_shift($field);
  968. $key2 = array_shift($field);
  969. $cols = array();
  970. $count = count($_field);
  971. foreach ($resultSet as $result) {
  972. $name = $result[$key1];
  973. if (2 == $count) {
  974. $cols[$name] = $result[$key2];
  975. } else {
  976. $cols[$name] = is_string($sepa) ? implode($sepa, array_slice($result, 1)) : $result;
  977. }
  978. }
  979. if (isset($cache)) {
  980. S($key, $cols, $cache);
  981. }
  982. return $cols;
  983. }
  984. } else {
  985. // 查找一条记录
  986. // 返回数据个数
  987. if (true !== $sepa) {
  988. // 当sepa指定为true的时候 返回所有数据
  989. $options['limit'] = is_numeric($sepa) ? $sepa : 1;
  990. }
  991. $result = $this->db->select($options);
  992. if (!empty($result)) {
  993. if (is_string($result)) {
  994. return $result;
  995. }
  996. if (true !== $sepa && 1 == $options['limit']) {
  997. $data = reset($result[0]);
  998. if (isset($cache)) {
  999. S($key, $data, $cache);
  1000. }
  1001. return $data;
  1002. }
  1003. foreach ($result as $val) {
  1004. $array[] = reset($val);
  1005. }
  1006. if (isset($cache)) {
  1007. S($key, $array, $cache);
  1008. }
  1009. return $array;
  1010. }
  1011. }
  1012. return null;
  1013. }
  1014. /**
  1015. * 创建数据对象 但不保存到数据库
  1016. * @access public
  1017. * @param mixed $data 创建数据
  1018. * @param string $type 状态
  1019. * @return mixed
  1020. */
  1021. public function create($data = '', $type = '')
  1022. {
  1023. // 如果没有传值默认取POST数据
  1024. if (empty($data)) {
  1025. $data = I('post.');
  1026. } elseif (is_object($data)) {
  1027. $data = get_object_vars($data);
  1028. }
  1029. // 验证数据
  1030. if (empty($data) || !is_array($data)) {
  1031. $this->error = L('_DATA_TYPE_INVALID_');
  1032. return false;
  1033. }
  1034. // 状态
  1035. $type = $type ?: (!empty($data[$this->getPk()]) ? self::MODEL_UPDATE : self::MODEL_INSERT);
  1036. // 检查字段映射
  1037. $data = $this->parseFieldsMap($data, 0);
  1038. // 检测提交字段的合法性
  1039. if (isset($this->options['field'])) {
  1040. // $this->field('field1,field2...')->create()
  1041. $fields = $this->options['field'];
  1042. unset($this->options['field']);
  1043. } elseif (self::MODEL_INSERT == $type && isset($this->insertFields)) {
  1044. $fields = $this->insertFields;
  1045. } elseif (self::MODEL_UPDATE == $type && isset($this->updateFields)) {
  1046. $fields = $this->updateFields;
  1047. $pk = $this->getPk();
  1048. if (is_string($pk)) {
  1049. array_push($fields, $pk);
  1050. }
  1051. if (is_array($pk)) {
  1052. foreach ($pk as $pkTemp) {
  1053. array_push($fields, $pkTemp);
  1054. }
  1055. }
  1056. }
  1057. if (isset($fields)) {
  1058. if (is_string($fields)) {
  1059. $fields = explode(',', $fields);
  1060. }
  1061. // 判断令牌验证字段
  1062. if (C('TOKEN_ON')) {
  1063. $fields[] = C('TOKEN_NAME', null, '__hash__');
  1064. }
  1065. foreach ($data as $key => $val) {
  1066. if (!in_array($key, $fields)) {
  1067. unset($data[$key]);
  1068. }
  1069. }
  1070. }
  1071. // 数据自动验证
  1072. if (!$this->autoValidation($data, $type)) {
  1073. return false;
  1074. }
  1075. // 表单令牌验证
  1076. if (!$this->autoCheckToken($data)) {
  1077. $this->error = L('_TOKEN_ERROR_');
  1078. return false;
  1079. }
  1080. // 验证完成生成数据对象
  1081. if ($this->autoCheckFields) {
  1082. // 开启字段检测 则过滤非法字段数据
  1083. $fields = $this->getDbFields();
  1084. foreach ($data as $key => $val) {
  1085. if (!in_array($key, $fields)) {
  1086. unset($data[$key]);
  1087. } elseif (MAGIC_QUOTES_GPC && is_string($val)) {
  1088. $data[$key] = stripslashes($val);
  1089. }
  1090. }
  1091. }
  1092. // 创建完成对数据进行自动处理
  1093. $this->autoOperation($data, $type);
  1094. // 赋值当前数据对象
  1095. $this->data = $data;
  1096. // 返回创建的数据以供其他调用
  1097. return $data;
  1098. }
  1099. // 自动表单令牌验证
  1100. // TODO ajax无刷新多次提交暂不能满足
  1101. public function autoCheckToken($data)
  1102. {
  1103. // 支持使用token(false) 关闭令牌验证
  1104. if (isset($this->options['token']) && !$this->options['token']) {
  1105. return true;
  1106. }
  1107. if (C('TOKEN_ON')) {
  1108. $name = C('TOKEN_NAME', null, '__hash__');
  1109. if (!isset($data[$name]) || !isset($_SESSION[$name])) {
  1110. // 令牌数据无效
  1111. return false;
  1112. }
  1113. // 令牌验证
  1114. list($key, $value) = explode('_', $data[$name]);
  1115. if (isset($_SESSION[$name][$key]) && $value && $_SESSION[$name][$key] === $value) {
  1116. // 防止重复提交
  1117. unset($_SESSION[$name][$key]); // 验证完成销毁session
  1118. return true;
  1119. }
  1120. // 开启TOKEN重置
  1121. if (C('TOKEN_RESET')) {
  1122. unset($_SESSION[$name][$key]);
  1123. }
  1124. return false;
  1125. }
  1126. return true;
  1127. }
  1128. /**
  1129. * 使用正则验证数据
  1130. * @access public
  1131. * @param string $value 要验证的数据
  1132. * @param string $rule 验证规则
  1133. * @return boolean
  1134. */
  1135. public function regex($value, $rule)
  1136. {
  1137. $validate = array(
  1138. 'require' => '/\S+/',
  1139. 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
  1140. 'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(:\d+)?(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
  1141. 'currency' => '/^\d+(\.\d+)?$/',
  1142. 'number' => '/^\d+$/',
  1143. 'zip' => '/^\d{6}$/',
  1144. 'integer' => '/^[-\+]?\d+$/',
  1145. 'double' => '/^[-\+]?\d+(\.\d+)?$/',
  1146. 'english' => '/^[A-Za-z]+$/',
  1147. );
  1148. // 检查是否有内置的正则表达式
  1149. if (isset($validate[strtolower($rule)])) {
  1150. $rule = $validate[strtolower($rule)];
  1151. }
  1152. return preg_match($rule, $value) === 1;
  1153. }
  1154. /**
  1155. * 自动表单处理
  1156. * @access public
  1157. * @param array $data 创建数据
  1158. * @param string $type 创建类型
  1159. * @return mixed
  1160. */
  1161. private function autoOperation(&$data, $type)
  1162. {
  1163. if (isset($this->options['auto']) && false === $this->options['auto']) {
  1164. // 关闭自动完成
  1165. return $data;
  1166. }
  1167. if (!empty($this->options['auto'])) {
  1168. $_auto = $this->options['auto'];
  1169. unset($this->options['auto']);
  1170. } elseif (!empty($this->_auto)) {
  1171. $_auto = $this->_auto;
  1172. }
  1173. // 自动填充
  1174. if (isset($_auto)) {
  1175. foreach ($_auto as $auto) {
  1176. // 填充因子定义格式
  1177. // array('field','填充内容','填充条件','附加规则',[额外参数])
  1178. if (empty($auto[2])) {
  1179. $auto[2] = self::MODEL_INSERT;
  1180. }
  1181. // 默认为新增的时候自动填充
  1182. if ($type == $auto[2] || self::MODEL_BOTH == $auto[2]) {
  1183. if (empty($auto[3])) {
  1184. $auto[3] = 'string';
  1185. }
  1186. switch (trim($auto[3])) {
  1187. case 'function': // 使用函数进行填充 字段的值作为参数
  1188. case 'callback': // 使用回调方法
  1189. $args = isset($auto[4]) ? (array) $auto[4] : array();
  1190. if (isset($data[$auto[0]])) {
  1191. array_unshift($args, $data[$auto[0]]);
  1192. }
  1193. if ('function' == $auto[3]) {
  1194. $data[$auto[0]] = call_user_func_array($auto[1], $args);
  1195. } else {
  1196. $data[$auto[0]] = call_user_func_array(array(&$this, $auto[1]), $args);
  1197. }
  1198. break;
  1199. case 'field': // 用其它字段的值进行填充
  1200. $data[$auto[0]] = $data[$auto[1]];
  1201. break;
  1202. case 'ignore': // 为空忽略
  1203. if ($auto[1] === $data[$auto[0]]) {
  1204. unset($data[$auto[0]]);
  1205. }
  1206. break;
  1207. case 'string':
  1208. default: // 默认作为字符串填充
  1209. $data[$auto[0]] = $auto[1];
  1210. }
  1211. if (isset($data[$auto[0]]) && false === $data[$auto[0]]) {
  1212. unset($data[$auto[0]]);
  1213. }
  1214. }
  1215. }
  1216. }
  1217. return $data;
  1218. }
  1219. /**
  1220. * 自动表单验证
  1221. * @access protected
  1222. * @param array $data 创建数据
  1223. * @param string $type 创建类型
  1224. * @return boolean
  1225. */
  1226. protected function autoValidation($data, $type)
  1227. {
  1228. if (isset($this->options['validate']) && false === $this->options['validate']) {
  1229. // 关闭自动验证
  1230. return true;
  1231. }
  1232. if (!empty($this->options['validate'])) {
  1233. $_validate = $this->options['validate'];
  1234. unset($this->options['validate']);
  1235. } elseif (!empty($this->_validate)) {
  1236. $_validate = $this->_validate;
  1237. }
  1238. // 属性验证
  1239. if (isset($_validate)) {
  1240. // 如果设置了数据自动验证则进行数据验证
  1241. if ($this->patchValidate) {
  1242. // 重置验证错误信息
  1243. $this->error = array();
  1244. }
  1245. foreach ($_validate as $key => $val) {
  1246. // 验证因子定义格式
  1247. // array(field,rule,message,condition,type,when,params)
  1248. // 判断是否需要执行验证
  1249. if (empty($val[5]) || (self::MODEL_BOTH == $val[5] && $type < 3) || $val[5] == $type) {
  1250. if (0 == strpos($val[2], '{%') && strpos($val[2], '}'))
  1251. // 支持提示信息的多语言 使用 {%语言定义} 方式
  1252. {
  1253. $val[2] = L(substr($val[2], 2, -1));
  1254. }
  1255. $val[3] = isset($val[3]) ? $val[3] : self::EXISTS_VALIDATE;
  1256. $val[4] = isset($val[4]) ? $val[4] : 'regex';
  1257. // 判断验证条件
  1258. switch ($val[3]) {
  1259. case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段
  1260. if (false === $this->_validationField($data, $val)) {
  1261. return false;
  1262. }
  1263. break;
  1264. case self::VALUE_VALIDATE: // 值不为空的时候才验证
  1265. if ('' != trim($data[$val[0]])) {
  1266. if (false === $this->_validationField($data, $val)) {
  1267. return false;
  1268. }
  1269. }
  1270. break;
  1271. default: // 默认表单存在该字段就验证
  1272. if (isset($data[$val[0]])) {
  1273. if (false === $this->_validationField($data, $val)) {
  1274. return false;
  1275. }
  1276. }
  1277. }
  1278. }
  1279. }
  1280. // 批量验证的时候最后返回错误
  1281. if (!empty($this->error)) {
  1282. return false;
  1283. }
  1284. }
  1285. return true;
  1286. }
  1287. /**
  1288. * 验证表单字段 支持批量验证
  1289. * 如果批量验证返回错误的数组信息
  1290. * @access protected
  1291. * @param array $data 创建数据
  1292. * @param array $val 验证因子
  1293. * @return boolean
  1294. */
  1295. protected function _validationField($data, $val)
  1296. {
  1297. if ($this->patchValidate && isset($this->error[$val[0]])) {
  1298. //当前字段已经有规则验证没有通过
  1299. return;
  1300. }
  1301. if (false === $this->_validationFieldItem($data, $val)) {
  1302. if ($this->patchValidate) {
  1303. $this->error[$val[0]] = $val[2];
  1304. } else {
  1305. $this->error = $val[2];
  1306. return false;
  1307. }
  1308. }
  1309. return;
  1310. }
  1311. /**
  1312. * 根据验证因子验证字段
  1313. * @access protected
  1314. * @param array $data 创建数据
  1315. * @param array $val 验证因子
  1316. * @return boolean
  1317. */
  1318. protected function _validationFieldItem($data, $val)
  1319. {
  1320. switch (strtolower(trim($val[4]))) {
  1321. case 'function': // 使用函数进行验证
  1322. case 'callback': // 调用方法进行验证
  1323. $args = isset($val[6]) ? (array) $val[6] : array();
  1324. if (is_string($val[0]) && strpos($val[0], ',')) {
  1325. $val[0] = explode(',', $val[0]);
  1326. }
  1327. if (is_array($val[0])) {
  1328. // 支持多个字段验证
  1329. foreach ($val[0] as $field) {
  1330. $_data[$field] = $data[$field];
  1331. }
  1332. array_unshift($args, $_data);
  1333. } else {
  1334. array_unshift($args, $data[$val[0]]);
  1335. }
  1336. if ('function' == $val[4]) {
  1337. return call_user_func_array($val[1], $args);
  1338. } else {
  1339. return call_user_func_array(array(&$this, $val[1]), $args);
  1340. }
  1341. case 'confirm': // 验证两个字段是否相同
  1342. return $data[$val[0]] == $data[$val[1]];
  1343. case 'unique': // 验证某个值是否唯一
  1344. if (is_string($val[0]) && strpos($val[0], ',')) {
  1345. $val[0] = explode(',', $val[0]);
  1346. }
  1347. $map = array();
  1348. if (is_array($val[0])) {
  1349. // 支持多个字段验证
  1350. foreach ($val[0] as $field) {
  1351. $map[$field] = $data[$field];
  1352. }
  1353. } else {
  1354. $map[$val[0]] = $data[$val[0]];
  1355. }
  1356. $pk = $this->getPk();
  1357. if (!empty($data[$pk]) && is_string($pk)) {
  1358. // 完善编辑的时候验证唯一
  1359. $map[$pk] = array('neq', $data[$pk]);
  1360. }
  1361. $options = $this->options;
  1362. if ($this->where($map)->find()) {
  1363. return false;
  1364. }
  1365. $this->options = $options;
  1366. return true;
  1367. default: // 检查附加规则
  1368. return $this->check($data[$val[0]], $val[1], $val[4]);
  1369. }
  1370. }
  1371. /**
  1372. * 验证数据 支持 in between equal length regex expire ip_allow ip_deny
  1373. * @access public
  1374. * @param string $value 验证数据
  1375. * @param mixed $rule 验证表达式
  1376. * @param string $type 验证方式 默认为正则验证
  1377. * @return boolean
  1378. */
  1379. public function check($value, $rule, $type = 'regex')
  1380. {
  1381. $type = strtolower(trim($type));
  1382. switch ($type) {
  1383. case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
  1384. case 'notin':
  1385. $range = is_array($rule) ? $rule : explode(',', $rule);
  1386. return 'in' == $type ? in_array($value, $range) : !in_array($value, $range);
  1387. case 'between': // 验证是否在某个范围
  1388. case 'notbetween': // 验证是否不在某个范围
  1389. if (is_array($rule)) {
  1390. $min = $rule[0];
  1391. $max = $rule[1];
  1392. } else {
  1393. list($min, $max) = explode(',', $rule);
  1394. }
  1395. return 'between' == $type ? $value >= $min && $value <= $max : $value < $min || $value > $max;
  1396. case 'equal': // 验证是否等于某个值
  1397. case 'notequal': // 验证是否等于某个值
  1398. return 'equal' == $type ? $value == $rule : $value != $rule;
  1399. case 'length': // 验证长度
  1400. $length = mb_strlen($value, 'utf-8'); // 当前数据长度
  1401. if (strpos($rule, ',')) {
  1402. // 长度区间
  1403. list($min, $max) = explode(',', $rule);
  1404. return $length >= $min && $length <= $max;
  1405. } else {
  1406. // 指定长度
  1407. return $length == $rule;
  1408. }
  1409. case 'expire':
  1410. list($start, $end) = explode(',', $rule);
  1411. if (!is_numeric($start)) {
  1412. $start = strtotime($start);
  1413. }
  1414. if (!is_numeric($end)) {
  1415. $end = strtotime($end);
  1416. }
  1417. return NOW_TIME >= $start && NOW_TIME <= $end;
  1418. case 'ip_allow': // IP 操作许可验证
  1419. return in_array(get_client_ip(), explode(',', $rule));
  1420. case 'ip_deny': // IP 操作禁止验证
  1421. return !in_array(get_client_ip(), explode(',', $rule));
  1422. case 'regex':
  1423. default: // 默认使用正则验证 可以使用验证类中定义的验证名称
  1424. // 检查附加规则
  1425. return $this->regex($value, $rule);
  1426. }
  1427. }
  1428. /**
  1429. * 存储过程返回多数据集
  1430. * @access public
  1431. * @param string $sql SQL指令
  1432. * @param mixed $parse 是否需要解析SQL
  1433. * @return array
  1434. */
  1435. public function procedure($sql, $parse = false)
  1436. {
  1437. return $this->db->procedure($sql, $parse);
  1438. }
  1439. /**
  1440. * SQL查询
  1441. * @access public
  1442. * @param string $sql SQL指令
  1443. * @param mixed $parse 是否需要解析SQL
  1444. * @return mixed
  1445. */
  1446. public function query($sql, $parse = false)
  1447. {
  1448. if (!is_bool($parse) && !is_array($parse)) {
  1449. $parse = func_get_args();
  1450. array_shift($parse);
  1451. }
  1452. $sql = $this->parseSql($sql, $parse);
  1453. return $this->db->query($sql);
  1454. }
  1455. /**
  1456. * 执行SQL语句
  1457. * @access public
  1458. * @param string $sql SQL指令
  1459. * @param mixed $parse 是否需要解析SQL
  1460. * @return false | integer
  1461. */
  1462. public function execute($sql, $parse = false)
  1463. {
  1464. if (!is_bool($parse) && !is_array($parse)) {
  1465. $parse = func_get_args();
  1466. array_shift($parse);
  1467. }
  1468. $sql = $this->parseSql($sql, $parse);
  1469. return $this->db->execute($sql);
  1470. }
  1471. /**
  1472. * 解析SQL语句
  1473. * @access public
  1474. * @param string $sql SQL指令
  1475. * @param boolean $parse 是否需要解析SQL
  1476. * @return string
  1477. */
  1478. protected function parseSql($sql, $parse)
  1479. {
  1480. // 分析表达式
  1481. if (true === $parse) {
  1482. $options = $this->_parseOptions();
  1483. $sql = $this->db->parseSql($sql, $options);
  1484. } elseif (is_array($parse)) {
  1485. // SQL预处理
  1486. $parse = array_map(array($this->db, 'escapeString'), $parse);
  1487. $sql = vsprintf($sql, $parse);
  1488. } else {
  1489. $sql = strtr($sql, array('__TABLE__' => $this->getTableName(), '__PREFIX__' => $this->tablePrefix));
  1490. $prefix = $this->tablePrefix;
  1491. $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $sql);
  1492. }
  1493. $this->db->setModel($this->name);
  1494. return $sql;
  1495. }
  1496. /**
  1497. * 切换当前的数据库连接
  1498. * @access public
  1499. * @param integer $linkNum 连接序号
  1500. * @param mixed $config 数据库连接信息
  1501. * @param boolean $force 强制重新连接
  1502. * @return Model
  1503. */
  1504. public function db($linkNum = '', $config = '', $force = false)
  1505. {
  1506. if ('' === $linkNum && $this->db) {
  1507. return $this->db;
  1508. }
  1509. if (!isset($this->_db[$linkNum]) || $force) {
  1510. // 创建一个新的实例
  1511. if (!empty($config) && is_string($config) && false === strpos($config, '/')) {
  1512. // 支持读取配置参数
  1513. $config = C($config);
  1514. }
  1515. $this->_db[$linkNum] = Db::getInstance($config);
  1516. } elseif (null === $config) {
  1517. $this->_db[$linkNum]->close(); // 关闭数据库连接
  1518. unset($this->_db[$linkNum]);
  1519. return;
  1520. }
  1521. // 切换数据库连接
  1522. $this->db = $this->_db[$linkNum];
  1523. $this->_after_db();
  1524. // 字段检测
  1525. if (!empty($this->name) && $this->autoCheckFields) {
  1526. $this->_checkTableInfo();
  1527. }
  1528. return $this;
  1529. }
  1530. // 数据库切换后回调方法
  1531. protected function _after_db()
  1532. {}
  1533. /**
  1534. * 得到当前的数据对象名称
  1535. * @access public
  1536. * @return string
  1537. */
  1538. public function getModelName()
  1539. {
  1540. if (empty($this->name)) {
  1541. $name = substr(get_class($this), 0, -strlen(C('DEFAULT_M_LAYER')));
  1542. if ($pos = strrpos($name, '\\')) {
  1543. //有命名空间
  1544. $this->name = substr($name, $pos + 1);
  1545. } else {
  1546. $this->name = $name;
  1547. }
  1548. }
  1549. return $this->name;
  1550. }
  1551. /**
  1552. * 得到完整的数据表名
  1553. * @access public
  1554. * @return string
  1555. */
  1556. public function getTableName()
  1557. {
  1558. if (empty($this->trueTableName)) {
  1559. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  1560. if (!empty($this->tableName)) {
  1561. $tableName .= $this->tableName;
  1562. } else {
  1563. $tableName .= parse_name($this->name);
  1564. }
  1565. $this->trueTableName = strtolower($tableName);
  1566. }
  1567. return (!empty($this->dbName) ? $this->dbName . '.' : '') . $this->trueTableName;
  1568. }
  1569. /**
  1570. * 启动事务
  1571. * @access public
  1572. * @return void
  1573. */
  1574. public function startTrans()
  1575. {
  1576. $this->commit();
  1577. $this->db->startTrans();
  1578. return;
  1579. }
  1580. /**
  1581. * 提交事务
  1582. * @access public
  1583. * @return boolean
  1584. */
  1585. public function commit()
  1586. {
  1587. return $this->db->commit();
  1588. }
  1589. /**
  1590. * 事务回滚
  1591. * @access public
  1592. * @return boolean
  1593. */
  1594. public function rollback()
  1595. {
  1596. return $this->db->rollback();
  1597. }
  1598. /**
  1599. * 返回模型的错误信息
  1600. * @access public
  1601. * @return string
  1602. */
  1603. public function getError()
  1604. {
  1605. return $this->error;
  1606. }
  1607. /**
  1608. * 返回数据库的错误信息
  1609. * @access public
  1610. * @return string
  1611. */
  1612. public function getDbError()
  1613. {
  1614. return $this->db->getError();
  1615. }
  1616. /**
  1617. * 返回最后插入的ID
  1618. * @access public
  1619. * @return string
  1620. */
  1621. public function getLastInsID()
  1622. {
  1623. return $this->db->getLastInsID();
  1624. }
  1625. /**
  1626. * 返回最后执行的sql语句
  1627. * @access public
  1628. * @return string
  1629. */
  1630. public function getLastSql()
  1631. {
  1632. return $this->db->getLastSql($this->name);
  1633. }
  1634. // 鉴于getLastSql比较常用 增加_sql 别名
  1635. public function _sql()
  1636. {
  1637. return $this->getLastSql();
  1638. }
  1639. /**
  1640. * 获取主键名称
  1641. * @access public
  1642. * @return string
  1643. */
  1644. public function getPk()
  1645. {
  1646. return $this->pk;
  1647. }
  1648. /**
  1649. * 获取数据表字段信息
  1650. * @access public
  1651. * @return array
  1652. */
  1653. public function getDbFields()
  1654. {
  1655. if (isset($this->options['table'])) {
  1656. // 动态指定表名
  1657. if (is_array($this->options['table'])) {
  1658. $table = key($this->options['table']);
  1659. } else {
  1660. $table = $this->options['table'];
  1661. if (strpos($table, ')')) {
  1662. // 子查询
  1663. return false;
  1664. }
  1665. }
  1666. $fields = $this->db->getFields($table);
  1667. return $fields ? array_keys($fields) : false;
  1668. }
  1669. if ($this->fields) {
  1670. $fields = $this->fields;
  1671. unset($fields['_type'], $fields['_pk']);
  1672. return $fields;
  1673. }
  1674. return false;
  1675. }
  1676. /**
  1677. * 设置数据对象值
  1678. * @access public
  1679. * @param mixed $data 数据
  1680. * @return Model
  1681. */
  1682. public function data($data = '')
  1683. {
  1684. if ('' === $data && !empty($this->data)) {
  1685. return $this->data;
  1686. }
  1687. if (is_object($data)) {
  1688. $data = get_object_vars($data);
  1689. } elseif (is_string($data)) {
  1690. parse_str($data, $data);
  1691. } elseif (!is_array($data)) {
  1692. E(L('_DATA_TYPE_INVALID_'));
  1693. }
  1694. $this->data = $data;
  1695. return $this;
  1696. }
  1697. /**
  1698. * 指定当前的数据表
  1699. * @access public
  1700. * @param mixed $table
  1701. * @return Model
  1702. */
  1703. public function table($table)
  1704. {
  1705. $prefix = $this->tablePrefix;
  1706. if (is_array($table)) {
  1707. $this->options['table'] = $table;
  1708. } elseif (!empty($table)) {
  1709. //将__TABLE_NAME__替换成带前缀的表名
  1710. $table = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $table);
  1711. $this->options['table'] = $table;
  1712. }
  1713. return $this;
  1714. }
  1715. /**
  1716. * USING支持 用于多表删除
  1717. * @access public
  1718. * @param mixed $using
  1719. * @return Model
  1720. */
  1721. public function using($using)
  1722. {
  1723. $prefix = $this->tablePrefix;
  1724. if (is_array($using)) {
  1725. $this->options['using'] = $using;
  1726. } elseif (!empty($using)) {
  1727. //将__TABLE_NAME__替换成带前缀的表名
  1728. $using = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $using);
  1729. $this->options['using'] = $using;
  1730. }
  1731. return $this;
  1732. }
  1733. /**
  1734. * 查询SQL组装 join
  1735. * @access public
  1736. * @param mixed $join
  1737. * @param string $type JOIN类型
  1738. * @return Model
  1739. */
  1740. public function join($join, $type = 'INNER')
  1741. {
  1742. $prefix = $this->tablePrefix;
  1743. if (is_array($join)) {
  1744. foreach ($join as $key => &$_join) {
  1745. $_join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $_join);
  1746. $_join = false !== stripos($_join, 'JOIN') ? $_join : $type . ' JOIN ' . $_join;
  1747. }
  1748. $this->options['join'] = $join;
  1749. } elseif (!empty($join)) {
  1750. //将__TABLE_NAME__字符串替换成带前缀的表名
  1751. $join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $join);
  1752. $this->options['join'][] = false !== stripos($join, 'JOIN') ? $join : $type . ' JOIN ' . $join;
  1753. }
  1754. return $this;
  1755. }
  1756. /**
  1757. * 查询SQL组装 union
  1758. * @access public
  1759. * @param mixed $union
  1760. * @param boolean $all
  1761. * @return Model
  1762. */
  1763. public function union($union, $all = false)
  1764. {
  1765. if (empty($union)) {
  1766. return $this;
  1767. }
  1768. if ($all) {
  1769. $this->options['union']['_all'] = true;
  1770. }
  1771. if (is_object($union)) {
  1772. $union = get_object_vars($union);
  1773. }
  1774. // 转换union表达式
  1775. if (is_string($union)) {
  1776. $prefix = $this->tablePrefix;
  1777. //将__TABLE_NAME__字符串替换成带前缀的表名
  1778. $options = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $union);
  1779. } elseif (is_array($union)) {
  1780. if (isset($union[0])) {
  1781. $this->options['union'] = array_merge($this->options['union'], $union);
  1782. return $this;
  1783. } else {
  1784. $options = $union;
  1785. }
  1786. } else {
  1787. E(L('_DATA_TYPE_INVALID_'));
  1788. }
  1789. $this->options['union'][] = $options;
  1790. return $this;
  1791. }
  1792. /**
  1793. * 查询缓存
  1794. * @access public
  1795. * @param mixed $key
  1796. * @param integer $expire
  1797. * @param string $type
  1798. * @return Model
  1799. */
  1800. public function cache($key = true, $expire = null, $type = '')
  1801. {
  1802. // 增加快捷调用方式 cache(10) 等同于 cache(true, 10)
  1803. if (is_numeric($key) && is_null($expire)) {
  1804. $expire = $key;
  1805. $key = true;
  1806. }
  1807. if (false !== $key) {
  1808. $this->options['cache'] = array('key' => $key, 'expire' => $expire, 'type' => $type);
  1809. }
  1810. return $this;
  1811. }
  1812. /**
  1813. * 指定查询字段 支持字段排除
  1814. * @access public
  1815. * @param mixed $field
  1816. * @param boolean $except 是否排除
  1817. * @return Model
  1818. */
  1819. public function field($field, $except = false)
  1820. {
  1821. if (true === $field) {
  1822. // 获取全部字段
  1823. $fields = $this->getDbFields();
  1824. $field = $fields ?: '*';
  1825. } elseif ($except) {
  1826. // 字段排除
  1827. if (is_string($field)) {
  1828. $field = explode(',', $field);
  1829. }
  1830. $fields = $this->getDbFields();
  1831. $field = $fields ? array_diff($fields, $field) : $field;
  1832. }
  1833. $this->options['field'] = $field;
  1834. return $this;
  1835. }
  1836. /**
  1837. * 调用命名范围
  1838. * @access public
  1839. * @param mixed $scope 命名范围名称 支持多个 和直接定义
  1840. * @param array $args 参数
  1841. * @return Model
  1842. */
  1843. public function scope($scope = '', $args = null)
  1844. {
  1845. if ('' === $scope) {
  1846. if (isset($this->_scope['default'])) {
  1847. // 默认的命名范围
  1848. $options = $this->_scope['default'];
  1849. } else {
  1850. return $this;
  1851. }
  1852. } elseif (is_string($scope)) {
  1853. // 支持多个命名范围调用 用逗号分割
  1854. $scopes = explode(',', $scope);
  1855. $options = array();
  1856. foreach ($scopes as $name) {
  1857. if (!isset($this->_scope[$name])) {
  1858. continue;
  1859. }
  1860. $options = array_merge($options, $this->_scope[$name]);
  1861. }
  1862. if (!empty($args) && is_array($args)) {
  1863. $options = array_merge($options, $args);
  1864. }
  1865. } elseif (is_array($scope)) {
  1866. // 直接传入命名范围定义
  1867. $options = $scope;
  1868. }
  1869. if (is_array($options) && !empty($options)) {
  1870. $this->options = array_merge($this->options, array_change_key_case($options));
  1871. }
  1872. return $this;
  1873. }
  1874. /**
  1875. * 指定查询条件 支持安全过滤
  1876. * @access public
  1877. * @param mixed $where 条件表达式
  1878. * @param mixed $parse 预处理参数
  1879. * @return Model
  1880. */
  1881. public function where($where, $parse = null)
  1882. {
  1883. if (!is_null($parse) && is_string($where)) {
  1884. if (!is_array($parse)) {
  1885. $parse = func_get_args();
  1886. array_shift($parse);
  1887. }
  1888. $parse = array_map(array($this->db, 'escapeString'), $parse);
  1889. $where = vsprintf($where, $parse);
  1890. } elseif (is_object($where)) {
  1891. $where = get_object_vars($where);
  1892. }
  1893. if (is_string($where) && '' != $where) {
  1894. $map = array();
  1895. $map['_string'] = $where;
  1896. $where = $map;
  1897. }
  1898. if (isset($this->options['where'])) {
  1899. $this->options['where'] = array_merge($this->options['where'], $where);
  1900. } else {
  1901. $this->options['where'] = $where;
  1902. }
  1903. return $this;
  1904. }
  1905. /**
  1906. * 指定查询数量
  1907. * @access public
  1908. * @param mixed $offset 起始位置
  1909. * @param mixed $length 查询数量
  1910. * @return Model
  1911. */
  1912. public function limit($offset, $length = null)
  1913. {
  1914. if (is_null($length) && strpos($offset, ',')) {
  1915. list($offset, $length) = explode(',', $offset);
  1916. }
  1917. $this->options['limit'] = intval($offset) . ($length ? ',' . intval($length) : '');
  1918. return $this;
  1919. }
  1920. /**
  1921. * 指定分页
  1922. * @access public
  1923. * @param mixed $page 页数
  1924. * @param mixed $listRows 每页数量
  1925. * @return Model
  1926. */
  1927. public function page($page, $listRows = null)
  1928. {
  1929. if (is_null($listRows) && strpos($page, ',')) {
  1930. list($page, $listRows) = explode(',', $page);
  1931. }
  1932. $this->options['page'] = array(intval($page), intval($listRows));
  1933. return $this;
  1934. }
  1935. /**
  1936. * 查询注释
  1937. * @access public
  1938. * @param string $comment 注释
  1939. * @return Model
  1940. */
  1941. public function comment($comment)
  1942. {
  1943. $this->options['comment'] = $comment;
  1944. return $this;
  1945. }
  1946. /**
  1947. * 获取执行的SQL语句
  1948. * @access public
  1949. * @param boolean $fetch 是否返回sql
  1950. * @return Model
  1951. */
  1952. public function fetchSql($fetch = true)
  1953. {
  1954. $this->options['fetch_sql'] = $fetch;
  1955. return $this;
  1956. }
  1957. /**
  1958. * 参数绑定
  1959. * @access public
  1960. * @param string $key 参数名
  1961. * @param mixed $value 绑定的变量及绑定参数
  1962. * @return Model
  1963. */
  1964. public function bind($key, $value = false)
  1965. {
  1966. if (is_array($key)) {
  1967. $this->options['bind'] = $key;
  1968. } else {
  1969. $num = func_num_args();
  1970. if ($num > 2) {
  1971. $params = func_get_args();
  1972. array_shift($params);
  1973. $this->options['bind'][$key] = $params;
  1974. } else {
  1975. $this->options['bind'][$key] = $value;
  1976. }
  1977. }
  1978. return $this;
  1979. }
  1980. /**
  1981. * 设置模型的属性值
  1982. * @access public
  1983. * @param string $name 名称
  1984. * @param mixed $value
  1985. * @return Model
  1986. */
  1987. public function setProperty($name, $value)
  1988. {
  1989. if (property_exists($this, $name)) {
  1990. $this->$name = $value;
  1991. }
  1992. return $this;
  1993. }
  1994. }