PHP简单MVC架构

时间:2023-12-27 16:35:13

http://blog.csdn.net/haiqiao_2010/article/details/12166283

由于需要搭建一个简单的框架来进行API接口开发,所以简单的mvc框架当然是首选.最原始,最简洁的mvc框架.下面来介绍下.

一. 项目目录结构:

app 
|-controller    存放控制器文件 
|-model        存放模型文件 
|-view        存放视图文件

core
|-lib        存放自定义类库 
|-config    存放配置文件 
|--config.php   系统配置文件

|--conn.php   数据库连接文件

|--db_config.php  
数据库配置文件 
|-mysql_db.php    数据库类文件

|-runtime    缓存文件

db_caches 数据库缓存文件

logs日志文件

|-index.php    入口文件

| -dispatcher.php

|
-loader.php

|
-router.php

二.项目架构

1.先介绍index.php,附源码:

  1. <?php
  2. include("./core/ini.php");
  3. include("./core/config/config.php");
  4. include("./core/global.fun.php");
  5. include("./core/common.php");
  6. initializer::initialize();//加载将要用到的目录文件<span style="font-family:verdana,sans-serif; font-size:13px; line-height:19px">,即调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.</span>
  7. $router = loader::load("router");//加载URL处理文件,对url进行解析--<span style="font-family:verdana,sans-serif; font-size:13px; line-height:19px">加载loader函数的静态函数load</span>
  8. dispatcher::dispatch($router);//<span style="font-family:verdana,sans-serif; font-size:13px; line-height:19px">router.php文件,这个文件的作用就是映射URL,对URL进行解析.</span>根据解析到的URL参数加载相关controller及action
  9. ?>

2.初始化项目文件
./core/ini.php 源码:

  1. <?php
  2. set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");
  3. //set_include_path — Sets the include_path configuration option
  4. function __autoload($object){
  5. require_once("{$object}.php");
  6. }

这个文件首先设置了include_path,也就是我们如果要找包含的文件,告诉系统在这个目录下查找。其实我们定义__autoload()方法,这个方法是在PHP5增加的,就是当我们实例化一个函数的时候,如果本文件没有,就会自动去加载文件

3.加载系统配置文件./core/config.php
源码:

  1. <?php
  2. /*
  3. * 设置页面编码格式
  4. */
  5. header("content-type:text/html;charset=utf-8");
  6. //禁用错误报告
  7. error_reporting(0);
  8. date_default_timezone_set("PRC");
  9. //定义常量
  10. define("URL_PATH","<a target="_blank" href="http://blog.csdn.net/haiqiao_2010">http://blog.csdn.net/haiqiao_2010</a>");//服务器IP
  11. define('IMG_PATH',"<a target="_blank" href="http://blog.csdn.net/haiqiao_2010">http://blog.csdn.net/haiqiao_2010</a>");//服务器图片目录
  12. //判断日志是否开启
  13. defined("APP_LOG") or define("APP_LOG",true);
  14. if (APP_LOG) {
  15. $GLOBALS['log'] = new APIlog();
  16. set_exception_handler(array($GLOBALS['log'],'quit'));
  17. set_error_handler(array($GLOBALS['log'],'error_handle'));
  18. }
  19. define('IS_CGI',substr(PHP_SAPI, 0,3)=='cgi' ? 1 : 0 );
  20. define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 );
  21. define('IS_CLI',PHP_SAPI=='cli'? 1   :   0);
  22. if(!defined('APP_NAME')) define('APP_NAME', basename(dirname($_SERVER['SCRIPT_FILENAME'])));
  23. if(!IS_CLI) {
  24. // 当前文件名
  25. if(!defined('_PHP_FILE_')) {
  26. if(IS_CGI) {
  27. //CGI/FASTCGI模式下
  28. $_temp  = explode('.php',$_SERVER["PHP_SELF"]);
  29. define('_PHP_FILE_',  rtrim(str_replace($_SERVER["HTTP_HOST"],'',$_temp[0].'.php'),'/'));
  30. }else {
  31. define('_PHP_FILE_',    rtrim($_SERVER["SCRIPT_NAME"],'/'));
  32. }
  33. }
  34. if(!defined('__ROOT__')) {
  35. // 网站URL根目录
  36. if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) {
  37. $_root = dirname(dirname(_PHP_FILE_));
  38. }else {
  39. $_root = dirname(_PHP_FILE_);
  40. }
  41. define('__ROOT__',   (($_root=='/' || $_root=='\\')?'':$_root));
  42. }
  43. //支持的URL模式
  44. define('URL_COMMON',      0);   //普通模式
  45. define('URL_PATHINFO',    1);   //PATHINFO模式
  46. define('URL_REWRITE',     2);   //REWRITE模式
  47. define('URL_COMPAT',      3);   // 兼容模式
  48. }
  49. if(!defined('APP_ROOT')) {//项目根路径
  50. // 网站URL根目录
  51. $_root = dirname(_PHP_FILE_);
  52. $_root = (($_root=='/' || $_root=='\\')?'':$_root);
  53. $_root = str_replace("/system","",$_root);
  54. define('APP_ROOT', $_root  );
  55. }
  56. if(!defined('APP_ROOT_PATH'))//项目绝对路径
  57. define('APP_ROOT_PATH', str_replace("\\","/",substr(dirname(__FILE__),0,-11)));
  58. if(!defined('PAGE_SIZE'))//im:页面大小
  59. define('PAGE_SIZE',15);
  60. ?>

