Model.class.php 65 KB

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