Model.class.php 67 KB

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