4.加载通用的方法的文件./core/global_fun.php
源码:

  1. <?php
  2. //header("content-type:text/html;charset=utf-8");
  3. /*
  4. <span style="white-space:pre">  </span>*   过滤sql语句的关键字
  5. <span style="white-space:pre">  </span>*/
  6. function strip_sql($string){
  7. <span style="white-space:pre">  </span>   global $search_arr,$replace_arr;
  8. <span style="white-space:pre">  </span>   return is_array($string) ? array_map('strip_sql', $string) : preg_replace($search_arr, $replace_arr, $string);
  9. }
  10. function new_htmlspecialchars($string){
  11. <span style="white-space:pre">      </span>return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string,ENT_QUOTES);
  12. }
  13. function new_addslashes($string){
  14. <span style="white-space:pre">      </span>if(!is_array($string)) return addslashes($string);
  15. <span style="white-space:pre">      </span>foreach($string as $key => $val) $string[$key] = new_addslashes($val);
  16. <span style="white-space:pre">      </span>return $string;
  17. }
  18. function new_stripslashes($string)
  19. {
  20. <span style="white-space:pre">      </span>if(!is_array($string)) return stripslashes($string);
  21. <span style="white-space:pre">      </span>foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
  22. <span style="white-space:pre">      </span>return $string;
  23. }
  24. function strip_textarea($string){
  25. <span style="white-space:pre">      </span>return nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($string, ENT_QUOTES)));
  26. }
  27. function strip_js($string, $js = 1){
  28. <span style="white-space:pre">      </span>$string = str_replace(array("\n","\r","\""),array('','',"\\\""),$string);
  29. <span style="white-space:pre">      </span>return $js==1 ? "document.write(\"".$string."\");\n" : $string;
  30. }
  31. //邮件格式验证的函数
  32. function check_email($email)
  33. {
  34. <span style="white-space:pre"> </span>if(!preg_match("/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/",$email))
  35. <span style="white-space:pre"> </span>{
  36. <span style="white-space:pre">     </span>return false;
  37. <span style="white-space:pre"> </span>}
  38. <span style="white-space:pre"> </span>else
  39. <span style="white-space:pre">     </span>return true;
  40. }
  41. //验证手机号码
  42. function check_mobile($mobile)
  43. {
  44. <span style="white-space:pre">     </span>$pattern = "/^1\d{10}$/";
  45. <span style="white-space:pre">     </span>if (preg_match($pattern,$mobile))
  46. <span style="white-space:pre">     </span>{
  47. <span style="white-space:pre">         </span>Return true;
  48. <span style="white-space:pre">     </span>}
  49. <span style="white-space:pre">     </span>else
  50. <span style="white-space:pre">     </span>{
  51. <span style="white-space:pre">         </span>Return false;
  52. <span style="white-space:pre">     </span>}
  53. }
  54. //获取GMTime
  55. function get_gmtime()
  56. {
  57. <span style="white-space:pre"> </span>return (time() - date('Z'));
  58. }
  59. function to_date($utc_time, $format = 'Y-m-d H:i:s') {
  60. <span style="white-space:pre"> </span>if (empty ( $utc_time )) {
  61. <span style="white-space:pre">     </span>return '';
  62. <span style="white-space:pre"> </span>}
  63. <span style="white-space:pre"> </span>$timezone = 8;
  64. <span style="white-space:pre"> </span>$time = $utc_time + $timezone * 3600;
  65. <span style="white-space:pre"> </span>return date ($format, $time );
  66. }
  67. function to_timespan($str, $format = 'Y-m-d H:i:s')
  68. {
  69. <span style="white-space:pre"> </span>$timezone = 8;
  70. <span style="white-space:pre"> </span>$time = intval(strtotime($str));
  71. <span style="white-space:pre"> </span>if($time!=0)
  72. <span style="white-space:pre">     </span>$time = $time - $timezone * 3600;
  73. <span style="white-space:pre"> </span>return $time;
  74. }
  75. function get_http()
  76. {
  77. <span style="white-space:pre"> </span>return (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
  78. }
  79. function get_domain()
  80. {
  81. <span style="white-space:pre"> </span>/* 协议 */
  82. <span style="white-space:pre"> </span>$protocol = get_http();
  83. <span style="white-space:pre"> </span>/* 域名或IP地址 */
  84. <span style="white-space:pre"> </span>if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
  85. <span style="white-space:pre"> </span>{
  86. <span style="white-space:pre">     </span>$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
  87. <span style="white-space:pre"> </span>}
  88. <span style="white-space:pre"> </span>elseif (isset($_SERVER['HTTP_HOST']))
  89. <span style="white-space:pre"> </span>{
  90. <span style="white-space:pre">     </span>$host = $_SERVER['HTTP_HOST'];
  91. <span style="white-space:pre"> </span>}
  92. <span style="white-space:pre"> </span>else
  93. <span style="white-space:pre"> </span>{
  94. <span style="white-space:pre">     </span>/* 端口 */
  95. <span style="white-space:pre">     </span>if (isset($_SERVER['SERVER_PORT']))
  96. <span style="white-space:pre">     </span>{
  97. <span style="white-space:pre">         </span>$port = ':' . $_SERVER['SERVER_PORT'];
  98. <span style="white-space:pre">         </span>if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol))
  99. <span style="white-space:pre">         </span>{
  100. <span style="white-space:pre">             </span>$port = '';
  101. <span style="white-space:pre">         </span>}
  102. <span style="white-space:pre">     </span>}
  103. <span style="white-space:pre">     </span>else
  104. <span style="white-space:pre">     </span>{
  105. <span style="white-space:pre">         </span>$port = '';
  106. <span style="white-space:pre">     </span>}
  107. <span style="white-space:pre">     </span>if (isset($_SERVER['SERVER_NAME']))
  108. <span style="white-space:pre">     </span>{
  109. <span style="white-space:pre">         </span>$host = $_SERVER['SERVER_NAME'] . $port;
  110. <span style="white-space:pre">     </span>}
  111. <span style="white-space:pre">     </span>elseif (isset($_SERVER['SERVER_ADDR']))
  112. <span style="white-space:pre">     </span>{
  113. <span style="white-space:pre">         </span>$host = $_SERVER['SERVER_ADDR'] . $port;
  114. <span style="white-space:pre">     </span>}
  115. <span style="white-space:pre"> </span>}
  116. <span style="white-space:pre"> </span>return $protocol . $host;
  117. }
  118. function get_host()
  119. {
  120. <span style="white-space:pre"> </span>/* 域名或IP地址 */
  121. <span style="white-space:pre"> </span>if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
  122. <span style="white-space:pre"> </span>{
  123. <span style="white-space:pre">     </span>$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
  124. <span style="white-space:pre"> </span>}
  125. <span style="white-space:pre"> </span>elseif (isset($_SERVER['HTTP_HOST']))
  126. <span style="white-space:pre"> </span>{
  127. <span style="white-space:pre">     </span>$host = $_SERVER['HTTP_HOST'];
  128. <span style="white-space:pre"> </span>}
  129. <span style="white-space:pre"> </span>else
  130. <span style="white-space:pre"> </span>{
  131. <span style="white-space:pre">     </span>if (isset($_SERVER['SERVER_NAME']))
  132. <span style="white-space:pre">     </span>{
  133. <span style="white-space:pre">         </span>$host = $_SERVER['SERVER_NAME'];
  134. <span style="white-space:pre">     </span>}
  135. <span style="white-space:pre">     </span>elseif (isset($_SERVER['SERVER_ADDR']))
  136. <span style="white-space:pre">     </span>{
  137. <span style="white-space:pre">         </span>$host = $_SERVER['SERVER_ADDR'];
  138. <span style="white-space:pre">     </span>}
  139. <span style="white-space:pre"> </span>}
  140. <span style="white-space:pre"> </span>return $host;
  141. }
  142. /*
  143. * 实现AES加密
  144. * $str : 要加密的字符串
  145. * $keys : 加密密钥
  146. * $iv : 加密向量
  147. * $cipher_alg : 加密方式
  148. */
  149. function aes_ecryptdString($str,$keys="1034567890666450",$iv="1034567890123450",$cipher_alg=MCRYPT_RIJNDAEL_128){
  150. // <span style="white-space:pre">   </span>$encrypted_string= base64_encode(bin2hex(mcrypt_encrypt($cipher_alg,$keys, $str, MCRYPT_MODE_CBC,$iv)));
  151. <span style="white-space:pre">  </span>$encrypted_string= bin2hex(mcrypt_encrypt($cipher_alg,$keys, $str, MCRYPT_MODE_CBC,$iv));
  152. <span style="white-space:pre">  </span>return $encrypted_string;
  153. }
  154. /*
  155. * 实现AES解密
  156. * $str : 要解密的字符串
  157. * $keys : 加密密钥
  158. * $iv : 加密向量
  159. * $cipher_alg : 加密方式
  160. */
  161. function aes_decryptString($str,$keys="1034567890666450",$iv="1034567890123450",$cipher_alg=MCRYPT_RIJNDAEL_128){
  162. // <span style="white-space:pre">   </span>$str= base64_decode($str);
  163. <span style="white-space:pre">  </span>$decrypted_string= mcrypt_decrypt($cipher_alg,$keys,pack("H*",$str),MCRYPT_MODE_CBC,$iv);
  164. <span style="white-space:pre">  </span>return $decrypted_string;
  165. }
  166. /**
  167. * 对数组进行转码操作
  168. * @param $array
  169. * @param $in_charset
  170. * @param $out_charset
  171. */
  172. function iconv_array(&$array,$in_charset,$out_charset)
  173. {
  174. <span style="white-space:pre">  </span>if(UC_CHARSET!='utf-8')
  175. <span style="white-space:pre">  </span>{
  176. <span style="white-space:pre">      </span>foreach($array as $k=>$v)
  177. <span style="white-space:pre">      </span>{
  178. <span style="white-space:pre">          </span>if(is_array($array[$k]))
  179. <span style="white-space:pre">          </span>{
  180. <span style="white-space:pre">              </span>iconv_array($array[$k],$in_charset,$out_charset);
  181. <span style="white-space:pre">          </span>}
  182. <span style="white-space:pre">          </span>else
  183. <span style="white-space:pre">          </span>{
  184. <span style="white-space:pre">              </span>$array[$k] = iconv($in_charset,$out_charset,$array[$k]);
  185. <span style="white-space:pre">          </span>}
  186. <span style="white-space:pre">      </span>}
  187. <span style="white-space:pre">  </span>}
  188. }
  189. /**
  190. * utf8字符转Unicode字符
  191. * @param string $char 要转换的单字符
  192. * @return void
  193. */
  194. function utf8_to_unicode($char)
  195. {
  196. <span style="white-space:pre">  </span>switch(strlen($char))
  197. <span style="white-space:pre">  </span>{
  198. <span style="white-space:pre">      </span>case 1:
  199. <span style="white-space:pre">          </span>return ord($char);
  200. <span style="white-space:pre">      </span>case 2:
  201. <span style="white-space:pre">          </span>$n = (ord($char[0]) & 0x3f) << 6;
  202. <span style="white-space:pre">          </span>$n += ord($char[1]) & 0x3f;
  203. <span style="white-space:pre">          </span>return $n;
  204. <span style="white-space:pre">      </span>case 3:
  205. <span style="white-space:pre">          </span>$n = (ord($char[0]) & 0x1f) << 12;
  206. <span style="white-space:pre">          </span>$n += (ord($char[1]) & 0x3f) << 6;
  207. <span style="white-space:pre">          </span>$n += ord($char[2]) & 0x3f;
  208. <span style="white-space:pre">          </span>return $n;
  209. <span style="white-space:pre">      </span>case 4:
  210. <span style="white-space:pre">          </span>$n = (ord($char[0]) & 0x0f) << 18;
  211. <span style="white-space:pre">          </span>$n += (ord($char[1]) & 0x3f) << 12;
  212. <span style="white-space:pre">          </span>$n += (ord($char[2]) & 0x3f) << 6;
  213. <span style="white-space:pre">          </span>$n += ord($char[3]) & 0x3f;
  214. <span style="white-space:pre">          </span>return $n;
  215. <span style="white-space:pre">  </span>}
  216. }
  217. /**
  218. * utf8字符串分隔为unicode字符串
  219. * @param string $str 要转换的字符串
  220. * @param string $depart 分隔,默认为空格为单字
  221. * @return string
  222. */
  223. function str_to_unicode_word($str,$depart=' ')
  224. {
  225. <span style="white-space:pre">  </span>$arr = array();
  226. <span style="white-space:pre">  </span>$str_len = mb_strlen($str,'utf-8');
  227. <span style="white-space:pre">  </span>for($i = 0;$i < $str_len;$i++)
  228. <span style="white-space:pre">  </span>{
  229. <span style="white-space:pre">      </span>$s = mb_substr($str,$i,1,'utf-8');
  230. <span style="white-space:pre">      </span>if($s != ' ' && $s != ' ')
  231. <span style="white-space:pre">          </span>{
  232. <span style="white-space:pre">          </span>$arr[] = 'ux'.utf8_to_unicode($s);
  233. <span style="white-space:pre">      </span>}
  234. <span style="white-space:pre">  </span>}
  235. return implode($depart,$arr);
  236. }
  237. /**
  238. * utf8字符串分隔为unicode字符串
  239. * @param string $str 要转换的字符串
  240. * @return string
  241. */
  242. function str_to_unicode_string($str)
  243. {
  244. <span style="white-space:pre">  </span>$string = str_to_unicode_word($str,'');
  245. <span style="white-space:pre">  </span>return $string;
  246. }
  247. //分词
  248. function div_str($str)
  249. {
  250. <span style="white-space:pre">  </span>require_once APP_ROOT_PATH."core/lib/words.php";
  251. <span style="white-space:pre">  </span>$words = words::segment($str);
  252. <span style="white-space:pre">  </span>$words[] = $str;
  253. <span style="white-space:pre">  </span>return $words;
  254. }
  255. /**
  256. * @desc  im:十进制数转换成三十六机制数
  257. * @param (int)$num 十进制数
  258. * return 返回:三十六进制数
  259. */
  260. function get_code_bynum($num) {
  261. <span style="white-space:pre">  </span>$num = intval($num);
  262. <span style="white-space:pre">  </span>if ($num <= 0)
  263. <span style="white-space:pre">      </span>return false;
  264. <span style="white-space:pre">  </span>$codeArr = array("0","1","2","3","4","5","6","7","8","9",'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
  265. <span style="white-space:pre">  </span>$code = '';
  266. <span style="white-space:pre">  </span>do {
  267. <span style="white-space:pre">      </span>$key = ($num - 1) % 36;
  268. <span style="white-space:pre">      </span>$code = $codeArr[$key] . $code;
  269. <span style="white-space:pre">      </span>$num = floor(($num - $key) / 36);
  270. <span style="white-space:pre">  </span>} while ($num > 0);
  271. <span style="white-space:pre">  </span>return $code;
  272. }
  273. /**
  274. * @desc  im:三十六进制数转换成十机制数
  275. * @param (string)$str 三十六进制数
  276. * return 返回:十进制数
  277. */
  278. function get_num_bycode($str){
  279. <span style="white-space:pre">  </span>$array=array("0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D","E", "F", "G", "H", "I", "J", "K", "L","M", "N", "O","P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y","Z");
  280. <span style="white-space:pre">  </span>$len=strlen($str);
  281. <span style="white-space:pre">  </span>for($i=0;$i<$len;$i++){
  282. <span style="white-space:pre">      </span>$index=array_search($str[$i],$array);
  283. <span style="white-space:pre">      </span>$sum+=($index+1)*pow(36,$len-$i-1);
  284. <span style="white-space:pre">  </span>}
  285. <span style="white-space:pre">  </span>return $sum;
  286. }
  287. ?>

5.加载公共方法的文件./core/common.php
源码:

  1. <?php
  2. function app_conf($name)
  3. {
  4. return  $GLOBALS['db']->getOne("select value from ".DB_PREFIX."conf where name='".$name."'");
  5. }
  6. /*
  7. * @des:im:验证手机号码
  8. * @param:$phone
  9. */
  10. function check_phone($phone)
  11. {
  12. if(!empty($phone) && !preg_match("/^1\d{10}$/",$phone))
  13. {
  14. return false;
  15. }
  16. else
  17. return true;
  18. }
  19. /**
  20. * @desc  get_pwd_strength()im:根据密码字符串判断密码结构
  21. * @param (string)$mobile
  22. * return 返回:$msg
  23. */
  24. function get_pwd_strength($pwd){
  25. if (strlen(iconv('UTF-8','GBK',$pwd))>30 || strlen(iconv('UTF-8','GBK',$pwd))<6)
  26. {
  27. return '密码是6-30位的字符串,且必须由字母和数字组成.';
  28. }
  29. if(preg_match("/^\d+$/",$pwd))
  30. {
  31. return '密码不能为全数字';//全数字
  32. }
  33. if(preg_match("/^[a-z]+$/i",$pwd))
  34. {
  35. return '密码不能为全字母';//全字母
  36. }
  37. if(!preg_match("/^[A-Za-z0-9]+$/",$pwd))
  38. {
  39. return '密码只能包含字母和数字';//有数字有字母   ";
  40. }
  41. return null;
  42. }
  43. /*ajax返回*/
  44. function ajax_return($data)
  45. {
  46. header("Content-Type:text/html; charset=utf-8");
  47. echo(json_encode($data));
  48. //  echo(base64_encode(json_encode($data)));
  49. if (APP_LOG) {
  50. $GLOBALS['log']->quit($data);
  51. }
  52. exit;
  53. }
  54. /**
  55. * 字符串加密函数
  56. * @param string $txt
  57. * @param string $key
  58. * @return string
  59. */
  60. function passport_encrypt($txt, $key = 'IMEMBER_2013') {
  61. srand((double)microtime() * 1000000);
  62. $encrypt_key = md5(rand(0, 32000));
  63. $ctr = 0;
  64. $tmp = '';
  65. for($i = 0;$i < strlen($txt); $i++) {
  66. $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
  67. $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
  68. }
  69. return base64_encode(passport_key($tmp, $key));
  70. }
  71. /**
  72. * 字符串解密函数
  73. * @param string $txt
  74. * @param string $key
  75. * @return string
  76. */
  77. function passport_decrypt($txt, $key = 'IMEMBER_2013') {
  78. $txt = passport_key(base64_decode($txt), $key);
  79. $tmp = '';
  80. for($i = 0;$i < strlen($txt); $i++) {
  81. if (empty($txt[$i+1])) {
  82. return false;
  83. }
  84. $md5 = $txt[$i];
  85. $tmp .= $txt[++$i] ^ $md5;
  86. }
  87. return $tmp;
  88. }
  89. function passport_key($txt, $encrypt_key) {
  90. $encrypt_key = md5($encrypt_key);
  91. $ctr = 0;
  92. $tmp = '';
  93. for($i = 0; $i < strlen($txt); $i++) {
  94. $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
  95. $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
  96. }
  97. return $tmp;
  98. }
  99. /**
  100. * 传入图片的地址,自动修复图片的相对路径(如 ./public/logo.png)到绝对路径(如http://www.imember.cc/public/logo.png)
  101. * @param unknown $img_path
  102. */
  103. function imagePathRevise($img_path){
  104. //判断$img_path的路径是否以http://开头
  105. if (preg_match('/^http:\/\//', $img_path)) {
  106. return $img_path;
  107. }else{
  108. return IMG_PATH.preg_replace('/^\.\//', '', $img_path);
  109. }
  110. }
  111. //utf8 字符串截取
  112. function msubstr($str, $start=0, $length=15, $charset="utf-8", $suffix=true)
  113. {
  114. if(function_exists("mb_substr"))
  115. {
  116. $slice =  mb_substr($str, $start, $length, $charset);
  117. if($suffix&$slice!=$str) return $slice."…";
  118. return $slice;
  119. }
  120. elseif(function_exists('iconv_substr')) {
  121. return iconv_substr($str,$start,$length,$charset);
  122. }
  123. $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  124. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  125. $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  126. $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  127. preg_match_all($re[$charset], $str, $match);
  128. $slice = join("",array_slice($match[0], $start, $length));
  129. if($suffix&&$slice!=$str) return $slice."…";
  130. return $slice;
  131. }
  132. }
  133. ?>

