Service.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. namespace Widget;
  3. use Typecho\Common;
  4. use Typecho\Http\Client;
  5. use Typecho\Response;
  6. use Typecho\Widget\Exception;
  7. use Widget\Base\Contents;
  8. use Widget\Base\Options as BaseOptions;
  9. if (!defined('__TYPECHO_ROOT_DIR__')) {
  10. exit;
  11. }
  12. /**
  13. * 通用异步服务组件
  14. *
  15. * @author qining
  16. * @category typecho
  17. * @package Widget
  18. */
  19. class Service extends BaseOptions implements ActionInterface
  20. {
  21. /**
  22. * 异步请求
  23. *
  24. * @var array
  25. */
  26. public $asyncRequests = [];
  27. /**
  28. * 发送pingback实现
  29. *
  30. * @throws Exception|Client\Exception
  31. */
  32. public function sendPingHandle()
  33. {
  34. /** 验证权限 */
  35. $data = $this->request->get('@json');
  36. $token = $data['token'] ?? '';
  37. $permalink = $data['permalink'];
  38. $title = $data['title'];
  39. $excerpt = $data['excerpt'];
  40. $response = ['trackback' => [], 'pingback' => []];
  41. if (!Common::timeTokenValidate($token, $this->options->secret, 3) || empty($permalink)) {
  42. throw new Exception(_t('禁止访问'), 403);
  43. }
  44. /** 忽略超时 */
  45. if (function_exists('ignore_user_abort')) {
  46. ignore_user_abort(true);
  47. }
  48. if (function_exists('set_time_limit')) {
  49. set_time_limit(30);
  50. }
  51. if (!empty($data['pingback'])) {
  52. $links = $data['pingback'];
  53. $permalinkPart = parse_url($permalink);
  54. /** 发送pingback */
  55. foreach ($links as $url) {
  56. $urlPart = parse_url($url);
  57. if (isset($urlPart['scheme'])) {
  58. if ('http' != $urlPart['scheme'] && 'https' != $urlPart['scheme']) {
  59. continue;
  60. }
  61. } else {
  62. $urlPart['scheme'] = 'http';
  63. $url = Common::buildUrl($urlPart);
  64. }
  65. if ($permalinkPart['host'] == $urlPart['host'] && $permalinkPart['path'] == $urlPart['path']) {
  66. continue;
  67. }
  68. $spider = Client::get();
  69. if ($spider) {
  70. $spider->setTimeout(10)
  71. ->send($url);
  72. if (!($xmlrpcUrl = $spider->getResponseHeader('x-pingback'))) {
  73. if (
  74. preg_match(
  75. "/<link[^>]*rel=[\"']pingback[\"'][^>]*href=[\"']([^\"']+)[\"'][^>]*>/i",
  76. $spider->getResponseBody(),
  77. $out
  78. )
  79. ) {
  80. $xmlrpcUrl = $out[1];
  81. }
  82. }
  83. if (!empty($xmlrpcUrl)) {
  84. $response['pingback'][] = $url;
  85. try {
  86. $xmlrpc = new \IXR\Client($xmlrpcUrl);
  87. $xmlrpc->pingback->ping($permalink, $url);
  88. unset($xmlrpc);
  89. } catch (\IXR\Exception $e) {
  90. continue;
  91. }
  92. }
  93. }
  94. unset($spider);
  95. }
  96. }
  97. /** 发送trackback */
  98. if (!empty($data['trackback'])) {
  99. $links = $data['trackback'];
  100. foreach ($links as $url) {
  101. $client = Client::get();
  102. $response['trackback'][] = $url;
  103. if ($client) {
  104. try {
  105. $client->setTimeout(5)
  106. ->setData([
  107. 'blog_name' => $this->options->title . ' &raquo ' . $title,
  108. 'url' => $permalink,
  109. 'excerpt' => $excerpt
  110. ])
  111. ->send($url);
  112. unset($client);
  113. } catch (Client\Exception $e) {
  114. continue;
  115. }
  116. }
  117. }
  118. }
  119. $this->response->throwJson($response);
  120. }
  121. /**
  122. * 发送pingback
  123. * <code>
  124. * $this->sendPing($post);
  125. * </code>
  126. *
  127. * @param Contents $content 内容url
  128. * @param array|null $trackback
  129. */
  130. public function sendPing(Contents $content, ?array $trackback = null)
  131. {
  132. $this->user->pass('contributor');
  133. if ($client = Client::get()) {
  134. try {
  135. $input = [
  136. 'do' => 'ping',
  137. 'permalink' => $content->permalink,
  138. 'excerpt' => $content->excerpt,
  139. 'title' => $content->title,
  140. 'token' => Common::timeToken($this->options->secret)
  141. ];
  142. if (preg_match_all("|<a[^>]*href=[\"'](.*?)[\"'][^>]*>(.*?)</a>|", $content->content, $matches)) {
  143. $pingback = array_unique($matches[1]);
  144. if (!empty($pingback)) {
  145. $input['pingback'] = $pingback;
  146. }
  147. }
  148. if (!empty($trackback)) {
  149. $input['trackback'] = $trackback;
  150. }
  151. $client->setHeader('User-Agent', $this->options->generator)
  152. ->setTimeout(2)
  153. ->setJson($input)
  154. ->send($this->getServiceUrl('ping'));
  155. } catch (Client\Exception $e) {
  156. return;
  157. }
  158. }
  159. }
  160. /**
  161. * 获取真实的 URL
  162. *
  163. * @param string $do 动作名
  164. * @return string
  165. */
  166. private function getServiceUrl(string $do): string
  167. {
  168. $url = Common::url('/action/service', $this->options->index);
  169. if (defined('__TYPECHO_SERVICE_URL__')) {
  170. $rootPath = rtrim(parse_url($this->options->rootUrl, PHP_URL_PATH), '/');
  171. $path = parse_url($url, PHP_URL_PATH);
  172. $parts = parse_url(__TYPECHO_SERVICE_URL__);
  173. if (
  174. !empty($parts['path'])
  175. && $parts['path'] != '/'
  176. && rtrim($parts['path'], '/') != $rootPath
  177. ) {
  178. $path = Common::url($path, $parts['path']);
  179. }
  180. $parts['path'] = $path;
  181. $url = Common::buildUrl($parts);
  182. }
  183. return $url . '?do=' . $do;
  184. }
  185. /**
  186. * 请求异步服务
  187. *
  188. * @param $method
  189. * @param mixed $params
  190. */
  191. public function requestService($method, $params = null)
  192. {
  193. static $called;
  194. if (!$called) {
  195. Response::getInstance()->addResponder(function () {
  196. if (!empty($this->asyncRequests) && $client = Client::get()) {
  197. try {
  198. $client->setHeader('User-Agent', $this->options->generator)
  199. ->setTimeout(2)
  200. ->setJson([
  201. 'requests' => $this->asyncRequests,
  202. 'token' => Common::timeToken($this->options->secret)
  203. ])
  204. ->send($this->getServiceUrl('async'));
  205. } catch (Client\Exception $e) {
  206. return;
  207. }
  208. }
  209. });
  210. $called = true;
  211. }
  212. $this->asyncRequests[] = [$method, $params];
  213. }
  214. /**
  215. * 执行回调
  216. *
  217. * @throws Exception
  218. */
  219. public function asyncHandle()
  220. {
  221. /** 验证权限 */
  222. $data = $this->request->get('@json');
  223. $token = $data['token'] ?? '';
  224. if (!Common::timeTokenValidate($token, $this->options->secret, 3)) {
  225. throw new Exception(_t('禁止访问'), 403);
  226. }
  227. /** 忽略超时 */
  228. if (function_exists('ignore_user_abort')) {
  229. ignore_user_abort(true);
  230. }
  231. if (function_exists('set_time_limit')) {
  232. set_time_limit(30);
  233. }
  234. $requests = $data['requests'] ?? null;
  235. $plugin = self::pluginHandle();
  236. if (!empty($requests)) {
  237. foreach ($requests as $request) {
  238. [$method, $params] = $request;
  239. $plugin->{$method}($params);
  240. }
  241. }
  242. }
  243. /**
  244. * 异步请求入口
  245. */
  246. public function action()
  247. {
  248. $this->on($this->request->isPost() && $this->request->is('do=ping'))->sendPingHandle();
  249. $this->on($this->request->isPost() && $this->request->is('do=async'))->asyncHandle();
  250. }
  251. }