api.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. <?php
  2. define('IN_API', true);
  3. require_once './framework/bootstrap.inc.php';
  4. load()->model('reply');
  5. load()->model('attachment');
  6. load()->model('visit');
  7. load()->model('app');
  8. load()->app('common');
  9. load()->classs('wesession');
  10. $hash = $_GPC['hash'];
  11. if(!empty($hash)) {
  12. $id = pdo_fetchcolumn("SELECT acid FROM " . tablename('account') . " WHERE hash = :hash", array(':hash' => $hash));
  13. }
  14. if(!empty($_GPC['appid'])) {
  15. $appid = ltrim($_GPC['appid'], '/');
  16. if ($appid == 'wx570bc396a51b8ff8') {
  17. $_W['account'] = array(
  18. 'type' => '3',
  19. 'key' => 'wx570bc396a51b8ff8',
  20. 'level' => 4,
  21. 'token' => 'platformtestaccount'
  22. );
  23. } else {
  24. $id = pdo_fetchcolumn("SELECT acid FROM " . tablename('account_wechats') . " WHERE `key` = :appid", array(':appid' => $appid));
  25. }
  26. }
  27. if(empty($id)) {
  28. $id = intval($_GPC['id']);
  29. }
  30. if (!empty($id)) {
  31. $uniacid = pdo_getcolumn('account', array('acid' => $id), 'uniacid');
  32. $_W['account'] = $_W['uniaccount'] = uni_fetch($uniacid);
  33. if (!empty($_W['account']['uniacid']) && app_pass_visit_limit($_W['account']['uniacid'])) {
  34. exit('success');
  35. }
  36. }
  37. if(empty($_W['account'])) {
  38. exit('initial error hash or id');
  39. }
  40. if(empty($_W['account']['token'])) {
  41. exit('initial missing token');
  42. }
  43. $_W['debug'] = intval($_GPC['debug']);
  44. $_W['acid'] = $_W['account']['acid'];
  45. $_W['uniacid'] = $_W['account']['uniacid'];
  46. $_W['account']['groupid'] = $_W['uniaccount']['groupid'];
  47. $_W['account']['qrcode'] = $_W['attachurl'].'qrcode_'.$_W['acid'].'.jpg?time='.$_W['timestamp'];
  48. $_W['account']['avatar'] = $_W['attachurl'].'headimg_'.$_W['acid'].'.jpg?time='.$_W['timestamp'];
  49. $_W['attachurl'] = attachment_set_attach_url();
  50. register_shutdown_function('visit_update_today', 'app', 'we7_api');
  51. $engine = new WeEngine();
  52. if (!empty($_W['setting']['copyright']['status'])) {
  53. $engine->died('抱歉,站点已关闭,关闭原因:' . $_W['setting']['copyright']['reason']);
  54. }
  55. if (!empty($_W['uniaccount']['endtime']) && TIMESTAMP > $_W['uniaccount']['endtime'] && !in_array($_W['uniaccount']['endtime'], array(USER_ENDTIME_GROUP_EMPTY_TYPE, USER_ENDTIME_GROUP_UNLIMIT_TYPE))) {
  56. $engine->died('抱歉,您的公众号已过期,请及时联系管理员');
  57. }
  58. if($_W['isajax'] && $_W['ispost'] && $_GPC['flag'] == 1) {
  59. $engine->encrypt();
  60. }
  61. if($_W['isajax'] && $_W['ispost'] && $_GPC['flag'] == 2) {
  62. $engine->decrypt();
  63. }
  64. $_W['isajax'] = false;
  65. $engine->start();
  66. class WeEngine {
  67. private $account = null;
  68. private $modules = array();
  69. public $keyword = array();
  70. public $message = array();
  71. public function __construct() {
  72. global $_W;
  73. $this->account = WeAccount::create($_W['account']);
  74. if(strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
  75. $_W['modules'] = uni_modules();
  76. $this->modules = array_keys($_W['modules']);
  77. $this->modules[] = 'cover';
  78. $this->modules[] = 'default';
  79. $this->modules[] = 'reply';
  80. $this->modules = array_unique ($this->modules);
  81. }
  82. }
  83. public function encrypt() {
  84. global $_W;
  85. if(empty($this->account)) {
  86. exit('Miss Account.');
  87. }
  88. $timestamp = TIMESTAMP;
  89. $nonce = random(5);
  90. $token = $_W['account']['token'];
  91. $signkey = array($token, TIMESTAMP, $nonce);
  92. sort($signkey, SORT_STRING);
  93. $signString = implode($signkey);
  94. $signString = sha1($signString);
  95. $_GET['timestamp'] = $timestamp;
  96. $_GET['nonce'] = $nonce;
  97. $_GET['signature'] = $signString;
  98. $postStr = file_get_contents('php://input');
  99. if(!empty($_W['account']['encodingaeskey']) && strlen($_W['account']['encodingaeskey']) == 43 && !empty($_W['account']['key']) && $_W['setting']['development'] != 1) {
  100. $data = $this->account->encryptMsg($postStr);
  101. $array = array('encrypt_type' => 'aes', 'timestamp' => $timestamp, 'nonce' => $nonce, 'signature' => $signString, 'msg_signature' => $data[0], 'msg' => $data[1]);
  102. } else {
  103. $data = array('', '');
  104. $array = array('encrypt_type' => '', 'timestamp' => $timestamp, 'nonce' => $nonce, 'signature' => $signString, 'msg_signature' => $data[0], 'msg' => $data[1]);
  105. }
  106. exit(json_encode($array));
  107. }
  108. public function decrypt() {
  109. global $_W;
  110. if(empty($this->account)) {
  111. exit('Miss Account.');
  112. }
  113. $postStr = file_get_contents('php://input');
  114. if(!empty($_W['account']['encodingaeskey']) && strlen($_W['account']['encodingaeskey']) == 43 && !empty($_W['account']['key']) && $_W['setting']['development'] != 1) {
  115. $resp = $this->account->local_decryptMsg($postStr);
  116. } else {
  117. $resp = $postStr;
  118. }
  119. exit($resp);
  120. }
  121. public function start() {
  122. global $_W;
  123. if(empty($this->account)) {
  124. exit('Miss Account.');
  125. }
  126. if(!$this->account->checkSign()) {
  127. exit('Check Sign Fail.');
  128. }
  129. if(strtolower($_SERVER['REQUEST_METHOD']) == 'get') {
  130. $row = array();
  131. $row['isconnect'] = 1;
  132. pdo_update('account', $row, array('acid' => $_W['acid']));
  133. cache_delete(cache_system_key('uniaccount', array('uniacid' => $_W['uniacid'])));
  134. exit(htmlspecialchars($_GET['echostr']));
  135. }
  136. if(strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
  137. $postStr = file_get_contents('php://input');
  138. if(!empty($_GET['encrypt_type']) && $_GET['encrypt_type'] == 'aes') {
  139. $postStr = $this->account->decryptMsg($postStr);
  140. }
  141. WeUtility::logging('trace', $postStr);
  142. $message = $this->account->parse($postStr);
  143. $this->message = $message;
  144. if(empty($message)) {
  145. WeUtility::logging('waring', 'Request Failed');
  146. exit('Request Failed');
  147. }
  148. $_W['openid'] = $message['from'];
  149. $_W['fans'] = array('from_user' => $_W['openid']);
  150. $this->booking($message);
  151. if($message['event'] == 'unsubscribe') {
  152. $this->receive(array(), array(), array());
  153. exit();
  154. }
  155. $sessionid = md5($message['from'] . $message['to'] . $_W['uniacid']);
  156. session_id($sessionid);
  157. WeSession::start($_W['uniacid'], $_W['openid']);
  158. $_SESSION['openid'] = $_W['openid'];
  159. $pars = $this->analyze($message);
  160. $pars[] = array(
  161. 'message' => $message,
  162. 'module' => 'default',
  163. 'rule' => '-1',
  164. );
  165. $hitParam['rule'] = -2;
  166. $hitParam['module'] = '';
  167. $hitParam['message'] = $message;
  168. $hitKeyword = array();
  169. $response = array();
  170. foreach($pars as $par) {
  171. if(empty($par['module'])) {
  172. continue;
  173. }
  174. $par['message'] = $message;
  175. $response = $this->process($par);
  176. if($this->isValidResponse($response)) {
  177. $hitParam = $par;
  178. if(!empty($par['keyword'])) {
  179. $hitKeyword = $par['keyword'];
  180. }
  181. break;
  182. }
  183. }
  184. $response_debug = $response;
  185. $pars_debug = $pars;
  186. if($hitParam['module'] == 'default' && is_array($response) && is_array($response['params'])) {
  187. foreach($response['params'] as $par) {
  188. if(empty($par['module'])) {
  189. continue;
  190. }
  191. $response = $this->process($par);
  192. if($this->isValidResponse($response)) {
  193. $hitParam = $par;
  194. if(!empty($par['keyword'])) {
  195. $hitKeyword = $par['keyword'];
  196. }
  197. break;
  198. }
  199. }
  200. }
  201. WeUtility::logging('params', var_export($hitParam, true));
  202. WeUtility::logging('response', $response);
  203. $resp = $this->account->response($response);
  204. if(!empty($_GET['encrypt_type']) && $_GET['encrypt_type'] == 'aes') {
  205. $resp = $this->account->encryptMsg($resp);
  206. $resp = $this->account->xmlDetract($resp);
  207. }
  208. if($_W['debug']) {
  209. $_W['debug_data'] = array(
  210. 'resp' => $resp,
  211. 'is_default' => 0
  212. );
  213. if(count($pars_debug) == 1) {
  214. $_W['debug_data']['is_default'] = 1;
  215. $_W['debug_data']['params'] = $response_debug['params'];
  216. } else {
  217. array_pop($pars_debug);
  218. $_W['debug_data']['params'] = $pars_debug;
  219. }
  220. $_W['debug_data']['hitparam'] = $hitParam;
  221. $_W['modules']['cover'] = array('title' => '入口封面', 'name' => 'cover');
  222. load()->web('template');
  223. $process = template('utility/emulator', TEMPLATE_FETCH);
  224. echo json_encode(array('resp' => $resp, 'process' => $process));
  225. exit();
  226. }
  227. if ($resp !== 'success') {
  228. $mapping = array(
  229. '[from]' => $this->message['from'],
  230. '[to]' => $this->message['to'],
  231. '[rule]' => $this->params['rule']
  232. );
  233. $resp = str_replace(array_keys($mapping), array_values($mapping), $resp);
  234. }
  235. $reply_times_info = (array)$_SESSION['__reply_times'];
  236. if ($reply_times_info['content'] == $message['content']) {
  237. $new_times = intval($reply_times_info['times']) + 1;
  238. } else {
  239. $new_times = 1;
  240. }
  241. $_SESSION['__reply_times'] = array('content' => $message['content'], 'date' => date('Y-m-d'), 'times' => $new_times);
  242. ob_start();
  243. echo $resp;
  244. ob_start();
  245. $this->receive($hitParam, $hitKeyword, $response);
  246. ob_end_clean();
  247. exit();
  248. }
  249. WeUtility::logging('waring', 'Request Failed');
  250. exit('Request Failed');
  251. }
  252. private function isValidResponse($response) {
  253. if ($response === 'success') {
  254. return true;
  255. }
  256. if(is_array($response)) {
  257. if($response['type'] == 'text' && !empty($response['content'])) {
  258. return true;
  259. }
  260. if($response['type'] == 'news' && !empty($response['items'])) {
  261. return true;
  262. }
  263. if(!in_array($response['type'], array('text', 'news', 'image'))) {
  264. return true;
  265. }
  266. }
  267. return false;
  268. }
  269. private function booking($message) {
  270. global $_W;
  271. if ($message['event'] == 'unsubscribe' || $message['event'] == 'subscribe') {
  272. $todaystat = pdo_get('stat_fans', array('date' => date('Ymd'), 'uniacid' => $_W['uniacid']));
  273. if ($message['event'] == 'unsubscribe') {
  274. if (empty($todaystat)) {
  275. $updatestat = array(
  276. 'new' => 0,
  277. 'uniacid' => $_W['uniacid'],
  278. 'cancel' => 1,
  279. 'cumulate' => 0,
  280. 'date' => date('Ymd'),
  281. );
  282. pdo_insert('stat_fans', $updatestat);
  283. } else {
  284. $updatestat = array(
  285. 'cancel' => $todaystat['cancel'] + 1,
  286. );
  287. $updatestat['cumulate'] = 0;
  288. pdo_update('stat_fans', $updatestat, array('id' => $todaystat['id']));
  289. }
  290. } elseif ($message['event'] == 'subscribe') {
  291. if (empty($todaystat)) {
  292. $updatestat = array(
  293. 'new' => 1,
  294. 'uniacid' => $_W['uniacid'],
  295. 'cancel' => 0,
  296. 'cumulate' => 0,
  297. 'date' => date('Ymd'),
  298. );
  299. pdo_insert('stat_fans', $updatestat);
  300. } else {
  301. $updatestat = array(
  302. 'new' => $todaystat['new'] + 1,
  303. 'cumulate' => 0,
  304. );
  305. pdo_update('stat_fans', $updatestat, array('id' => $todaystat['id']));
  306. }
  307. }
  308. }
  309. load()->model('mc');
  310. $setting = uni_setting($_W['uniacid'], array('passport'));
  311. $fans = mc_fansinfo($message['from']);
  312. $default_groupid = cache_load(cache_system_key('defaultgroupid', array('uniacid' => $_W['uniacid'])));
  313. if (empty($default_groupid)) {
  314. $default_groupid = pdo_fetchcolumn('SELECT groupid FROM ' .tablename('mc_groups') . ' WHERE uniacid = :uniacid AND isdefault = 1', array(':uniacid' => $_W['uniacid']));
  315. cache_write(cache_system_key('defaultgroupid', array('uniacid' => $_W['uniacid'])), $default_groupid);
  316. }
  317. if(!empty($fans)) {
  318. if ($message['event'] == 'unsubscribe') {
  319. cache_build_memberinfo($fans['uid']);
  320. pdo_update('mc_mapping_fans', array('follow' => 0, 'unfollowtime' => TIMESTAMP), array('fanid' => $fans['fanid']));
  321. pdo_delete('mc_fans_tag_mapping', array('fanid' => $fans['fanid']));
  322. } elseif ($message['event'] != 'ShakearoundUserShake' && $message['type'] != 'trace') {
  323. $rec = array();
  324. if (empty($fans['follow'])) {
  325. $rec['follow'] = 1;
  326. $rec['followtime'] = $message['time'];
  327. }
  328. $member = array();
  329. if(!empty($fans['uid'])){
  330. $member = mc_fetch($fans['uid']);
  331. }
  332. if (empty($member)) {
  333. if (!isset($setting['passport']) || empty($setting['passport']['focusreg'])) {
  334. $data = array(
  335. 'uniacid' => $_W['uniacid'],
  336. 'email' => md5($message['from']).'@we7.cc',
  337. 'salt' => random(8),
  338. 'groupid' => $default_groupid,
  339. 'createtime' => TIMESTAMP,
  340. );
  341. $data['password'] = md5($message['from'] . $data['salt'] . $_W['config']['setting']['authkey']);
  342. pdo_insert('mc_members', $data);
  343. $rec['uid'] = pdo_insertid();
  344. }
  345. }
  346. if(!empty($rec)){
  347. pdo_update('mc_mapping_fans', $rec, array('openid' => $message['from']));
  348. }
  349. }
  350. } else {
  351. if ($message['event'] == 'subscribe' || $message['type'] == 'text' || $message['type'] == 'image') {
  352. load()->model('mc');
  353. $force_init_member = false;
  354. if (!isset($setting['passport']) || empty($setting['passport']['focusreg'])) {
  355. $force_init_member = true;
  356. }
  357. mc_init_fans_info($message['from'], $force_init_member);
  358. }
  359. }
  360. }
  361. private function receive($par, $keyword, $response) {
  362. global $_W;
  363. fastcgi_finish_request();
  364. $subscribe = cache_load(cache_system_key('module_receive_enable'));
  365. if (empty($subscribe)) {
  366. $subscribe = cache_build_module_subscribe_type();
  367. }
  368. $modules = uni_modules();
  369. $obj = WeUtility::createModuleReceiver('core');
  370. $obj->message = $this->message;
  371. $obj->params = $par;
  372. $obj->response = $response;
  373. $obj->keyword = $keyword;
  374. $obj->module = 'core';
  375. $obj->uniacid = $_W['uniacid'];
  376. $obj->acid = $_W['acid'];
  377. if(method_exists($obj, 'receive')) {
  378. @$obj->receive();
  379. }
  380. load()->func('communication');
  381. if (empty($subscribe[$this->message['type']]) && !empty($this->message['event'])) {
  382. $subscribe[$this->message['type']] = $subscribe[strtolower($this->message['event'])];
  383. }
  384. if (!empty($subscribe[$this->message['type']])) {
  385. foreach ($subscribe[$this->message['type']] as $modulename) {
  386. if (!in_array($modulename, array_keys($modules))) {
  387. continue;
  388. }
  389. $params = array(
  390. 'i' => $GLOBALS['uniacid'],
  391. 'modulename' => $modulename,
  392. 'request' => json_encode($par),
  393. 'response' => json_encode($response),
  394. 'message' => json_encode($this->message),
  395. );
  396. $response = ihttp_request(wurl('utility/subscribe/receive'), $params, array(), 10);
  397. if (is_error($response) || $response['code'] != 200) {
  398. $response = ihttp_request($_W['siteroot'] . 'web/' . wurl('utility/subscribe/receive'), $params, array(), 10);
  399. }
  400. }
  401. }
  402. }
  403. private function analyze(&$message) {
  404. global $_W;
  405. $params = array();
  406. if(in_array($message['type'], array('event', 'qr'))) {
  407. $params = call_user_func_array(array($this, 'analyze' . $message['type']), array(&$message));
  408. if(!empty($params)) {
  409. return (array)$params;
  410. }
  411. }
  412. if(!empty($_SESSION['__contextmodule']) && in_array($_SESSION['__contextmodule'], $this->modules)) {
  413. if($_SESSION['__contextexpire'] > TIMESTAMP) {
  414. $params[] = array(
  415. 'message' => $message,
  416. 'module' => $_SESSION['__contextmodule'],
  417. 'rule' => $_SESSION['__contextrule'],
  418. 'priority' => $_SESSION['__contextpriority'],
  419. 'context' => true
  420. );
  421. return $params;
  422. } else {
  423. unset($_SESSION);
  424. session_destroy();
  425. }
  426. }
  427. $reply_times_info = (array)$_SESSION['__reply_times'];
  428. if (!empty($_W['account']['setting']) && !empty($reply_times_info) && intval($_W['account']['setting']['reply_setting']) > 0 && strtotime($reply_times_info['date']) >= strtotime(date('Y-m-d')) && $reply_times_info['times'] >= $_W['account']['setting']['reply_setting'] && $reply_times_info['content'] == $message['content']) {
  429. exit('success');
  430. }
  431. if(method_exists($this, 'analyze' . $message['type'])) {
  432. $temp = call_user_func_array(array($this, 'analyze' . $message['type']), array(&$message));
  433. if(!empty($temp) && is_array($temp)){
  434. $params += $temp;
  435. }
  436. } else {
  437. $params += $this->handler($message['type']);
  438. }
  439. return $params;
  440. }
  441. private function analyzeSubscribe(&$message) {
  442. global $_W;
  443. $params = array();
  444. $message['type'] = 'text';
  445. $message['redirection'] = true;
  446. if(!empty($message['scene'])) {
  447. $message['source'] = 'qr';
  448. $sceneid = trim($message['scene']);
  449. if (is_numeric($sceneid)) {
  450. $scene_condition = " `qrcid` = :sceneid";
  451. }else{
  452. $scene_condition = " `scene_str` = :sceneid";
  453. }
  454. $condition = array(':sceneid' => $sceneid, ':uniacid' => $_W['uniacid']);
  455. $qr = pdo_fetch("SELECT `id`, `keyword` FROM " . tablename('qrcode') . " WHERE {$scene_condition} AND `uniacid` = :uniacid", $condition);
  456. if(!empty($qr)) {
  457. $message['content'] = $qr['keyword'];
  458. if (!empty($qr['type']) && $qr['type'] == 'scene') {
  459. $message['msgtype'] = 'text';
  460. }
  461. $params += $this->analyzeText($message);
  462. return $params;
  463. }
  464. }
  465. $message['source'] = 'subscribe';
  466. $setting = uni_setting($_W['uniacid'], array('welcome'));
  467. if(!empty($setting['welcome'])) {
  468. $message['content'] = $setting['welcome'];
  469. $params += $this->analyzeText($message);
  470. }
  471. return $params;
  472. }
  473. private function analyzeQR(&$message) {
  474. global $_W;
  475. $params = array();
  476. $params = $this->handler($message['type']);
  477. if (!empty($params)) {
  478. return $params;
  479. }
  480. $message['type'] = 'text';
  481. $message['redirection'] = true;
  482. if(!empty($message['scene'])) {
  483. $message['source'] = 'qr';
  484. $sceneid = trim($message['scene']);
  485. if (is_numeric($sceneid)) {
  486. $scene_condition = " `qrcid` = :sceneid";
  487. }else{
  488. $scene_condition = " `scene_str` = :sceneid";
  489. }
  490. $condition_params = array(':sceneid' => $sceneid, ':uniacid' => $_W['uniacid']);
  491. $qr = pdo_fetch("SELECT `id`, `keyword` FROM " . tablename('qrcode') . " WHERE {$scene_condition} AND `uniacid` = :uniacid AND `type` = 'scene'", $condition_params);
  492. }
  493. if (empty($qr) && !empty($message['ticket'])) {
  494. $message['source'] = 'qr';
  495. $ticket = trim($message['ticket']);
  496. if(!empty($ticket)) {
  497. $qr = pdo_fetchall("SELECT `id`, `keyword` FROM " . tablename('qrcode') . " WHERE `uniacid` = :uniacid AND ticket = :ticket", array(':uniacid' => $_W['uniacid'], ':ticket' => $ticket));
  498. if(!empty($qr)) {
  499. if(count($qr) != 1) {
  500. $qr = array();
  501. } else {
  502. $qr = $qr[0];
  503. }
  504. }
  505. }
  506. }
  507. if(!empty($qr)) {
  508. $message['content'] = $qr['keyword'];
  509. if (!empty($qr['type']) && $qr['type'] == 'scene') {
  510. $message['msgtype'] = 'text';
  511. }
  512. $params += $this->analyzeText($message);
  513. }
  514. return $params;
  515. }
  516. public function analyzeText(&$message, $order = 0) {
  517. global $_W;
  518. $pars = array();
  519. $order = intval($order);
  520. if(!isset($message['content'])) {
  521. return $pars;
  522. }
  523. $cachekey = cache_system_key('keyword', array('content' => md5($message['content']), 'uniacid' => $_W['uniacid']));
  524. $keyword_cache = cache_load($cachekey);
  525. if (!empty($keyword_cache) && $keyword_cache['expire'] > TIMESTAMP) {
  526. return $keyword_cache['data'];
  527. }
  528. $condition = <<<EOF
  529. `uniacid` IN ( 0, {$_W['uniacid']} )
  530. AND
  531. (
  532. ( `type` = 1 AND `content` = :c1 )
  533. or
  534. ( `type` = 2 AND instr(:c2, `content`) )
  535. or
  536. ( `type` = 3 AND :c3 REGEXP `content` )
  537. or
  538. ( `type` = 4 )
  539. )
  540. AND `status`=1
  541. EOF;
  542. $params = array();
  543. $params[':c1'] = $message['content'];
  544. $params[':c2'] = $message['content'];
  545. $params[':c3'] = $message['content'];
  546. if (intval($order) > 0) {
  547. $condition .= " AND `displayorder` > :order";
  548. $params[':order'] = $order;
  549. }
  550. $keywords = reply_keywords_search($condition, $params);
  551. if(empty($keywords)) {
  552. return $pars;
  553. }
  554. $system_module_reply = true;
  555. foreach($keywords as $keyword) {
  556. if (!in_array($keyword['module'], array('defalut', 'cover', 'reply'))) {
  557. $system_module_reply = false;
  558. }
  559. $params = array(
  560. 'message' => $message,
  561. 'module' => $keyword['module'],
  562. 'rule' => $keyword['rid'],
  563. 'priority' => $keyword['displayorder'],
  564. 'keyword' => $keyword,
  565. 'reply_type' => $keyword['reply_type']
  566. );
  567. $pars[] = $params;
  568. }
  569. if (!empty($system_module_reply)) {
  570. $cache = array(
  571. 'data' => $pars,
  572. 'expire' => TIMESTAMP + 5 * 60,
  573. );
  574. cache_write($cachekey, $cache);
  575. }
  576. return $pars;
  577. }
  578. private function analyzeEvent(&$message) {
  579. if (strtolower($message['event']) == 'subscribe') {
  580. return $this->analyzeSubscribe($message);
  581. }
  582. if (strtolower($message['event']) == 'click') {
  583. $message['content'] = strval($message['eventkey']);
  584. return $this->analyzeClick($message);
  585. }
  586. if (in_array($message['event'], array('pic_photo_or_album', 'pic_weixin', 'pic_sysphoto'))) {
  587. pdo_delete('menu_event', array('createtime <' => $GLOBALS['_W']['timestamp'] - 100, 'openid' => $message['from']), 'OR');
  588. if (!empty($message['sendpicsinfo']['count'])) {
  589. foreach ($message['sendpicsinfo']['piclist'] as $item) {
  590. pdo_insert('menu_event', array(
  591. 'uniacid' => $GLOBALS['_W']['uniacid'],
  592. 'keyword' => $message['eventkey'],
  593. 'type' => $message['event'],
  594. 'picmd5' => $item,
  595. 'openid' => $message['from'],
  596. 'createtime' => TIMESTAMP,
  597. ));
  598. }
  599. } else {
  600. pdo_insert('menu_event', array(
  601. 'uniacid' => $GLOBALS['_W']['uniacid'],
  602. 'keyword' => $message['eventkey'],
  603. 'type' => $message['event'],
  604. 'picmd5' => $item,
  605. 'openid' => $message['from'],
  606. 'createtime' => TIMESTAMP,
  607. ));
  608. }
  609. $message['content'] = strval($message['eventkey']);
  610. $message['source'] = $message['event'];
  611. return $this->analyzeText($message);
  612. }
  613. if (!empty($message['eventkey'])) {
  614. $message['content'] = strval($message['eventkey']);
  615. $message['type'] = 'text';
  616. $message['redirection'] = true;
  617. $message['source'] = $message['event'];
  618. return $this->analyzeText($message);
  619. }
  620. return $this->handler($message['event']);
  621. }
  622. private function analyzeClick(&$message) {
  623. if(!empty($message['content']) || $message['content'] !== '') {
  624. $message['type'] = 'text';
  625. $message['redirection'] = true;
  626. $message['source'] = 'click';
  627. return $this->analyzeText($message);
  628. }
  629. return array();
  630. }
  631. private function analyzeImage(&$message) {
  632. load()->func('communication');
  633. if (!empty($message['picurl'])) {
  634. $response = ihttp_get($message['picurl']);
  635. if (!empty($response)) {
  636. $md5 = md5($response['content']);
  637. $event = pdo_get('menu_event', array('picmd5' => $md5), array('keyword', 'type'));
  638. if (!empty($event['keyword'])) {
  639. pdo_delete('menu_event', array('picmd5' => $md5));
  640. } else {
  641. $event = pdo_get('menu_event', array('openid' => $message['from']), array('keyword', 'type'));
  642. }
  643. if (!empty($event)) {
  644. $message['content'] = $event['keyword'];
  645. $message['eventkey'] = $event['keyword'];
  646. $message['type'] = 'text';
  647. $message['event'] = $event['type'];
  648. $message['redirection'] = true;
  649. $message['source'] = $event['type'];
  650. return $this->analyzeText($message);
  651. }
  652. }
  653. return $this->handler('image');
  654. }
  655. }
  656. private function analyzeVoice(&$message) {
  657. $params = $this->handler('voice');
  658. if (empty($params) && !empty($message['recognition'])) {
  659. $message['type'] = 'text';
  660. $message['redirection'] = true;
  661. $message['source'] = 'voice';
  662. $message['content'] = $message['recognition'];
  663. return $this->analyzeText($message);
  664. } else {
  665. return $params;
  666. }
  667. }
  668. private function handler($type) {
  669. if(empty($type)) {
  670. return array();
  671. }
  672. global $_W;
  673. $params = array();
  674. $setting = uni_setting($_W['uniacid'], array('default_message'));
  675. $default_message = $setting['default_message'];
  676. if(is_array($default_message) && !empty($default_message[$type]['type'])) {
  677. if ($default_message[$type]['type'] == 'keyword') {
  678. $message = $this->message;
  679. $message['type'] = 'text';
  680. $message['redirection'] = true;
  681. $message['source'] = $type;
  682. $message['content'] = $default_message[$type]['keyword'];
  683. return $this->analyzeText($message);
  684. } else {
  685. $params[] = array(
  686. 'message' => $this->message,
  687. 'module' => is_array($default_message[$type]) ? $default_message[$type]['module'] : $default_message[$type],
  688. 'rule' => '-1',
  689. );
  690. return $params;
  691. }
  692. }
  693. return array();
  694. }
  695. private function process($param) {
  696. global $_W;
  697. if(empty($param['module']) || !in_array($param['module'], $this->modules)) {
  698. return false;
  699. }
  700. if ($param['module'] == 'reply') {
  701. $processor = WeUtility::createModuleProcessor('core');
  702. } else {
  703. $processor = WeUtility::createModuleProcessor($param['module']);
  704. }
  705. $processor->message = $param['message'];
  706. $processor->rule = $param['rule'];
  707. $processor->reply_type = $param['reply_type'];
  708. $processor->priority = intval($param['priority']);
  709. $processor->inContext = $param['context'] === true;
  710. $response = $processor->respond();
  711. if(empty($response)) {
  712. return false;
  713. }
  714. return $response;
  715. }
  716. public function died($content = '') {
  717. global $_W, $engine;
  718. if (empty($content)) {
  719. exit('');
  720. }
  721. $response['FromUserName'] = $engine->message['to'];
  722. $response['ToUserName'] = $engine->message['from'];
  723. $response['MsgType'] = 'text';
  724. $response['Content'] = htmlspecialchars_decode($content);
  725. $response['CreateTime'] = TIMESTAMP;
  726. $response['FuncFlag'] = 0;
  727. $xml = array2xml($response);
  728. if(!empty($_GET['encrypt_type']) && $_GET['encrypt_type'] == 'aes') {
  729. $resp = $engine->account->encryptMsg($xml);
  730. $resp = $engine->account->xmlDetract($resp);
  731. } else {
  732. $resp = $xml;
  733. }
  734. exit($resp);
  735. }
  736. }