6.加载./initializer.php,initializer()用于将所有公用的文件目录在此函数里声明

initializer::initialize();
这就话就是调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.
定义了一个静态函数,initialize函数,这个函数就是设置include_path,这样,以后如果包含文件,或者__autoload,就会去这些目录下查找。
  1. <?php
  2. class initializer
  3. {
  4. public static function initialize() {
  5. set_include_path(get_include_path().PATH_SEPARATOR . "core/main");
  6. set_include_path(get_include_path().PATH_SEPARATOR . "core/main/cache");
  7. set_include_path(get_include_path().PATH_SEPARATOR . "core/helpers");
  8. set_include_path(get_include_path().PATH_SEPARATOR . "core/libraries");
  9. set_include_path(get_include_path().PATH_SEPARATOR . "core/config");
  10. set_include_path(get_include_path().PATH_SEPARATOR . "app/controllers");
  11. set_include_path(get_include_path().PATH_SEPARATOR."app/models");
  12. set_include_path(get_include_path().PATH_SEPARATOR."app/views");
  13. }
  14. }
  15. ?>

7.加载./loader.php文件,源码:

  1. <?php
  2. class loader
  3. {
  4. private static $loaded = array();
  5. public static function load($object){
  6. $valid = array(
  7. "library",
  8. "view",
  9. "model",
  10. "helper",
  11. "router",
  12. "config",
  13. "hook",
  14. "cache",
  15. "db");
  16. if (!in_array($object,$valid)){
  17. //          throw new Exception("Not a valid object '{$object}' to load");
  18. ajax_return(array('recode'=>"0003",'msg'=>"非法操作","data"=>"Not a valid object '{$object}' to load"));
  19. }
  20. if (empty(self::$loaded[$object])){
  21. self::$loaded[$object]= new $object();
  22. }
  23. return self::$loaded[$object];
  24. }
  25. }
  26. ?>

