Model.class.php 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124
  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) . '(' . $field . ') 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. $options = array();
  496. $options['where'] = $where;
  497. }
  498. // 根据复合主键删除记录
  499. if (is_array($options) && (count($options) > 0) && is_array($pk)) {
  500. $count = 0;
  501. foreach (array_keys($options) as $key) {
  502. if (is_int($key)) {
  503. $count++;
  504. }
  505. }
  506. if (count($pk) == $count) {
  507. $i = 0;
  508. foreach ($pk as $field) {
  509. $where[$field] = $options[$i];
  510. unset($options[$i++]);
  511. }
  512. $options['where'] = $where;
  513. } else {
  514. return false;
  515. }
  516. }
  517. // 分析表达式
  518. $options = $this->_parseOptions($options);
  519. if (empty($options['where'])) {
  520. // 如果条件为空 不进行删除操作 除非设置 1=1
  521. return false;
  522. }
  523. if (is_array($options['where']) && isset($options['where'][$pk])) {
  524. $pkValue = $options['where'][$pk];
  525. }
  526. if (false === $this->_before_delete($options)) {
  527. return false;
  528. }
  529. $result = $this->db->delete($options);
  530. if (false !== $result && is_numeric($result)) {
  531. $data = array();
  532. if (isset($pkValue)) {
  533. $data[$pk] = $pkValue;
  534. }
  535. $this->_after_delete($data, $options);
  536. }
  537. // 返回删除记录个数
  538. return $result;
  539. }
  540. // 删除数据前的回调方法
  541. protected function _before_delete($options)
  542. {}
  543. // 删除成功后的回调方法
  544. protected function _after_delete($data, $options)
  545. {}
  546. /**
  547. * 查询数据集
  548. * @access public
  549. * @param array $options 表达式参数
  550. * @return mixed
  551. */
  552. public function select($options = array())
  553. {
  554. $pk = $this->getPk();
  555. if (is_string($options) || is_numeric($options)) {
  556. // 根据主键查询
  557. if (strpos($options, ',')) {
  558. $where[$pk] = array('IN', $options);
  559. } else {
  560. $where[$pk] = $options;
  561. }
  562. $options = array();
  563. $options['where'] = $where;
  564. } elseif (is_array($options) && (count($options) > 0) && is_array($pk)) {
  565. // 根据复合主键查询
  566. $count = 0;
  567. foreach (array_keys($options) as $key) {
  568. if (is_int($key)) {
  569. $count++;
  570. }
  571. }
  572. if (count($pk) == $count) {
  573. $i = 0;
  574. foreach ($pk as $field) {
  575. $where[$field] = $options[$i];
  576. unset($options[$i++]);
  577. }
  578. $options['where'] = $where;
  579. } else {
  580. return false;
  581. }
  582. } elseif (false === $options) {
  583. // 用于子查询 不查询只返回SQL
  584. $options['fetch_sql'] = true;
  585. }
  586. // 分析表达式
  587. $options = $this->_parseOptions($options);
  588. // 判断查询缓存
  589. if (isset($options['cache'])) {
  590. $cache = $options['cache'];
  591. $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
  592. $data = S($key, '', $cache);
  593. if (false !== $data) {
  594. return $data;
  595. }
  596. }
  597. $resultSet = $this->db->select($options);
  598. if (false === $resultSet) {
  599. return false;
  600. }
  601. if (!empty($resultSet)) {
  602. // 有查询结果
  603. if (is_string($resultSet)) {
  604. return $resultSet;
  605. }
  606. $resultSet = array_map(array($this, '_read_data'), $resultSet);
  607. $this->_after_select($resultSet, $options);
  608. if (isset($options['index'])) {
  609. // 对数据集进行索引
  610. $index = explode(',', $options['index']);
  611. foreach ($resultSet as $result) {
  612. $_key = $result[$index[0]];
  613. if (isset($index[1]) && isset($result[$index[1]])) {
  614. $cols[$_key] = $result[$index[1]];
  615. } else {
  616. $cols[$_key] = $result;
  617. }
  618. }
  619. $resultSet = $cols;
  620. }
  621. }
  622. if (isset($cache)) {
  623. S($key, $resultSet, $cache);
  624. }
  625. return $resultSet;
  626. }
  627. // 查询成功后的回调方法
  628. protected function _after_select(&$resultSet, $options)
  629. {}
  630. /**
  631. * 生成查询SQL 可用于子查询
  632. * @access public
  633. * @return string
  634. */
  635. public function buildSql()
  636. {
  637. return '( ' . $this->fetchSql(true)->select() . ' )';
  638. }
  639. /**
  640. * 分析表达式
  641. * @access protected
  642. * @param array $options 表达式参数
  643. * @return array
  644. */
  645. protected function _parseOptions($options = array())
  646. {
  647. if (is_array($options)) {
  648. $options = array_merge($this->options, $options);
  649. }
  650. if (!isset($options['table'])) {
  651. // 自动获取表名
  652. $options['table'] = $this->getTableName();
  653. $fields = $this->fields;
  654. } else {
  655. // 指定数据表 则重新获取字段列表 但不支持类型检测
  656. $fields = $this->getDbFields();
  657. }
  658. // 数据表别名
  659. if (!empty($options['alias'])) {
  660. $options['table'] .= ' ' . $options['alias'];
  661. }
  662. // 记录操作的模型名称
  663. $options['model'] = $this->name;
  664. // 字段类型验证
  665. if (isset($options['where']) && is_array($options['where']) && !empty($fields) && !isset($options['join'])) {
  666. // 对数组查询条件进行字段类型检查
  667. foreach ($options['where'] as $key => $val) {
  668. $key = trim($key);
  669. if (in_array($key, $fields, true)) {
  670. if (is_scalar($val)) {
  671. $this->_parseType($options['where'], $key);
  672. }
  673. }
  674. }
  675. }
  676. // 查询过后清空sql表达式组装 避免影响下次查询
  677. $this->options = array();
  678. // 表达式过滤
  679. $this->_options_filter($options);
  680. return $options;
  681. }
  682. // 表达式过滤回调方法
  683. protected function _options_filter(&$options)
  684. {}
  685. /**
  686. * 数据类型检测
  687. * @access protected
  688. * @param mixed $data 数据
  689. * @param string $key 字段名
  690. * @return void
  691. */
  692. protected function _parseType(&$data, $key)
  693. {
  694. if (!isset($this->options['bind'][':' . $key]) && isset($this->fields['_type'][$key])) {
  695. $fieldType = strtolower($this->fields['_type'][$key]);
  696. if (false !== strpos($fieldType, 'enum')) {
  697. // 支持ENUM类型优先检测
  698. } elseif (false === strpos($fieldType, 'bigint') && false !== strpos($fieldType, 'int')) {
  699. $data[$key] = intval($data[$key]);
  700. } elseif (false !== strpos($fieldType, 'float') || false !== strpos($fieldType, 'double')) {
  701. $data[$key] = floatval($data[$key]);
  702. } elseif (false !== strpos($fieldType, 'bool')) {
  703. $data[$key] = (bool) $data[$key];
  704. }
  705. }
  706. }
  707. /**
  708. * 数据读取后的处理
  709. * @access protected
  710. * @param array $data 当前数据
  711. * @return array
  712. */
  713. protected function _read_data($data)
  714. {
  715. // 检查字段映射
  716. if (!empty($this->_map) && C('READ_DATA_MAP')) {
  717. foreach ($this->_map as $key => $val) {
  718. if (isset($data[$val])) {
  719. $data[$key] = $data[$val];
  720. unset($data[$val]);
  721. }
  722. }
  723. }
  724. return $data;
  725. }
  726. /**
  727. * 查询数据
  728. * @access public
  729. * @param mixed $options 表达式参数
  730. * @return mixed
  731. */
  732. public function find($options = array())
  733. {
  734. if (is_numeric($options) || is_string($options)) {
  735. $where[$this->getPk()] = $options;
  736. $options = array();
  737. $options['where'] = $where;
  738. }
  739. // 根据复合主键查找记录
  740. $pk = $this->getPk();
  741. if (is_array($options) && (count($options) > 0) && is_array($pk)) {
  742. // 根据复合主键查询
  743. $count = 0;
  744. foreach (array_keys($options) as $key) {
  745. if (is_int($key)) {
  746. $count++;
  747. }
  748. }
  749. if (count($pk) == $count) {
  750. $i = 0;
  751. foreach ($pk as $field) {
  752. $where[$field] = $options[$i];
  753. unset($options[$i++]);
  754. }
  755. $options['where'] = $where;
  756. } else {
  757. return false;
  758. }
  759. }
  760. // 总是查找一条记录
  761. $options['limit'] = 1;
  762. // 分析表达式
  763. $options = $this->_parseOptions($options);
  764. // 判断查询缓存
  765. if (isset($options['cache'])) {
  766. $cache = $options['cache'];
  767. $key = is_string($cache['key']) ? $cache['key'] : md5(serialize($options));
  768. $data = S($key, '', $cache);
  769. if (false !== $data) {
  770. $this->data = $data;
  771. return $data;
  772. }
  773. }
  774. $resultSet = $this->db->select($options);
  775. if (false === $resultSet) {
  776. return false;
  777. }
  778. if (empty($resultSet)) {
  779. // 查询结果为空
  780. return null;
  781. }
  782. if (is_string($resultSet)) {
  783. return $resultSet;
  784. }
  785. // 读取数据后的处理
  786. $data = $this->_read_data($resultSet[0]);
  787. $this->_after_find($data, $options);
  788. if (!empty($options['result'])) {
  789. return $this->returnResult($data, $options['result']);
  790. }
  791. $this->data = $data;
  792. if (isset($cache)) {
  793. S($key, $data, $cache);
  794. }
  795. return $this->data;
  796. }
  797. // 查询成功的回调方法
  798. protected function _after_find(&$result, $options)
  799. {}
  800. protected function returnResult($data, $type = '')
  801. {
  802. if ($type) {
  803. if (is_callable($type)) {
  804. return call_user_func($type, $data);
  805. }
  806. switch (strtolower($type)) {
  807. case 'json':
  808. return json_encode($data);
  809. case 'xml':
  810. return xml_encode($data);
  811. }
  812. }
  813. return $data;
  814. }
  815. /**
  816. * 处理字段映射
  817. * @access public
  818. * @param array $data 当前数据
  819. * @param integer $type 类型 0 写入 1 读取
  820. * @return array
  821. */
  822. public function parseFieldsMap($data, $type = 1)
  823. {
  824. // 检查字段映射
  825. if (!empty($this->_map)) {
  826. foreach ($this->_map as $key => $val) {
  827. if (1 == $type) {
  828. // 读取
  829. if (isset($data[$val])) {
  830. $data[$key] = $data[$val];
  831. unset($data[$val]);
  832. }
  833. } else {
  834. if (isset($data[$key])) {
  835. $data[$val] = $data[$key];
  836. unset($data[$key]);
  837. }
  838. }
  839. }
  840. }
  841. return $data;
  842. }
  843. /**
  844. * 设置记录的某个字段值
  845. * 支持使用数据库字段和方法
  846. * @access public
  847. * @param string|array $field 字段名
  848. * @param string $value 字段值
  849. * @return boolean
  850. */
  851. public function setField($field, $value = '')
  852. {
  853. if (is_array($field)) {
  854. $data = $field;
  855. } else {
  856. $data[$field] = $value;
  857. }
  858. return $this->save($data);
  859. }
  860. /**
  861. * 字段值增长
  862. * @access public
  863. * @param string $field 字段名
  864. * @param integer $step 增长值
  865. * @param integer $lazyTime 延时时间(s)
  866. * @return boolean
  867. */
  868. public function setInc($field, $step = 1, $lazyTime = 0)
  869. {
  870. if ($lazyTime > 0) {
  871. // 延迟写入
  872. $condition = $this->options['where'];
  873. $guid = md5($this->name . '_' . $field . '_' . serialize($condition));
  874. $step = $this->lazyWrite($guid, $step, $lazyTime);
  875. if (empty($step)) {
  876. return true; // 等待下次写入
  877. } elseif ($step < 0) {
  878. $step = '-' . $step;
  879. }
  880. }
  881. return $this->setField($field, array('exp', $field . '+' . $step));
  882. }
  883. /**
  884. * 字段值减少
  885. * @access public
  886. * @param string $field 字段名
  887. * @param integer $step 减少值
  888. * @param integer $lazyTime 延时时间(s)
  889. * @return boolean
  890. */
  891. public function setDec($field, $step = 1, $lazyTime = 0)
  892. {
  893. if ($lazyTime > 0) {
  894. // 延迟写入
  895. $condition = $this->options['where'];
  896. $guid = md5($this->name . '_' . $field . '_' . serialize($condition));
  897. $step = $this->lazyWrite($guid, -$step, $lazyTime);
  898. if (empty($step)) {
  899. return true; // 等待下次写入
  900. } elseif ($step > 0) {
  901. $step = '-' . $step;
  902. }
  903. }
  904. return $this->setField($field, array('exp', $field . '-' . $step));
  905. }
  906. /**
  907. * 延时更新检查 返回false表示需要延时
  908. * 否则返回实际写入的数值
  909. * @access public
  910. * @param string $guid 写入标识
  911. * @param integer $step 写入步进值
  912. * @param integer $lazyTime 延时时间(s)
  913. * @return false|integer
  914. */
  915. protected function lazyWrite($guid, $step, $lazyTime)
  916. {
  917. if (false !== ($value = S($guid))) {
  918. // 存在缓存写入数据
  919. if (NOW_TIME > S($guid . '_time') + $lazyTime) {
  920. // 延时更新时间到了,删除缓存数据 并实际写入数据库
  921. S($guid, null);
  922. S($guid . '_time', null);
  923. return $value + $step;
  924. } else {
  925. // 追加数据到缓存
  926. S($guid, $value + $step, 0);
  927. return false;
  928. }
  929. } else {
  930. // 没有缓存数据
  931. S($guid, $step, 0);
  932. // 计时开始
  933. S($guid . '_time', NOW_TIME, 0);
  934. return false;
  935. }
  936. }
  937. /**
  938. * 获取一条记录的某个字段值
  939. * @access public
  940. * @param string $field 字段名
  941. * @param string $spea 字段数据间隔符号 NULL返回数组
  942. * @return mixed
  943. */
  944. public function getField($field, $sepa = null)
  945. {
  946. $options['field'] = $field;
  947. $options = $this->_parseOptions($options);
  948. // 判断查询缓存
  949. if (isset($options['cache'])) {
  950. $cache = $options['cache'];
  951. $key = is_string($cache['key']) ? $cache['key'] : md5($sepa . serialize($options));
  952. $data = S($key, '', $cache);
  953. if (false !== $data) {
  954. return $data;
  955. }
  956. }
  957. $field = trim($field);
  958. if (strpos($field, ',') && false !== $sepa) {
  959. // 多字段
  960. if (!isset($options['limit'])) {
  961. $options['limit'] = is_numeric($sepa) ? $sepa : '';
  962. }
  963. $resultSet = $this->db->select($options);
  964. if (!empty($resultSet)) {
  965. if (is_string($resultSet)) {
  966. return $resultSet;
  967. }
  968. $_field = explode(',', $field);
  969. $field = array_keys($resultSet[0]);
  970. $key1 = array_shift($field);
  971. $key2 = array_shift($field);
  972. $cols = array();
  973. $count = count($_field);
  974. foreach ($resultSet as $result) {
  975. $name = $result[$key1];
  976. if (2 == $count) {
  977. $cols[$name] = $result[$key2];
  978. } else {
  979. $cols[$name] = is_string($sepa) ? implode($sepa, array_slice($result, 1)) : $result;
  980. }
  981. }
  982. if (isset($cache)) {
  983. S($key, $cols, $cache);
  984. }
  985. return $cols;
  986. }
  987. } else {
  988. // 查找一条记录
  989. // 返回数据个数
  990. if (true !== $sepa) {
  991. // 当sepa指定为true的时候 返回所有数据
  992. $options['limit'] = is_numeric($sepa) ? $sepa : 1;
  993. }
  994. $result = $this->db->select($options);
  995. if (!empty($result)) {
  996. if (is_string($result)) {
  997. return $result;
  998. }
  999. if (true !== $sepa && 1 == $options['limit']) {
  1000. $data = reset($result[0]);
  1001. if (isset($cache)) {
  1002. S($key, $data, $cache);
  1003. }
  1004. return $data;
  1005. }
  1006. foreach ($result as $val) {
  1007. $array[] = reset($val);
  1008. }
  1009. if (isset($cache)) {
  1010. S($key, $array, $cache);
  1011. }
  1012. return $array;
  1013. }
  1014. }
  1015. return null;
  1016. }
  1017. /**
  1018. * 创建数据对象 但不保存到数据库
  1019. * @access public
  1020. * @param mixed $data 创建数据
  1021. * @param string $type 状态
  1022. * @return mixed
  1023. */
  1024. public function create($data = '', $type = '')
  1025. {
  1026. // 如果没有传值默认取POST数据
  1027. if (empty($data)) {
  1028. $data = I('post.');
  1029. } elseif (is_object($data)) {
  1030. $data = get_object_vars($data);
  1031. }
  1032. // 验证数据
  1033. if (empty($data) || !is_array($data)) {
  1034. $this->error = L('_DATA_TYPE_INVALID_');
  1035. return false;
  1036. }
  1037. // 状态
  1038. $type = $type ?: (!empty($data[$this->getPk()]) ? self::MODEL_UPDATE : self::MODEL_INSERT);
  1039. // 检查字段映射
  1040. $data = $this->parseFieldsMap($data, 0);
  1041. // 检测提交字段的合法性
  1042. if (isset($this->options['field'])) {
  1043. // $this->field('field1,field2...')->create()
  1044. $fields = $this->options['field'];
  1045. unset($this->options['field']);
  1046. } elseif (self::MODEL_INSERT == $type && isset($this->insertFields)) {
  1047. $fields = $this->insertFields;
  1048. } elseif (self::MODEL_UPDATE == $type && isset($this->updateFields)) {
  1049. $fields = $this->updateFields;
  1050. $pk = $this->getPk();
  1051. if (is_string($pk)) {
  1052. array_push($fields, $pk);
  1053. }
  1054. if (is_array($pk)) {
  1055. foreach ($pk as $pkTemp) {
  1056. array_push($fields, $pkTemp);
  1057. }
  1058. }
  1059. }
  1060. if (isset($fields)) {
  1061. if (is_string($fields)) {
  1062. $fields = explode(',', $fields);
  1063. }
  1064. // 判断令牌验证字段
  1065. if (C('TOKEN_ON')) {
  1066. $fields[] = C('TOKEN_NAME', null, '__hash__');
  1067. }
  1068. foreach ($data as $key => $val) {
  1069. if (!in_array($key, $fields)) {
  1070. unset($data[$key]);
  1071. }
  1072. }
  1073. }
  1074. // 数据自动验证
  1075. if (!$this->autoValidation($data, $type)) {
  1076. return false;
  1077. }
  1078. // 表单令牌验证
  1079. if (!$this->autoCheckToken($data)) {
  1080. $this->error = L('_TOKEN_ERROR_');
  1081. return false;
  1082. }
  1083. // 验证完成生成数据对象
  1084. if ($this->autoCheckFields) {
  1085. // 开启字段检测 则过滤非法字段数据
  1086. $fields = $this->getDbFields();
  1087. foreach ($data as $key => $val) {
  1088. if (!in_array($key, $fields)) {
  1089. unset($data[$key]);
  1090. } elseif (MAGIC_QUOTES_GPC && is_string($val)) {
  1091. $data[$key] = stripslashes($val);
  1092. }
  1093. }
  1094. }
  1095. // 创建完成对数据进行自动处理
  1096. $this->autoOperation($data, $type);
  1097. // 赋值当前数据对象
  1098. $this->data = $data;
  1099. // 返回创建的数据以供其他调用
  1100. return $data;
  1101. }
  1102. // 自动表单令牌验证
  1103. // TODO ajax无刷新多次提交暂不能满足
  1104. public function autoCheckToken($data)
  1105. {
  1106. // 支持使用token(false) 关闭令牌验证
  1107. if (isset($this->options['token']) && !$this->options['token']) {
  1108. return true;
  1109. }
  1110. if (C('TOKEN_ON')) {
  1111. $name = C('TOKEN_NAME', null, '__hash__');
  1112. if (!isset($data[$name]) || !isset($_SESSION[$name])) {
  1113. // 令牌数据无效
  1114. return false;
  1115. }
  1116. // 令牌验证
  1117. list($key, $value) = explode('_', $data[$name]);
  1118. if (isset($_SESSION[$name][$key]) && $value && $_SESSION[$name][$key] === $value) {
  1119. // 防止重复提交
  1120. unset($_SESSION[$name][$key]); // 验证完成销毁session
  1121. return true;
  1122. }
  1123. // 开启TOKEN重置
  1124. if (C('TOKEN_RESET')) {
  1125. unset($_SESSION[$name][$key]);
  1126. }
  1127. return false;
  1128. }
  1129. return true;
  1130. }
  1131. /**
  1132. * 使用正则验证数据
  1133. * @access public
  1134. * @param string $value 要验证的数据
  1135. * @param string $rule 验证规则
  1136. * @return boolean
  1137. */
  1138. public function regex($value, $rule)
  1139. {
  1140. $validate = array(
  1141. 'require' => '/\S+/',
  1142. 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
  1143. 'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(:\d+)?(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
  1144. 'currency' => '/^\d+(\.\d+)?$/',
  1145. 'number' => '/^\d+$/',
  1146. 'zip' => '/^\d{6}$/',
  1147. 'integer' => '/^[-\+]?\d+$/',
  1148. 'double' => '/^[-\+]?\d+(\.\d+)?$/',
  1149. 'english' => '/^[A-Za-z]+$/',
  1150. );
  1151. // 检查是否有内置的正则表达式
  1152. if (isset($validate[strtolower($rule)])) {
  1153. $rule = $validate[strtolower($rule)];
  1154. }
  1155. return preg_match($rule, $value) === 1;
  1156. }
  1157. /**
  1158. * 自动表单处理
  1159. * @access public
  1160. * @param array $data 创建数据
  1161. * @param string $type 创建类型
  1162. * @return mixed
  1163. */
  1164. private function autoOperation(&$data, $type)
  1165. {
  1166. if (isset($this->options['auto']) && false === $this->options['auto']) {
  1167. // 关闭自动完成
  1168. return $data;
  1169. }
  1170. if (!empty($this->options['auto'])) {
  1171. $_auto = $this->options['auto'];
  1172. unset($this->options['auto']);
  1173. } elseif (!empty($this->_auto)) {
  1174. $_auto = $this->_auto;
  1175. }
  1176. // 自动填充
  1177. if (isset($_auto)) {
  1178. foreach ($_auto as $auto) {
  1179. // 填充因子定义格式
  1180. // array('field','填充内容','填充条件','附加规则',[额外参数])
  1181. if (empty($auto[2])) {
  1182. $auto[2] = self::MODEL_INSERT;
  1183. }
  1184. // 默认为新增的时候自动填充
  1185. if ($type == $auto[2] || self::MODEL_BOTH == $auto[2]) {
  1186. if (empty($auto[3])) {
  1187. $auto[3] = 'string';
  1188. }
  1189. switch (trim($auto[3])) {
  1190. case 'function': // 使用函数进行填充 字段的值作为参数
  1191. case 'callback': // 使用回调方法
  1192. $args = isset($auto[4]) ? (array) $auto[4] : array();
  1193. if (isset($data[$auto[0]])) {
  1194. array_unshift($args, $data[$auto[0]]);
  1195. }
  1196. if ('function' == $auto[3]) {
  1197. $data[$auto[0]] = call_user_func_array($auto[1], $args);
  1198. } else {
  1199. $data[$auto[0]] = call_user_func_array(array(&$this, $auto[1]), $args);
  1200. }
  1201. break;
  1202. case 'field': // 用其它字段的值进行填充
  1203. $data[$auto[0]] = $data[$auto[1]];
  1204. break;
  1205. case 'ignore': // 为空忽略
  1206. if ($auto[1] === $data[$auto[0]]) {
  1207. unset($data[$auto[0]]);
  1208. }
  1209. break;
  1210. case 'string':
  1211. default: // 默认作为字符串填充
  1212. $data[$auto[0]] = $auto[1];
  1213. }
  1214. if (isset($data[$auto[0]]) && false === $data[$auto[0]]) {
  1215. unset($data[$auto[0]]);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. return $data;
  1221. }
  1222. /**
  1223. * 自动表单验证
  1224. * @access protected
  1225. * @param array $data 创建数据
  1226. * @param string $type 创建类型
  1227. * @return boolean
  1228. */
  1229. protected function autoValidation($data, $type)
  1230. {
  1231. if (isset($this->options['validate']) && false === $this->options['validate']) {
  1232. // 关闭自动验证
  1233. return true;
  1234. }
  1235. if (!empty($this->options['validate'])) {
  1236. $_validate = $this->options['validate'];
  1237. unset($this->options['validate']);
  1238. } elseif (!empty($this->_validate)) {
  1239. $_validate = $this->_validate;
  1240. }
  1241. // 属性验证
  1242. if (isset($_validate)) {
  1243. // 如果设置了数据自动验证则进行数据验证
  1244. if ($this->patchValidate) {
  1245. // 重置验证错误信息
  1246. $this->error = array();
  1247. }
  1248. foreach ($_validate as $key => $val) {
  1249. // 验证因子定义格式
  1250. // array(field,rule,message,condition,type,when,params)
  1251. // 判断是否需要执行验证
  1252. if (empty($val[5]) || (self::MODEL_BOTH == $val[5] && $type < 3) || $val[5] == $type) {
  1253. if (0 == strpos($val[2], '{%') && strpos($val[2], '}'))
  1254. // 支持提示信息的多语言 使用 {%语言定义} 方式
  1255. {
  1256. $val[2] = L(substr($val[2], 2, -1));
  1257. }
  1258. $val[3] = isset($val[3]) ? $val[3] : self::EXISTS_VALIDATE;
  1259. $val[4] = isset($val[4]) ? $val[4] : 'regex';
  1260. // 判断验证条件
  1261. switch ($val[3]) {
  1262. case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段
  1263. if (false === $this->_validationField($data, $val)) {
  1264. return false;
  1265. }
  1266. break;
  1267. case self::VALUE_VALIDATE: // 值不为空的时候才验证
  1268. if ('' != trim($data[$val[0]])) {
  1269. if (false === $this->_validationField($data, $val)) {
  1270. return false;
  1271. }
  1272. }
  1273. break;
  1274. default: // 默认表单存在该字段就验证
  1275. if (isset($data[$val[0]])) {
  1276. if (false === $this->_validationField($data, $val)) {
  1277. return false;
  1278. }
  1279. }
  1280. }
  1281. }
  1282. }
  1283. // 批量验证的时候最后返回错误
  1284. if (!empty($this->error)) {
  1285. return false;
  1286. }
  1287. }
  1288. return true;
  1289. }
  1290. /**
  1291. * 验证表单字段 支持批量验证
  1292. * 如果批量验证返回错误的数组信息
  1293. * @access protected
  1294. * @param array $data 创建数据
  1295. * @param array $val 验证因子
  1296. * @return boolean
  1297. */
  1298. protected function _validationField($data, $val)
  1299. {
  1300. if ($this->patchValidate && isset($this->error[$val[0]])) {
  1301. //当前字段已经有规则验证没有通过
  1302. return;
  1303. }
  1304. if (false === $this->_validationFieldItem($data, $val)) {
  1305. if ($this->patchValidate) {
  1306. $this->error[$val[0]] = $val[2];
  1307. } else {
  1308. $this->error = $val[2];
  1309. return false;
  1310. }
  1311. }
  1312. return;
  1313. }
  1314. /**
  1315. * 根据验证因子验证字段
  1316. * @access protected
  1317. * @param array $data 创建数据
  1318. * @param array $val 验证因子
  1319. * @return boolean
  1320. */
  1321. protected function _validationFieldItem($data, $val)
  1322. {
  1323. switch (strtolower(trim($val[4]))) {
  1324. case 'function': // 使用函数进行验证
  1325. case 'callback': // 调用方法进行验证
  1326. $args = isset($val[6]) ? (array) $val[6] : array();
  1327. if (is_string($val[0]) && strpos($val[0], ',')) {
  1328. $val[0] = explode(',', $val[0]);
  1329. }
  1330. if (is_array($val[0])) {
  1331. // 支持多个字段验证
  1332. foreach ($val[0] as $field) {
  1333. $_data[$field] = $data[$field];
  1334. }
  1335. array_unshift($args, $_data);
  1336. } else {
  1337. array_unshift($args, $data[$val[0]]);
  1338. }
  1339. if ('function' == $val[4]) {
  1340. return call_user_func_array($val[1], $args);
  1341. } else {
  1342. return call_user_func_array(array(&$this, $val[1]), $args);
  1343. }
  1344. case 'confirm': // 验证两个字段是否相同
  1345. return $data[$val[0]] == $data[$val[1]];
  1346. case 'unique': // 验证某个值是否唯一
  1347. if (is_string($val[0]) && strpos($val[0], ',')) {
  1348. $val[0] = explode(',', $val[0]);
  1349. }
  1350. $map = array();
  1351. if (is_array($val[0])) {
  1352. // 支持多个字段验证
  1353. foreach ($val[0] as $field) {
  1354. $map[$field] = $data[$field];
  1355. }
  1356. } else {
  1357. $map[$val[0]] = $data[$val[0]];
  1358. }
  1359. $pk = $this->getPk();
  1360. if (!empty($data[$pk]) && is_string($pk)) {
  1361. // 完善编辑的时候验证唯一
  1362. $map[$pk] = array('neq', $data[$pk]);
  1363. }
  1364. $options = $this->options;
  1365. if ($this->where($map)->find()) {
  1366. return false;
  1367. }
  1368. $this->options = $options;
  1369. return true;
  1370. default: // 检查附加规则
  1371. return $this->check($data[$val[0]], $val[1], $val[4]);
  1372. }
  1373. }
  1374. /**
  1375. * 验证数据 支持 in between equal length regex expire ip_allow ip_deny
  1376. * @access public
  1377. * @param string $value 验证数据
  1378. * @param mixed $rule 验证表达式
  1379. * @param string $type 验证方式 默认为正则验证
  1380. * @return boolean
  1381. */
  1382. public function check($value, $rule, $type = 'regex')
  1383. {
  1384. $type = strtolower(trim($type));
  1385. switch ($type) {
  1386. case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组
  1387. case 'notin':
  1388. $range = is_array($rule) ? $rule : explode(',', $rule);
  1389. return 'in' == $type ? in_array($value, $range) : !in_array($value, $range);
  1390. case 'between': // 验证是否在某个范围
  1391. case 'notbetween': // 验证是否不在某个范围
  1392. if (is_array($rule)) {
  1393. $min = $rule[0];
  1394. $max = $rule[1];
  1395. } else {
  1396. list($min, $max) = explode(',', $rule);
  1397. }
  1398. return 'between' == $type ? $value >= $min && $value <= $max : $value < $min || $value > $max;
  1399. case 'equal': // 验证是否等于某个值
  1400. case 'notequal': // 验证是否等于某个值
  1401. return 'equal' == $type ? $value == $rule : $value != $rule;
  1402. case 'length': // 验证长度
  1403. $length = mb_strlen($value, 'utf-8'); // 当前数据长度
  1404. if (strpos($rule, ',')) {
  1405. // 长度区间
  1406. list($min, $max) = explode(',', $rule);
  1407. return $length >= $min && $length <= $max;
  1408. } else {
  1409. // 指定长度
  1410. return $length == $rule;
  1411. }
  1412. case 'expire':
  1413. list($start, $end) = explode(',', $rule);
  1414. if (!is_numeric($start)) {
  1415. $start = strtotime($start);
  1416. }
  1417. if (!is_numeric($end)) {
  1418. $end = strtotime($end);
  1419. }
  1420. return NOW_TIME >= $start && NOW_TIME <= $end;
  1421. case 'ip_allow': // IP 操作许可验证
  1422. return in_array(get_client_ip(), explode(',', $rule));
  1423. case 'ip_deny': // IP 操作禁止验证
  1424. return !in_array(get_client_ip(), explode(',', $rule));
  1425. case 'regex':
  1426. default: // 默认使用正则验证 可以使用验证类中定义的验证名称
  1427. // 检查附加规则
  1428. return $this->regex($value, $rule);
  1429. }
  1430. }
  1431. /**
  1432. * 存储过程返回多数据集
  1433. * @access public
  1434. * @param string $sql SQL指令
  1435. * @param mixed $parse 是否需要解析SQL
  1436. * @return array
  1437. */
  1438. public function procedure($sql, $parse = false)
  1439. {
  1440. return $this->db->procedure($sql, $parse);
  1441. }
  1442. /**
  1443. * SQL查询
  1444. * @access public
  1445. * @param string $sql SQL指令
  1446. * @param mixed $parse 是否需要解析SQL
  1447. * @return mixed
  1448. */
  1449. public function query($sql, $parse = false)
  1450. {
  1451. if (!is_bool($parse) && !is_array($parse)) {
  1452. $parse = func_get_args();
  1453. array_shift($parse);
  1454. }
  1455. $sql = $this->parseSql($sql, $parse);
  1456. return $this->db->query($sql);
  1457. }
  1458. /**
  1459. * 执行SQL语句
  1460. * @access public
  1461. * @param string $sql SQL指令
  1462. * @param mixed $parse 是否需要解析SQL
  1463. * @return false | integer
  1464. */
  1465. public function execute($sql, $parse = false)
  1466. {
  1467. if (!is_bool($parse) && !is_array($parse)) {
  1468. $parse = func_get_args();
  1469. array_shift($parse);
  1470. }
  1471. $sql = $this->parseSql($sql, $parse);
  1472. return $this->db->execute($sql);
  1473. }
  1474. /**
  1475. * 解析SQL语句
  1476. * @access public
  1477. * @param string $sql SQL指令
  1478. * @param boolean $parse 是否需要解析SQL
  1479. * @return string
  1480. */
  1481. protected function parseSql($sql, $parse)
  1482. {
  1483. // 分析表达式
  1484. if (true === $parse) {
  1485. $options = $this->_parseOptions();
  1486. $sql = $this->db->parseSql($sql, $options);
  1487. } elseif (is_array($parse)) {
  1488. // SQL预处理
  1489. $parse = array_map(array($this->db, 'escapeString'), $parse);
  1490. $sql = vsprintf($sql, $parse);
  1491. } else {
  1492. $sql = strtr($sql, array('__TABLE__' => $this->getTableName(), '__PREFIX__' => $this->tablePrefix));
  1493. $prefix = $this->tablePrefix;
  1494. $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $sql);
  1495. }
  1496. $this->db->setModel($this->name);
  1497. return $sql;
  1498. }
  1499. /**
  1500. * 切换当前的数据库连接
  1501. * @access public
  1502. * @param integer $linkNum 连接序号
  1503. * @param mixed $config 数据库连接信息
  1504. * @param boolean $force 强制重新连接
  1505. * @return Model
  1506. */
  1507. public function db($linkNum = '', $config = '', $force = false)
  1508. {
  1509. if ('' === $linkNum && $this->db) {
  1510. return $this->db;
  1511. }
  1512. if (!isset($this->_db[$linkNum]) || $force) {
  1513. // 创建一个新的实例
  1514. if (!empty($config) && is_string($config) && false === strpos($config, '/')) {
  1515. // 支持读取配置参数
  1516. $config = C($config);
  1517. }
  1518. $this->_db[$linkNum] = Db::getInstance($config);
  1519. } elseif (null === $config) {
  1520. $this->_db[$linkNum]->close(); // 关闭数据库连接
  1521. unset($this->_db[$linkNum]);
  1522. return;
  1523. }
  1524. // 切换数据库连接
  1525. $this->db = $this->_db[$linkNum];
  1526. $this->_after_db();
  1527. // 字段检测
  1528. if (!empty($this->name) && $this->autoCheckFields) {
  1529. $this->_checkTableInfo();
  1530. }
  1531. return $this;
  1532. }
  1533. // 数据库切换后回调方法
  1534. protected function _after_db()
  1535. {}
  1536. /**
  1537. * 得到当前的数据对象名称
  1538. * @access public
  1539. * @return string
  1540. */
  1541. public function getModelName()
  1542. {
  1543. if (empty($this->name)) {
  1544. $name = substr(get_class($this), 0, -strlen(C('DEFAULT_M_LAYER')));
  1545. if ($pos = strrpos($name, '\\')) {
  1546. //有命名空间
  1547. $this->name = substr($name, $pos + 1);
  1548. } else {
  1549. $this->name = $name;
  1550. }
  1551. }
  1552. return $this->name;
  1553. }
  1554. /**
  1555. * 得到完整的数据表名
  1556. * @access public
  1557. * @return string
  1558. */
  1559. public function getTableName()
  1560. {
  1561. if (empty($this->trueTableName)) {
  1562. $tableName = !empty($this->tablePrefix) ? $this->tablePrefix : '';
  1563. if (!empty($this->tableName)) {
  1564. $tableName .= $this->tableName;
  1565. } else {
  1566. $tableName .= parse_name($this->name);
  1567. }
  1568. $this->trueTableName = strtolower($tableName);
  1569. }
  1570. return (!empty($this->dbName) ? $this->dbName . '.' : '') . $this->trueTableName;
  1571. }
  1572. /**
  1573. * 启动事务
  1574. * @access public
  1575. * @return void
  1576. */
  1577. public function startTrans()
  1578. {
  1579. $this->commit();
  1580. $this->db->startTrans();
  1581. return;
  1582. }
  1583. /**
  1584. * 提交事务
  1585. * @access public
  1586. * @return boolean
  1587. */
  1588. public function commit()
  1589. {
  1590. return $this->db->commit();
  1591. }
  1592. /**
  1593. * 事务回滚
  1594. * @access public
  1595. * @return boolean
  1596. */
  1597. public function rollback()
  1598. {
  1599. return $this->db->rollback();
  1600. }
  1601. /**
  1602. * 返回模型的错误信息
  1603. * @access public
  1604. * @return string
  1605. */
  1606. public function getError()
  1607. {
  1608. return $this->error;
  1609. }
  1610. /**
  1611. * 返回数据库的错误信息
  1612. * @access public
  1613. * @return string
  1614. */
  1615. public function getDbError()
  1616. {
  1617. return $this->db->getError();
  1618. }
  1619. /**
  1620. * 返回最后插入的ID
  1621. * @access public
  1622. * @return string
  1623. */
  1624. public function getLastInsID()
  1625. {
  1626. return $this->db->getLastInsID();
  1627. }
  1628. /**
  1629. * 返回最后执行的sql语句
  1630. * @access public
  1631. * @return string
  1632. */
  1633. public function getLastSql()
  1634. {
  1635. return $this->db->getLastSql($this->name);
  1636. }
  1637. // 鉴于getLastSql比较常用 增加_sql 别名
  1638. public function _sql()
  1639. {
  1640. return $this->getLastSql();
  1641. }
  1642. /**
  1643. * 获取主键名称
  1644. * @access public
  1645. * @return string
  1646. */
  1647. public function getPk()
  1648. {
  1649. return $this->pk;
  1650. }
  1651. /**
  1652. * 获取数据表字段信息
  1653. * @access public
  1654. * @return array
  1655. */
  1656. public function getDbFields()
  1657. {
  1658. if (isset($this->options['table'])) {
  1659. // 动态指定表名
  1660. if (is_array($this->options['table'])) {
  1661. $table = key($this->options['table']);
  1662. } else {
  1663. $table = $this->options['table'];
  1664. if (strpos($table, ')')) {
  1665. // 子查询
  1666. return false;
  1667. }
  1668. }
  1669. $fields = $this->db->getFields($table);
  1670. return $fields ? array_keys($fields) : false;
  1671. }
  1672. if ($this->fields) {
  1673. $fields = $this->fields;
  1674. unset($fields['_type'], $fields['_pk']);
  1675. return $fields;
  1676. }
  1677. return false;
  1678. }
  1679. /**
  1680. * 设置数据对象值
  1681. * @access public
  1682. * @param mixed $data 数据
  1683. * @return Model
  1684. */
  1685. public function data($data = '')
  1686. {
  1687. if ('' === $data && !empty($this->data)) {
  1688. return $this->data;
  1689. }
  1690. if (is_object($data)) {
  1691. $data = get_object_vars($data);
  1692. } elseif (is_string($data)) {
  1693. parse_str($data, $data);
  1694. } elseif (!is_array($data)) {
  1695. E(L('_DATA_TYPE_INVALID_'));
  1696. }
  1697. $this->data = $data;
  1698. return $this;
  1699. }
  1700. /**
  1701. * 指定当前的数据表
  1702. * @access public
  1703. * @param mixed $table
  1704. * @return Model
  1705. */
  1706. public function table($table)
  1707. {
  1708. $prefix = $this->tablePrefix;
  1709. if (is_array($table)) {
  1710. $this->options['table'] = $table;
  1711. } elseif (!empty($table)) {
  1712. //将__TABLE_NAME__替换成带前缀的表名
  1713. $table = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $table);
  1714. $this->options['table'] = $table;
  1715. }
  1716. return $this;
  1717. }
  1718. /**
  1719. * USING支持 用于多表删除
  1720. * @access public
  1721. * @param mixed $using
  1722. * @return Model
  1723. */
  1724. public function using($using)
  1725. {
  1726. $prefix = $this->tablePrefix;
  1727. if (is_array($using)) {
  1728. $this->options['using'] = $using;
  1729. } elseif (!empty($using)) {
  1730. //将__TABLE_NAME__替换成带前缀的表名
  1731. $using = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $using);
  1732. $this->options['using'] = $using;
  1733. }
  1734. return $this;
  1735. }
  1736. /**
  1737. * 查询SQL组装 join
  1738. * @access public
  1739. * @param mixed $join
  1740. * @param string $type JOIN类型
  1741. * @return Model
  1742. */
  1743. public function join($join, $type = 'INNER')
  1744. {
  1745. $prefix = $this->tablePrefix;
  1746. if (is_array($join)) {
  1747. foreach ($join as $key => &$_join) {
  1748. $_join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $_join);
  1749. $_join = false !== stripos($_join, 'JOIN') ? $_join : $type . ' JOIN ' . $_join;
  1750. }
  1751. $this->options['join'] = $join;
  1752. } elseif (!empty($join)) {
  1753. //将__TABLE_NAME__字符串替换成带前缀的表名
  1754. $join = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $join);
  1755. $this->options['join'][] = false !== stripos($join, 'JOIN') ? $join : $type . ' JOIN ' . $join;
  1756. }
  1757. return $this;
  1758. }
  1759. /**
  1760. * 查询SQL组装 union
  1761. * @access public
  1762. * @param mixed $union
  1763. * @param boolean $all
  1764. * @return Model
  1765. */
  1766. public function union($union, $all = false)
  1767. {
  1768. if (empty($union)) {
  1769. return $this;
  1770. }
  1771. if ($all) {
  1772. $this->options['union']['_all'] = true;
  1773. }
  1774. if (is_object($union)) {
  1775. $union = get_object_vars($union);
  1776. }
  1777. // 转换union表达式
  1778. if (is_string($union)) {
  1779. $prefix = $this->tablePrefix;
  1780. //将__TABLE_NAME__字符串替换成带前缀的表名
  1781. $options = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $union);
  1782. } elseif (is_array($union)) {
  1783. if (isset($union[0])) {
  1784. $this->options['union'] = array_merge($this->options['union'], $union);
  1785. return $this;
  1786. } else {
  1787. $options = $union;
  1788. }
  1789. } else {
  1790. E(L('_DATA_TYPE_INVALID_'));
  1791. }
  1792. $this->options['union'][] = $options;
  1793. return $this;
  1794. }
  1795. /**
  1796. * 查询缓存
  1797. * @access public
  1798. * @param mixed $key
  1799. * @param integer $expire
  1800. * @param string $type
  1801. * @return Model
  1802. */
  1803. public function cache($key = true, $expire = null, $type = '')
  1804. {
  1805. // 增加快捷调用方式 cache(10) 等同于 cache(true, 10)
  1806. if (is_numeric($key) && is_null($expire)) {
  1807. $expire = $key;
  1808. $key = true;
  1809. }
  1810. if (false !== $key) {
  1811. $this->options['cache'] = array('key' => $key, 'expire' => $expire, 'type' => $type);
  1812. }
  1813. return $this;
  1814. }
  1815. /**
  1816. * 指定查询字段 支持字段排除
  1817. * @access public
  1818. * @param mixed $field
  1819. * @param boolean $except 是否排除
  1820. * @return Model
  1821. */
  1822. public function field($field, $except = false)
  1823. {
  1824. if (true === $field) {
  1825. // 获取全部字段
  1826. $fields = $this->getDbFields();
  1827. $field = $fields ?: '*';
  1828. } elseif ($except) {
  1829. // 字段排除
  1830. if (is_string($field)) {
  1831. $field = explode(',', $field);
  1832. }
  1833. $fields = $this->getDbFields();
  1834. $field = $fields ? array_diff($fields, $field) : $field;
  1835. }
  1836. $this->options['field'] = $field;
  1837. return $this;
  1838. }
  1839. /**
  1840. * 调用命名范围
  1841. * @access public
  1842. * @param mixed $scope 命名范围名称 支持多个 和直接定义
  1843. * @param array $args 参数
  1844. * @return Model
  1845. */
  1846. public function scope($scope = '', $args = null)
  1847. {
  1848. if ('' === $scope) {
  1849. if (isset($this->_scope['default'])) {
  1850. // 默认的命名范围
  1851. $options = $this->_scope['default'];
  1852. } else {
  1853. return $this;
  1854. }
  1855. } elseif (is_string($scope)) {
  1856. // 支持多个命名范围调用 用逗号分割
  1857. $scopes = explode(',', $scope);
  1858. $options = array();
  1859. foreach ($scopes as $name) {
  1860. if (!isset($this->_scope[$name])) {
  1861. continue;
  1862. }
  1863. $options = array_merge($options, $this->_scope[$name]);
  1864. }
  1865. if (!empty($args) && is_array($args)) {
  1866. $options = array_merge($options, $args);
  1867. }
  1868. } elseif (is_array($scope)) {
  1869. // 直接传入命名范围定义
  1870. $options = $scope;
  1871. }
  1872. if (is_array($options) && !empty($options)) {
  1873. $this->options = array_merge($this->options, array_change_key_case($options));
  1874. }
  1875. return $this;
  1876. }
  1877. /**
  1878. * 指定查询条件 支持安全过滤
  1879. * @access public
  1880. * @param mixed $where 条件表达式
  1881. * @param mixed $parse 预处理参数
  1882. * @return Model
  1883. */
  1884. public function where($where, $parse = null)
  1885. {
  1886. if (!is_null($parse) && is_string($where)) {
  1887. if (!is_array($parse)) {
  1888. $parse = func_get_args();
  1889. array_shift($parse);
  1890. }
  1891. $parse = array_map(array($this->db, 'escapeString'), $parse);
  1892. $where = vsprintf($where, $parse);
  1893. } elseif (is_object($where)) {
  1894. $where = get_object_vars($where);
  1895. }
  1896. if (is_string($where) && '' != $where) {
  1897. $map = array();
  1898. $map['_string'] = $where;
  1899. $where = $map;
  1900. }
  1901. if (isset($this->options['where'])) {
  1902. $this->options['where'] = array_merge($this->options['where'], $where);
  1903. } else {
  1904. $this->options['where'] = $where;
  1905. }
  1906. return $this;
  1907. }
  1908. /**
  1909. * 指定查询数量
  1910. * @access public
  1911. * @param mixed $offset 起始位置
  1912. * @param mixed $length 查询数量
  1913. * @return Model
  1914. */
  1915. public function limit($offset, $length = null)
  1916. {
  1917. if (is_null($length) && strpos($offset, ',')) {
  1918. list($offset, $length) = explode(',', $offset);
  1919. }
  1920. $this->options['limit'] = intval($offset) . ($length ? ',' . intval($length) : '');
  1921. return $this;
  1922. }
  1923. /**
  1924. * 指定分页
  1925. * @access public
  1926. * @param mixed $page 页数
  1927. * @param mixed $listRows 每页数量
  1928. * @return Model
  1929. */
  1930. public function page($page, $listRows = null)
  1931. {
  1932. if (is_null($listRows) && strpos($page, ',')) {
  1933. list($page, $listRows) = explode(',', $page);
  1934. }
  1935. $this->options['page'] = array(intval($page), intval($listRows));
  1936. return $this;
  1937. }
  1938. /**
  1939. * 查询注释
  1940. * @access public
  1941. * @param string $comment 注释
  1942. * @return Model
  1943. */
  1944. public function comment($comment)
  1945. {
  1946. $this->options['comment'] = $comment;
  1947. return $this;
  1948. }
  1949. /**
  1950. * 获取执行的SQL语句
  1951. * @access public
  1952. * @param boolean $fetch 是否返回sql
  1953. * @return Model
  1954. */
  1955. public function fetchSql($fetch = true)
  1956. {
  1957. $this->options['fetch_sql'] = $fetch;
  1958. return $this;
  1959. }
  1960. /**
  1961. * 参数绑定
  1962. * @access public
  1963. * @param string $key 参数名
  1964. * @param mixed $value 绑定的变量及绑定参数
  1965. * @return Model
  1966. */
  1967. public function bind($key, $value = false)
  1968. {
  1969. if (is_array($key)) {
  1970. $this->options['bind'] = $key;
  1971. } else {
  1972. $num = func_num_args();
  1973. if ($num > 2) {
  1974. $params = func_get_args();
  1975. array_shift($params);
  1976. $this->options['bind'][$key] = $params;
  1977. } else {
  1978. $this->options['bind'][$key] = $value;
  1979. }
  1980. }
  1981. return $this;
  1982. }
  1983. /**
  1984. * 设置模型的属性值
  1985. * @access public
  1986. * @param string $name 名称
  1987. * @param mixed $value 值
  1988. * @return Model
  1989. */
  1990. public function setProperty($name, $value)
  1991. {
  1992. if (property_exists($this, $name)) {
  1993. $this->$name = $value;
  1994. }
  1995. return $this;
  1996. }
  1997. }