Model.class.php 65 KB

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