8.加载控制层文件./router.php,源码:

  1. <?php
  2. class router
  3. {
  4. private $route;
  5. private $controller;
  6. private $action;
  7. private $params;
  8. public function __construct()
  9. {
  10. //base64_decode(str)解码
  11. $routeParts=$_GET;
  12. //      $routeParts=base64_decode($_GET);
  13. if (!isset($routeParts['c'])){
  14. ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>"Controller is null"));
  15. }
  16. $this->route = $routeParts['c'];
  17. $this->controller=$routeParts['c'];
  18. $this->action=isset($routeParts['act'])? $routeParts['act']:"index";
  19. array_shift($routeParts);
  20. array_shift($routeParts);
  21. $this->params=$routeParts;
  22. }
  23. public function getAction() {
  24. if (empty($this->action)) $this->action="index";
  25. return $this->action;
  26. }
  27. public function getController()  {
  28. return $this->controller;
  29. }
  30. public function getParams()  {
  31. return $this->params;
  32. }
  33. }
  34. ?>

9.加载数据库连接文件./core/conn.php,源码:

  1. <?php
  2. /*
  3. * 数据库连接
  4. */
  5. //第一种方法:直接写入数据库连接参数
  6. //    $dblink=mysql_connect("127.0.0.1:3306","sara","abc123");
  7. //    mysql_select_db("ipolarbear",$dblink);
  8. //    mysql_query("SET NAMES UTF8");
  9. //    if (!$dblink) {
  10. //          mysql_query("SET NAMES UTF8");
  11. //          die (json_encode(array('recode'=>"0009",'msg'=>"连接数据库失败" . mysql_error (),'data'=>'')));
  12. //    }
  13. //第二种方法:定义DB类,加载数据库配置,对数据库SQL进行封装
  14. //加载数据库配置
  15. $dbcfg = require APP_ROOT_PATH."core/config/db_config.php";
  16. if(!defined('DB_PREFIX'))//im:数据库表前缀
  17. define('DB_PREFIX', $dbcfg['DB_PREFIX']);
  18. if(!file_exists(APP_ROOT_PATH.'core/runtime/db_caches/'))
  19. mkdir(APP_ROOT_PATH.'core/runtime/db_caches/',0777);
  20. $pconnect = false;
  21. $GLOBALS['db'] = new mysql_db($dbcfg['DB_HOST'].":".$dbcfg['DB_PORT'], $dbcfg['DB_USER'],$dbcfg['DB_PWD'],$dbcfg['DB_NAME'],'utf8',$pconnect);
  22. mysql_query("SET NAMES UTF8");//相当于character_set_client(),character_set_connection(),character_set_results()客户端 连接器 返回值三者同时设置编码方式
  23. //检查PHP是否连接上MYSQL
  24. if(mysqli_connect_errno()){
  25. die (json_encode(array('recode'=>"0009",'msg'=>"连接数据库失败:" . mysql_error (),'data'=>'')));
  26. }
  27. //end 定义DB
  28. ?>

10.加载数据库配置文件./core/db_config.php,源码:

  1. <?php
  2. return array(
  3. 'DB_HOST'=>'localhost',
  4. 'DB_NAME'=>'ip',
  5. 'DB_USER'=>'sara',
  6. 'DB_PWD'=>'abc123',
  7. 'DB_PORT'=>'3306',
  8. 'DB_PREFIX'=>'base_',
  9. );
  10. ?>

11.加载数据库类文件./core/mysql_db.php,源码:

  1. <?php
  2. class mysql_db
  3. {
  4. var $link_id    = NULL;
  5. var $settings   = array();
  6. var $queryCount = 0;
  7. var $queryTime  = '';
  8. var $queryLog   = array();
  9. var $max_cache_time = 60; // 最大的缓存时间,以秒为单位
  10. var $cache_data_dir = 'core/runtime/db_caches/';
  11. var $root_path      = '';
  12. var $error_message  = array();
  13. var $platform       = '';
  14. var $version        = '';
  15. var $dbhash         = '';
  16. var $starttime      = 0;
  17. var $timeline       = 0;
  18. var $timezone       = 0;
  19. var $mysql_config_cache_file_time = 0;
  20. var $mysql_disable_cache_tables = array(); // 不允许被缓存的表,遇到将不会进行缓存
  21. function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
  22. {
  23. $this->mysql_db($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);
  24. }
  25. function mysql_db($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
  26. {
  27. if (defined('APP_ROOT_PATH') && !$this->root_path)
  28. {
  29. $this->root_path = APP_ROOT_PATH;
  30. }
  31. if ($quiet)
  32. {
  33. $this->connect($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);
  34. }
  35. else
  36. {
  37. $this->settings = array(
  38. 'dbhost'   => $dbhost,
  39. 'dbuser'   => $dbuser,
  40. 'dbpw'     => $dbpw,
  41. 'dbname'   => $dbname,
  42. 'charset'  => $charset,
  43. 'pconnect' => $pconnect
  44. );
  45. }
  46. }
  47. function connect($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
  48. {
  49. if ($pconnect)
  50. {
  51. if (!($this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw)))
  52. {
  53. if (!$quiet)
  54. {
  55. $this->ErrorMsg("Can't pConnect MySQL Server($dbhost)!");
  56. }
  57. return false;
  58. }
  59. }
  60. else
  61. {
  62. if (PHP_VERSION >= '4.2')
  63. {
  64. $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
  65. }
  66. else
  67. {
  68. $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw);
  69. mt_srand((double)microtime() * 1000000); // 对 PHP 4.2 以下的版本进行随机数函数的初始化工作
  70. }
  71. if (!$this->link_id)
  72. {
  73. if (!$quiet)
  74. {
  75. $this->ErrorMsg("Can't Connect MySQL Server($dbhost)!");
  76. }
  77. return false;
  78. }
  79. }
  80. $this->dbhash  = md5($this->root_path . $dbhost . $dbuser . $dbpw . $dbname);
  81. $this->version = mysql_get_server_info($this->link_id);
  82. /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */
  83. if ($this->version > '4.1')
  84. {
  85. if ($charset != 'latin1')
  86. {
  87. mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id);
  88. }
  89. if ($this->version > '5.0.1')
  90. {
  91. mysql_query("SET sql_mode=''", $this->link_id);
  92. }
  93. }
  94. $sqlcache_config_file = $this->root_path . $this->cache_data_dir . 'sqlcache_config_file_' . $this->dbhash . '.php';
  95. @include($sqlcache_config_file);
  96. $this->starttime = time();
  97. if ($this->max_cache_time && $this->starttime > $this->mysql_config_cache_file_time + $this->max_cache_time)
  98. {
  99. if ($dbhost != '.')
  100. {
  101. $result = mysql_query("SHOW VARIABLES LIKE 'basedir'", $this->link_id);
  102. $row    = mysql_fetch_assoc($result);
  103. if (!empty($row['Value']{
  104. 1}) && $row['Value']{
  105. 1} == ':' && !empty($row['Value']{
  106. 2}) && $row['Value']{
  107. 2} == "\\")
  108. {
  109. $this->platform = 'WINDOWS';
  110. }
  111. else
  112. {
  113. $this->platform = 'OTHER';
  114. }
  115. }
  116. else
  117. {
  118. $this->platform = 'WINDOWS';
  119. }
  120. if ($this->platform == 'OTHER' &&
  121. ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306') ||
  122. (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC'))
  123. {
  124. $result = mysql_query("SELECT UNIX_TIMESTAMP() AS timeline, UNIX_TIMESTAMP('" . date('Y-m-d H:i:s', $this->starttime) . "') AS timezone", $this->link_id);
  125. $row    = mysql_fetch_assoc($result);
  126. if ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306')
  127. {
  128. $this->timeline = $this->starttime - $row['timeline'];
  129. }
  130. if (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC')
  131. {
  132. $this->timezone = $this->starttime - $row['timezone'];
  133. }
  134. }
  135. $content = '<' . "?php\r\n" .
  136. '$this->mysql_config_cache_file_time = ' . $this->starttime . ";\r\n" .
  137. '$this->timeline = ' . $this->timeline . ";\r\n" .
  138. '$this->timezone = ' . $this->timezone . ";\r\n" .
  139. '$this->platform = ' . "'" . $this->platform . "';\r\n?" . '>';
  140. @file_put_contents($sqlcache_config_file, $content);
  141. }
  142. /* 选择数据库 */
  143. if ($dbname)
  144. {
  145. if (mysql_select_db($dbname, $this->link_id) === false )
  146. {
  147. if (!$quiet)
  148. {
  149. $this->ErrorMsg("Can't select MySQL database($dbname)!");
  150. }
  151. return false;
  152. }
  153. else
  154. {
  155. return true;
  156. }
  157. }
  158. else
  159. {
  160. return true;
  161. }
  162. }
  163. function select_database($dbname)
  164. {
  165. return mysql_select_db($dbname, $this->link_id);
  166. }
  167. function set_mysql_charset($charset)
  168. {
  169. /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */
  170. if ($this->version > '4.1')
  171. {
  172. if (in_array(strtolower($charset), array('gbk', 'big5', 'utf-8', 'utf8')))
  173. {
  174. $charset = str_replace('-', '', $charset);
  175. }
  176. if ($charset != 'latin1')
  177. {
  178. mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id);
  179. }
  180. }
  181. }
  182. function fetch_array($query, $result_type = MYSQL_ASSOC)
  183. {
  184. return mysql_fetch_array($query, $result_type);
  185. }
  186. function query($sql, $type = '')
  187. {
  188. if ($this->link_id === NULL)
  189. {
  190. $this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'], $this->settings['dbname'], $this->settings['charset'], $this->settings['pconnect']);
  191. $this->settings = array();
  192. }
  193. if ($this->queryCount++ <= 99)
  194. {
  195. $this->queryLog[] = $sql;
  196. }
  197. if ($this->queryTime == '')
  198. {
  199. if (PHP_VERSION >= '5.0.0')
  200. {
  201. $this->queryTime = microtime(true);
  202. }
  203. else
  204. {
  205. $this->queryTime = microtime();
  206. }
  207. }
  208. /* 当当前的时间大于类初始化时间的时候,自动执行 ping 这个自动重新连接操作 */
  209. if (PHP_VERSION >= '4.3' && time() > $this->starttime + 1)
  210. {
  211. mysql_ping($this->link_id);
  212. }
  213. if (!($query = mysql_query($sql, $this->link_id)) && $type != 'SILENT')
  214. {
  215. $this->error_message[]['message'] = 'MySQL Query Error';
  216. $this->error_message[]['sql'] = $sql;
  217. $this->error_message[]['error'] = mysql_error($this->link_id);
  218. $this->error_message[]['errno'] = mysql_errno($this->link_id);
  219. $this->ErrorMsg();
  220. return false;
  221. }
  222. if (defined('DEBUG_MODE') && (DEBUG_MODE & 8) == 8)
  223. {
  224. $logfilename = $this->root_path . DATA_DIR . '/mysql_query_' . $this->dbhash . '_' . date('Y_m_d') . '.log';
  225. $str = $sql . "\n\n";
  226. if (PHP_VERSION >= '5.0')
  227. {
  228. file_put_contents($logfilename, $str, FILE_APPEND);
  229. }
  230. else
  231. {
  232. $fp = @fopen($logfilename, 'ab+');
  233. if ($fp)
  234. {
  235. fwrite($fp, $str);
  236. fclose($fp);
  237. }
  238. }
  239. }
  240. //echo $sql."<br/><br/>======================================<br/><br/>";
  241. return $query;
  242. }
  243. function affected_rows()
  244. {
  245. return mysql_affected_rows($this->link_id);
  246. }
  247. function error()
  248. {
  249. return mysql_error($this->link_id);
  250. }
  251. function errno()
  252. {
  253. return mysql_errno($this->link_id);
  254. }
  255. function result($query, $row)
  256. {
  257. return @mysql_result($query, $row);
  258. }
  259. function num_rows($query)
  260. {
  261. return mysql_num_rows($query);
  262. }
  263. function num_fields($query)
  264. {
  265. return mysql_num_fields($query);
  266. }
  267. function free_result($query)
  268. {
  269. return mysql_free_result($query);
  270. }
  271. function insert_id()
  272. {
  273. return mysql_insert_id($this->link_id);
  274. }
  275. function fetchRow($query)
  276. {
  277. return mysql_fetch_assoc($query);
  278. }
  279. function fetch_fields($query)
  280. {
  281. return mysql_fetch_field($query);
  282. }
  283. function version()
  284. {
  285. return $this->version;
  286. }
  287. function ping()
  288. {
  289. if (PHP_VERSION >= '4.3')
  290. {
  291. return mysql_ping($this->link_id);
  292. }
  293. else
  294. {
  295. return false;
  296. }
  297. }
  298. function escape_string($unescaped_string)
  299. {
  300. if (PHP_VERSION >= '4.3')
  301. {
  302. return mysql_real_escape_string($unescaped_string);
  303. }
  304. else
  305. {
  306. return mysql_escape_string($unescaped_string);
  307. }
  308. }
  309. function close()
  310. {
  311. return mysql_close($this->link_id);
  312. }
  313. function ErrorMsg($message = '', $sql = '')
  314. {
  315. if ($message)
  316. {
  317. ajax_return(array('recode'=>"0009",'msg'=>"MySQL server error info:".$message,'data'=>''));
  318. }
  319. else
  320. {
  321. ajax_return(array('recode'=>"0010",'msg'=>"MySQL server error report:".$this->error_message,'data'=>''));
  322. }
  323. }
  324. /* 仿真 Adodb 函数 */
  325. function selectLimit($sql, $num, $start = 0)
  326. {
  327. if ($start == 0)
  328. {
  329. $sql .= ' LIMIT ' . $num;
  330. }
  331. else
  332. {
  333. $sql .= ' LIMIT ' . $start . ', ' . $num;
  334. }
  335. return $this->query($sql);
  336. }
  337. function getOne($sql, $limited = false)
  338. {
  339. if ($limited == true)
  340. {
  341. $sql = trim($sql . ' LIMIT 1');
  342. }
  343. $res = $this->query($sql);
  344. if ($res !== false)
  345. {
  346. $row = mysql_fetch_row($res);
  347. if ($row !== false)
  348. {
  349. return $row[0];
  350. }
  351. else
  352. {
  353. return '';
  354. }
  355. }
  356. else
  357. {
  358. return false;
  359. }
  360. }
  361. function getOneCached($sql, $cached = 'FILEFIRST')
  362. {
  363. $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;
  364. if (!$cachefirst)
  365. {
  366. return $this->getOne($sql, true);
  367. }
  368. else
  369. {
  370. $result = $this->getSqlCacheData($sql, $cached);
  371. if (empty($result['storecache']) == true)
  372. {
  373. return $result['data'];
  374. }
  375. }
  376. $arr = $this->getOne($sql, true);
  377. if ($arr !== false && $cachefirst)
  378. {
  379. $this->setSqlCacheData($result, $arr);
  380. }
  381. return $arr;
  382. }
  383. function getAll($sql)
  384. {
  385. $res = $this->query($sql);
  386. if ($res !== false)
  387. {
  388. $arr = array();
  389. while ($row = mysql_fetch_assoc($res))
  390. {
  391. $arr[] = $row;
  392. }
  393. return $arr;
  394. }
  395. else
  396. {
  397. return false;
  398. }
  399. }
  400. function getAllCached($sql, $cached = 'FILEFIRST')
  401. {
  402. $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;
  403. if (!$cachefirst)
  404. {
  405. return $this->getAll($sql);
  406. }
  407. else
  408. {
  409. $result = $this->getSqlCacheData($sql, $cached);
  410. if (empty($result['storecache']) == true)
  411. {
  412. return $result['data'];
  413. }
  414. }
  415. $arr = $this->getAll($sql);
  416. if ($arr !== false && $cachefirst)
  417. {
  418. $this->setSqlCacheData($result, $arr);
  419. }
  420. return $arr;
  421. }
  422. function getRow($sql, $limited = false)
  423. {
  424. if ($limited == true)
  425. {
  426. $sql = trim($sql . ' LIMIT 1');
  427. }
  428. $res = $this->query($sql);
  429. if ($res !== false)
  430. {
  431. return mysql_fetch_assoc($res);
  432. }
  433. else
  434. {
  435. return false;
  436. }
  437. }
  438. function getRowCached($sql, $cached = 'FILEFIRST')
  439. {
  440. $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;
  441. if (!$cachefirst)
  442. {
  443. return $this->getRow($sql, true);
  444. }
  445. else
  446. {
  447. $result = $this->getSqlCacheData($sql, $cached);
  448. if (empty($result['storecache']) == true)
  449. {
  450. return $result['data'];
  451. }
  452. }
  453. $arr = $this->getRow($sql, true);
  454. if ($arr !== false && $cachefirst)
  455. {
  456. $this->setSqlCacheData($result, $arr);
  457. }
  458. return $arr;
  459. }
  460. function getCol($sql)
  461. {
  462. $res = $this->query($sql);
  463. if ($res !== false)
  464. {
  465. $arr = array();
  466. while ($row = mysql_fetch_row($res))
  467. {
  468. $arr[] = $row[0];
  469. }
  470. return $arr;
  471. }
  472. else
  473. {
  474. return false;
  475. }
  476. }
  477. function getColCached($sql, $cached = 'FILEFIRST')
  478. {
  479. $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;
  480. if (!$cachefirst)
  481. {
  482. return $this->getCol($sql);
  483. }
  484. else
  485. {
  486. $result = $this->getSqlCacheData($sql, $cached);
  487. if (empty($result['storecache']) == true)
  488. {
  489. return $result['data'];
  490. }
  491. }
  492. $arr = $this->getCol($sql);
  493. if ($arr !== false && $cachefirst)
  494. {
  495. $this->setSqlCacheData($result, $arr);
  496. }
  497. return $arr;
  498. }
  499. function autoExecute($table, $field_values, $mode = 'INSERT', $where = '', $querymode = '')
  500. {
  501. $field_names = $this->getCol('DESC ' . $table);
  502. $sql = '';
  503. if ($mode == 'INSERT')
  504. {
  505. $fields = $values = array();
  506. foreach ($field_names AS $value)
  507. {
  508. if (@array_key_exists($value, $field_values) == true)
  509. {
  510. $fields[] = $value;
  511. $field_values[$value] = stripslashes($field_values[$value]);
  512. $values[] = "'" . addslashes($field_values[$value]) . "'";
  513. }
  514. }
  515. if (!empty($fields))
  516. {
  517. $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
  518. }
  519. }
  520. else
  521. {
  522. $sets = array();
  523. foreach ($field_names AS $value)
  524. {
  525. if (array_key_exists($value, $field_values) == true)
  526. {
  527. $field_values[$value] = stripslashes($field_values[$value]);
  528. $sets[] = $value . " = '" . addslashes($field_values[$value]) . "'";
  529. }
  530. }
  531. if (!empty($sets))
  532. {
  533. $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
  534. }
  535. }
  536. if ($sql)
  537. {
  538. return $this->query($sql, $querymode);
  539. }
  540. else
  541. {
  542. return false;
  543. }
  544. }
  545. function autoReplace($table, $field_values, $update_values, $where = '', $querymode = '')
  546. {
  547. $field_descs = $this->getAll('DESC ' . $table);
  548. $primary_keys = array();
  549. foreach ($field_descs AS $value)
  550. {
  551. $field_names[] = $value['Field'];
  552. if ($value['Key'] == 'PRI')
  553. {
  554. $primary_keys[] = $value['Field'];
  555. }
  556. }
  557. $fields = $values = array();
  558. foreach ($field_names AS $value)
  559. {
  560. if (array_key_exists($value, $field_values) == true)
  561. {
  562. $fields[] = $value;
  563. $values[] = "'" . $field_values[$value] . "'";
  564. }
  565. }
  566. $sets = array();
  567. foreach ($update_values AS $key => $value)
  568. {
  569. if (array_key_exists($key, $field_values) == true)
  570. {
  571. if (is_int($value) || is_float($value))
  572. {
  573. $sets[] = $key . ' = ' . $key . ' + ' . $value;
  574. }
  575. else
  576. {
  577. $sets[] = $key . " = '" . $value . "'";
  578. }
  579. }
  580. }
  581. $sql = '';
  582. if (empty($primary_keys))
  583. {
  584. if (!empty($fields))
  585. {
  586. $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
  587. }
  588. }
  589. else
  590. {
  591. if ($this->version() >= '4.1')
  592. {
  593. if (!empty($fields))
  594. {
  595. $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
  596. if (!empty($sets))
  597. {
  598. $sql .=  'ON DUPLICATE KEY UPDATE ' . implode(', ', $sets);
  599. }
  600. }
  601. }
  602. else
  603. {
  604. if (empty($where))
  605. {
  606. $where = array();
  607. foreach ($primary_keys AS $value)
  608. {
  609. if (is_numeric($value))
  610. {
  611. $where[] = $value . ' = ' . $field_values[$value];
  612. }
  613. else
  614. {
  615. $where[] = $value . " = '" . $field_values[$value] . "'";
  616. }
  617. }
  618. $where = implode(' AND ', $where);
  619. }
  620. if ($where && (!empty($sets) || !empty($fields)))
  621. {
  622. if (intval($this->getOne("SELECT COUNT(*) FROM $table WHERE $where")) > 0)
  623. {
  624. if (!empty($sets))
  625. {
  626. $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
  627. }
  628. }
  629. else
  630. {
  631. if (!empty($fields))
  632. {
  633. $sql = 'REPLACE INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
  634. }
  635. }
  636. }
  637. }
  638. }
  639. if ($sql)
  640. {
  641. return $this->query($sql, $querymode);
  642. }
  643. else
  644. {
  645. return false;
  646. }
  647. }
  648. function setMaxCacheTime($second)
  649. {
  650. $this->max_cache_time = $second;
  651. }
  652. function getMaxCacheTime()
  653. {
  654. return $this->max_cache_time;
  655. }
  656. function getSqlCacheData($sql, $cached = '')
  657. {
  658. $sql = trim($sql);
  659. $result = array();
  660. $result['filename'] = $this->root_path . $this->cache_data_dir . 'sqlcache_' . abs(crc32($this->dbhash . $sql)) . '_' . md5($this->dbhash . $sql) . '.php';
  661. $result['data'] = $GLOBALS['cache']->get($result['filename']);
  662. if($result['data']===false)
  663. {
  664. $result['storecache'] = true;
  665. }
  666. else
  667. {
  668. $result['storecache'] = false;
  669. }
  670. return $result;
  671. }
  672. function setSqlCacheData($result, $data)
  673. {
  674. if ($result['storecache'] === true && $result['filename'])
  675. {
  676. $GLOBALS['cache']->set($result['filename'],$data,$this->max_cache_time);
  677. }
  678. }
  679. /* 获取 SQL 语句中最后更新的表的时间,有多个表的情况下,返回最新的表的时间 */
  680. function table_lastupdate($tables)
  681. {
  682. if ($this->link_id === NULL)
  683. {
  684. $this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'], $this->settings['dbname'], $this->settings['charset'], $this->settings['pconnect']);
  685. $this->settings = array();
  686. }
  687. $lastupdatetime = '0000-00-00 00:00:00';
  688. $tables = str_replace('`', '', $tables);
  689. $this->mysql_disable_cache_tables = str_replace('`', '', $this->mysql_disable_cache_tables);
  690. foreach ($tables AS $table)
  691. {
  692. if (in_array($table, $this->mysql_disable_cache_tables) == true)
  693. {
  694. $lastupdatetime = '2037-12-31 23:59:59';
  695. break;
  696. }
  697. if (strstr($table, '.') != NULL)
  698. {
  699. $tmp = explode('.', $table);
  700. $sql = 'SHOW TABLE STATUS FROM `' . trim($tmp[0]) . "` LIKE '" . trim($tmp[1]) . "'";
  701. }
  702. else
  703. {
  704. $sql = "SHOW TABLE STATUS LIKE '" . trim($table) . "'";
  705. }
  706. $result = mysql_query($sql, $this->link_id);
  707. $row = mysql_fetch_assoc($result);
  708. if ($row['Update_time'] > $lastupdatetime)
  709. {
  710. $lastupdatetime = $row['Update_time'];
  711. }
  712. }
  713. $lastupdatetime = strtotime($lastupdatetime) - $this->timezone + $this->timeline;
  714. return $lastupdatetime;
  715. }
  716. function get_table_name($query_item)
  717. {
  718. $query_item = trim($query_item);
  719. $table_names = array();
  720. /* 判断语句中是不是含有 JOIN */
  721. if (stristr($query_item, ' JOIN ') == '')
  722. {
  723. /* 解析一般的 SELECT FROM 语句 */
  724. if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?(?:\s*,\s*(?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?)*)/is', $query_item, $table_names))
  725. {
  726. $table_names = preg_replace('/((?:`?\w+`?\s*\.\s*)?`?\w+`?)[^,]*/', '\1', $table_names[1]);
  727. return preg_split('/\s*,\s*/', $table_names);
  728. }
  729. }
  730. else
  731. {
  732. /* 对含有 JOIN 的语句进行解析 */
  733. if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)(?:(?:\s*AS)?\s*`?\w+`?)?.*?JOIN.*$/is', $query_item, $table_names))
  734. {
  735. $other_table_names = array();
  736. preg_match_all('/JOIN\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)\s*/i', $query_item, $other_table_names);
  737. return array_merge(array($table_names[1]), $other_table_names[1]);
  738. }
  739. }
  740. return $table_names;
  741. }
  742. /* 设置不允许进行缓存的表 */
  743. function set_disable_cache_tables($tables)
  744. {
  745. if (!is_array($tables))
  746. {
  747. $tables = explode(',', $tables);
  748. }
  749. foreach ($tables AS $table)
  750. {
  751. $this->mysql_disable_cache_tables[] = $table;
  752. }
  753. array_unique($this->mysql_disable_cache_tables);
  754. }
  755. }
  756. ?>

至此框架搭建完成,下面来写一个简单的例子

三.介绍简单的实例

controller控制层文件./app/controllers/user.php用户类

    1. <?php
    2. /**
    3. * @file: user.php 用户控制层
    4. * @version: 1.0
    5. * @author: Sara
    6. * @create: 2012-12-17 10:15:00
    7. * @update: 2012-12-17 10:15:00
    8. * @access: <a target="_blank" href="http://blog.csdn.net/haiqiao_2010" style="font-family:verdana,'ms song',宋体,Arial,微软雅黑,Helvetica,sans-serif">http://blog.csdn.net/haiqiao_2010</a>
    9. * @copyright: 2012 <a target="_blank" href="http://blog.csdn.net/haiqiao_2010" style="font-family:verdana,'ms song',宋体,Arial,微软雅黑,Helvetica,sans-serif">http://blog.csdn.net/haiqiao_2010</a> All rights reserved.
    10. **/
    11. header('Content-Type: text/html; charset=utf-8');
    12. @require_once './core/config/conn.php';
    13. class user
    14. {
    15. /*
    16. * method __construct
    17. * paramemter string $a
    18. * return 提示信息/调用方法
    19. */
    20. function __construct()
    21. {
    22. $action=@trim(@$_REQUEST['act']);
    23. if(empty($action)){
    24. $action="index";
    25. }else{
    26. if(!in_array($action,array('index','login','register','<span style="font-family:verdana,'ms song',宋体,Arial,微软雅黑,Helvetica,sans-serif">userUpdatePwd</span><span style="font-family:verdana,'ms song',宋体,Arial,微软雅黑,Helvetica,sans-serif">'))){</span>
    27. ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>$action));
    28. }
    29. }
    30. }
    31. /*
    32. * method index 非法调用
    33. * param
    34. * return
    35. */
    36. public function index()
    37. {
    38. ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>@$_REQUEST['act']));
    39. }
    40. /*
    41. * method login 用户登陆(支持邮箱+密码或者账号+密码)
    42. * param string $user_name,string $user_pwd,string $l_ip,string $city_name,float $l_xpoint,float $l_ypoint
    43. * return 返回成功/失败已经登陆信息
    44. */
    45. public function login()
    46. {
    47. $data=json_decode(@$_REQUEST['req']);
    48. $user_name_or_email = trim(new_htmlspecialchars(new_addslashes(@$data->user_name)));
    49. $user_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->user_pwd)));
    50. $log['l_ip'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_ip)));
    51. $log['city_name'] = trim(new_htmlspecialchars(new_addslashes(@$data->city_name)));
    52. $log['l_xpoint'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_xpoint)));
    53. $log['l_ypoint'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_ypoint)));
    54. $log['l_type'] = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android
    55. $log['l_version'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_version)));
    56. if(empty($user_name_or_email)|| empty($user_pwd))
    57. {
    58. $r=array('recode'=>"0002",'msg'=>"参数错误",'data'=>'');
    59. }
    60. else
    61. {
    62. $user_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user where (user_name='".$user_name_or_email."' or email = '".$user_name_or_email."') and is_delete = 0");
    63. if(!$user_data)
    64. {
    65. $r=array('recode'=>"1014",'msg'=>"该用户不存在,请确认操作.",'data'=>'');
    66. }
    67. else
    68. {
    69. if($user_data['user_pwd'] != md5($user_pwd.$user_data['code'])&&$user_data['user_pwd']!=$user_pwd)
    70. {
    71. $r=array('recode'=>"0012",'msg'=>"用户密码不对,请确认您的登陆信息.",'data'=>'');
    72. }
    73. elseif($user_data['is_effect'] != 1)
    74. {
    75. $r=array('recode'=>"0011",'msg'=>"账号未被激活,暂时不能进行如下操作.",'data'=>'');
    76. }
    77. elseif($user_data['is_locking'] != 0)
    78. {
    79. $r=array('recode'=>"0014",'msg'=>"账号已经被锁定,暂时不能进行如下操作.",'data'=>'');
    80. if(app_conf("SHOP_TEL")!='')
    81. $r['msg'].="若有疑问,请致电联系客服: <".app_conf("SHOP_TEL").">";
    82. }
    83. else
    84. {
    85. //im:查看会员分组是否能够升级
    86. $user_current_group = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_group where id = ".intval($user_data['group_id']));
    87. $user_group = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_group where score <=".intval($user_data['score'])." order by score desc");
    88. if($user_current_group['score']<$user_group['score'])
    89. {
    90. $user_data['group_id'] = intval($user_group['id']);
    91. $GLOBALS['db']->query("update ".DB_PREFIX."user set group_id = ".$user_data['group_id']." where id = ".$user_data['id']);
    92. $pm_title = "您已经成为".$user_group['name']."";
    93. $pm_content = "恭喜您,您已经成为".$user_group['name']."。";
    94. if($user_group['discount']<1)
    95. {
    96. $pm_content.="您将享有".($user_group['discount']*10)."折的购物优惠";
    97. }
    98. send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true);
    99. }
    100. //im:查看会员积分是否能够升级
    101. $user_current_level = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_level where id = ".intval($user_data['level_id']));
    102. $user_level = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_level where point <=".intval($user_data['point'])." order by point desc");
    103. if($user_current_level['point']<$user_level['point'])
    104. {
    105. $user_data['level_id'] = intval($user_level['id']);
    106. $GLOBALS['db']->query("update ".DB_PREFIX."user set level_id = ".$user_data['level_id']." where id = ".$user_data['id']);
    107. $pm_title = "您已经成为".$user_level['name']."";
    108. $pm_content = "恭喜您,您已经成为".$user_level['name']."。";
    109. send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true);
    110. }
    111. if($user_current_level['point']>$user_level['point'])
    112. {
    113. $user_data['level_id'] = intval($user_level['id']);
    114. $GLOBALS['db']->query("update ".DB_PREFIX."user set level_id = ".$user_data['level_id']." where id = ".$user_data['id']);
    115. $pm_title = "您已经降为".$user_level['name']."";
    116. $pm_content = "很报歉,您已经降为".$user_level['name']."。";
    117. send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true);
    118. }
    119. $log['l_time']=get_gmtime();
    120. $log['user_id']=$user_data['id'];
    121. //im:更新最后登陆信息
    122. $GLOBALS['db']->query("update ".DB_PREFIX."user set login_ip = '".$log['l_ip']."',login_time= ".$log['l_time'].",group_id=".intval($user_data['group_id'])." where id =".$user_data['id']);
    123. //添加登陆日志
    124. $GLOBALS['db']->autoExecute("im_user_login_log",$log);
    125. //检查是否为最新系统版本
    126. $log['l_type'] = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android
    127. switch ($log['l_type'])//im_m_package:p_type:手机系统版本类型,默认为0 ios系统;为1 android系统
    128. {
    129. case "1":
    130. $package=$GLOBALS['db']->getRow("select p_version,p_url,is_must from im_m_package where is_effect=1 and p_type=0");
    131. break;
    132. case "2":
    133. $package=$GLOBALS['db']->getRow("select p_version,p_url,is_must from im_m_package where is_effect=1 and p_type=1");
    134. break;
    135. default:
    136. break;
    137. }
    138. if (@$package && strnatcmp($log['l_version'],$package['p_version'])<0)
    139. {
    140. //                      $varreg="/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/";
    141. $varreg="/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
    142. if(!preg_match($varreg,$package['p_url']))//im:判断是否为超链接
    143. {
    144. $package['p_url']=URL_PATH.str_replace("./","",$package['p_url']);
    145. }
    146. $r=array('recode'=>"0015",'msg'=>"用户登陆成功.",'data'=>array('user_id'=>$user_data['id'],'user_name'=>$user_data['user_name'],'true_name'=>$user_data['true_name'],'email'=>is_null($user_data['email'])?"":$user_data['email'],'mobile'=>is_null($user_data['mobile'])?"":$user_data['mobile'],'l_time'=>to_date($log['l_time']),'p_version'=>$package['p_version'],'p_url'=>$package['p_url'],'is_must'=>$package['is_must']));
    147. }
    148. else
    149. {
    150. $r=array('recode'=>"0015",'msg'=>"用户登陆成功.",'data'=>array('user_id'=>$user_data['id'],'user_name'=>$user_data['user_name'],'true_name'=>$user_data['true_name'],'email'=>is_null($user_data['email'])?"":$user_data['email'],'mobile'=>is_null($user_data['mobile'])?"":$user_data['mobile'],'l_time'=>to_date($log['l_time']),'p_version'=>$log['l_version'],'p_url'=>"",'is_must'=>""));
    151. }
    152. }
    153. }
    154. }
    155. ajax_return($r);
    156. }
    157. /*
    158. * method register 用户注册
    159. * param int $type,string $user_name,string $user_pwd,string $email ,string mobile
    160. * return 返回成功/失败
    161. */
    162. public function register()
    163. {
    164. //{"type":0,"user_name":"sara123","user_pwd":"123456","email":"sara123@qq.com","mobile":"13245678900","xpoint":"119.306938","ypoint":"26.069746","city_name":"\u5b81\u590f","ip":"192.168.1","l_type":"1","l_version":"1.0","verify_code":"123456","msg_id":"12"}
    165. //      $data=json_encode(array(
    166. //                      "type"=>0,
    167. //                      "user_name"=>"sara123",
    168. //                      "user_pwd"=>"123456",
    169. //                      "email"=>"sara123@qq.com",
    170. //                      "mobile"=>"13245678900",
    171. //                      "xpoint"=>"119.306938",
    172. //                      "ypoint"=>"26.069746",
    173. //                      "city_name"=>"宁夏",
    174. //                      "ip"=>"192.168.1",
    175. //                      "l_type"=>"1",
    176. //                      "l_version"=>"1.0",
    177. //                      "verify_code"=>"123456",
    178. //                      "msg_id"=>12
    179. //                      ));
    180. $data=json_decode(@$_REQUEST['req']);
    181. $type = intval(@$data->type);//im:注册方式:默认为0:邮箱+账号;1为:手机号+账号
    182. $user_data['user_name'] = strtolower(trim(new_htmlspecialchars(new_addslashes(@$data->user_name))));
    183. $user_data["user_pwd"] = trim(new_htmlspecialchars(new_addslashes(@$data->user_pwd)));
    184. $user_data["email"] = trim(new_htmlspecialchars(new_addslashes(@$data->email)));
    185. $user_data["mobile"] = trim(new_htmlspecialchars(new_addslashes(@$data->mobile)));
    186. $user_data["xpoint"] = doubleval(@$data->xpoint);
    187. $user_data["ypoint"] = doubleval(@$data->ypoint);
    188. $city_name = trim(new_htmlspecialchars(new_addslashes(@$data->city_name)));
    189. $user_data["login_ip"] = trim(new_htmlspecialchars(new_addslashes(@$data->ip)));
    190. $l_type = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android
    191. $l_version = trim(new_htmlspecialchars(new_addslashes(@$data->l_version)));
    192. if($user_data['user_name']==''|| !preg_match("/^[a-z\d]{3,20}$/i", $user_data['user_name']))
    193. {
    194. ajax_return(array('recode'=>"1001",'msg'=>"用户名不能为空,且为3-20个由字母和数字组成的字符串.".$data->user_name,'data'=>""));
    195. }
    196. else
    197. {
    198. if($GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where user_name = '".trim($user_data['user_name'])."'")>0)
    199. {
    200. ajax_return(array('recode'=>"1006",'msg'=>"该用户名已经存在,请重新填写",'data'=>''));
    201. }
    202. else
    203. {
    204. $msg=get_pwd_strength($user_data['user_pwd']);
    205. if(!empty($msg))
    206. {
    207. ajax_return(array('recode'=>"1003",'msg'=>$msg,'data'=>''));
    208. }
    209. else
    210. {
    211. if($type==0)
    212. {
    213. if(!check_email($user_data['email']))
    214. {
    215. ajax_return(array('recode'=>"1003",'msg'=>"邮箱格式不正确.",'data'=>''));
    216. }
    217. else
    218. {
    219. if($GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where email = '".trim($user_data['email'])."'")>0)
    220. {
    221. ajax_return(array('recode'=>"1004",'msg'=>"该邮箱已经被注册过,请填写其他邮箱.",'data'=>''));
    222. }
    223. }
    224. }
    225. else
    226. {
    227. if(!check_mobile($user_data['mobile']))
    228. {
    229. ajax_return(array('recode'=>"1005",'msg'=>"手机号码格式错误,手机号码为11位.",'data'=>''));
    230. }
    231. else
    232. {
    233. $verify_code = trim(new_htmlspecialchars(new_addslashes(@$data->verify_code)));
    234. $msg_id = intval(@$data->msg_id);
    235. if ($msg_id<=0 || empty($verify_code))
    236. {
    237. ajax_return(array('recode'=>"0002",'msg'=>"参数错误",'data'=>''));
    238. }
    239. $verify_result=use_sms_code(0,0,$msg_id,0,$user_data["mobile"],$verify_code);
    240. if($verify_result['status']==0)
    241. {
    242. ajax_return(array('recode'=>$verify_result['recode'],'msg'=>$verify_result['msg'],'data'=>''));
    243. }
    244. }
    245. }
    246. //验证结束开始插入数据
    247. $user_data['create_time'] = get_gmtime();
    248. $user_data['update_time'] = get_gmtime();
    249. //获取默认会员组, 即升级积分最小的会员组
    250. $user_data['group_id'] = $GLOBALS['db']->getOne("select id from ".DB_PREFIX."user_group order by score asc limit 1");
    251. //获取用户所在城市id
    252. $city = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."region_conf where name='".$city_name."'");
    253. if ($city)
    254. {
    255. switch ($city['region_level']) {//im:1:国 2:省 3:市(县) 4:区(镇)
    256. case "2":
    257. $user_data['province_id']=$city['id'];
    258. break;
    259. case "3":
    260. $user_data['city_id']=$city['id'];
    261. $user_data['province_id'] = $city['pid'];
    262. break;
    263. default:
    264. break;
    265. }
    266. }
    267. //账号是否激活
    268. //                      $user_data['is_effect'] = empty($user_data['is_effect'])? app_conf("USER_VERIFY"):$user_data['is_effect'];
    269. $user_data['is_effect']=1;//手机端注册,默认账号为激活状态
    270. $user_data['code'] = ''; //默认不使用code, 该值用于其他系统导入时的初次认证
    271. $user_data['user_pwd'] = md5($user_data['user_pwd'].$user_data['code']);
    272. $user_data['register_type'] = 1;//register_type:im:用户注册的方式:默认为0,web端注册,1为手机端注册
    273. if($GLOBALS['db']->autoExecute(DB_PREFIX."user",$user_data,"INSERT"))
    274. {
    275. $user_id = $GLOBALS['db']->insert_id();
    276. $register_money = app_conf('USER_REGISTER_MONEY');
    277. $register_score = app_conf('USER_REGISTER_SCORE');
    278. $register_point = app_conf('USER_REGISTER_POINT');
    279. if($register_money>0||$register_score>0)
    280. {
    281. $user_get['score'] = $register_score;
    282. $user_get['money'] = $register_money;
    283. $user_get['point'] = $register_point;
    284. @require_once './app/modules/userModule.php';
    285. modify_account($user_get,intval($user_id),"在".to_date(get_gmtime())."注册成功");
    286. }
    287. //im:添加登陆日志
    288. $GLOBALS['db']->autoExecute("im_user_login_log",array('user_id'=>$user_id,'l_type'=>1,'l_ip'=>$user_data['login_ip'],'l_time'=>get_gmtime(),"city_name"=>$city_name,"l_xpoint"=>$user_data['xpoint'],"l_ypoint"=>$user_data['ypoint'],"l_type"=>$l_type,"l_version"=>$l_version));
    289. ajax_return(array('recode'=>"1009",'msg'=>"用户注册成功",'data'=>array('user_id'=>$user_id,"user_name"=>$user_data['user_name'],"email"=>is_null($user_data['email'])?"":$user_data['email'],"mobile"=>is_null($user_data['mobile'])?"":$user_data['mobile'],"create_time"=>to_date($user_data['create_time']))));
    290. }
    291. else
    292. {
    293. ajax_return(array('recode'=>"1008",'msg'=>"用户注册失败",'data'=>''));
    294. }
    295. }
    296. }
    297. }
    298. }
    299. /*
    300. * method userUpdatePwd 修改密码接口
    301. * parameter int $user_id
    302. * parameter string $old_pwd
    303. * parameter string $new_pwd
    304. * return 返回成功/失败
    305. */
    306. function userUpdatePwd()
    307. {
    308. //{"user_id":0,"old_pwd":"111@qq.com","new_pwd":"13245678900"}
    309. //      $data=json_encode(array(
    310. //                      "user_id"=>0,
    311. //                      "old_pwd"=>"sara123@qq.com",
    312. //                      "new_pwd"=>"13245678900"
    313. //                      ));
    314. $data=json_decode(@$_REQUEST['req']);
    315. $user_id = intval(@$data->user_id);
    316. $user_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->old_pwd)));
    317. $new_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->new_pwd)));
    318. if ($user_id<=0)
    319. {
    320. $r=array('recode'=>"0002",'msg'=>"参数错误.",'data'=>'');
    321. }
    322. else
    323. {
    324. $msg=get_pwd_strength($new_pwd);
    325. if(!empty($msg))
    326. {
    327. $r=array('recode'=>"1002",'msg'=>$msg,'data'=>'');
    328. ajax_return($r);
    329. }
    330. else
    331. {
    332. $user_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user where id='".$user_id."'");
    333. if(!$user_data)
    334. {
    335. $r=array('recode'=>"1014",'msg'=>"该用户不存在,请确认操作.",'data'=>'');
    336. }
    337. else
    338. {
    339. if($user_data['user_pwd'] != md5($user_pwd.$user_data['code'])&&$user_data['user_pwd']!=$user_pwd)
    340. {
    341. $r=array('recode'=>"0012",'msg'=>"用户密码不对,请确认您的登陆信息.",'data'=>'');
    342. }
    343. elseif($user_data['is_effect'] != 1)
    344. {
    345. $r=array('recode'=>"0011",'msg'=>"账号未被激活,暂时不能进行如下操作.",'data'=>'');
    346. }
    347. else if ($user_data['is_delete']==1)
    348. {
    349. $r=array('recode'=>"1012",'msg'=>"该用户已被删除,请重新注册.",'data'=>'');
    350. }
    351. else
    352. {
    353. $user_data['user_pwd'] = $new_pwd;
    354. $new_pwd = md5($new_pwd.$user_data['code']);
    355. if($GLOBALS['db']->query("update ".DB_PREFIX."user set user_pwd = '".$new_pwd."',password_verify='' where id = ".$user_data['id'] ))
    356. {
    357. $GLOBALS['db']->query("update ".DB_PREFIX."supplier_account set account_password = '".$new_pwd."' where user_id = ".$user_data['id'] );
    358. $r=array('recode'=>"0000",'msg'=>"操作成功.",'data'=>'');
    359. }
    360. else
    361. {
    362. $r=array('recode'=>"0001",'msg'=>"操作失败.",'data'=>'');
    363. }
    364. }
    365. }
    366. }
    367. }
    368. ajax_return($r);
    369. }
    370. }
    371. ?>