/** * 激活插件方法,如果激活失败,直接抛出异常 * * @access public * @return void * @throws Typecho_Plugin_Exception */ public static function activate() { if (false == Typecho_Http_Client::get()) { throw new Typecho_Plugin_Exception(_t('对不起, 您的主机不支持 php-curl 扩展而且没有打开 allow_url_fopen 功能, 无法正常使用此功能')); } Typecho_Plugin::factory('admin/write-post.php')->bottom_20 = array('BaiduSlug_Plugin', 'ajax'); Typecho_Plugin::factory('admin/write-page.php')->bottom_20 = array('BaiduSlug_Plugin', 'ajax'); Helper::addAction('baidu-slug', 'BaiduSlug_Action'); return _t('请配置此插件的API KEY, 以使您的插件生效'); }
/** * 远程请求代理 * * @access public * @return void */ public function feed() { $this->user->pass('subscriber'); $client = Typecho_Http_Client::get(); if ($client) { $client->setHeader('User-Agent', $this->options->generator)->send('http://typecho.org/feed/'); /** 匹配内容体 */ $response = $client->getResponseBody(); preg_match_all("/<item>\\s*<title>([^>]*)<\\/title>\\s*<link>([^>]*)<\\/link>\\s*<guid>[^>]*<\\/guid>\\s*<pubDate>([^>]*)<\\/pubDate>/is", $response, $matches); $data = array(); if ($matches) { foreach ($matches[0] as $key => $val) { $data[] = array('title' => $matches[1][$key], 'link' => $matches[2][$key], 'date' => Typecho_I18n::dateWord(strtotime($matches[3][$key]), $this->options->gmtTime + $this->options->timezone)); if ($key > 3) { break; } } } if (!empty($data)) { Typecho_Cookie::set('__typecho_feed', Typecho_Json::encode($data)); } $this->response->throwJson($data); return; } throw new Typecho_Widget_Exception(_t('禁止访问'), 403); }
/** * 激活插件方法,如果激活失败,直接抛出异常 * * @access public * @return void * @throws Typecho_Plugin_Exception */ public static function activate() { if (false == Typecho_Http_Client::get()) { throw new Typecho_Plugin_Exception(_t('对不起, 您的主机不支持 php-curl 扩展而且没有打开 allow_url_fopen 功能, 无法正常使用此功能')); } Typecho_Plugin::factory('admin/menu.php')->navBar = array('Qiniu_Plugin', 'render'); }
/** * 激活插件方法,如果激活失败,直接抛出异常 * * @access public * @return void * @throws Typecho_Plugin_Exception */ public static function activate() { if (false == Typecho_Http_Client::get()) { throw new Typecho_Plugin_Exception(_t('对不起, 您的主机不支持 php-curl 扩展而且没有打开 allow_url_fopen 功能, 无法正常使用此功能')); } Helper::addAction('googlecode-svn', 'GoogleCodeSVN_Action'); return _t('请在插件设置里设置 Google Code 的SVN参数') . $error; }
/** * 发送API请求 * * @access public * @param string $url 请求地址 * @return array */ public function translate($url) { $client = Typecho_Http_Client::get(); $client->setTimeout(50)->send($url); if (200 === $client->getResponseStatus()) { return Json::decode($client->getResponseBody(), true); } }
/** * 激活插件方法,如果激活失败,直接抛出异常 * * @access public * @return void * @throws Typecho_Plugin_Exception */ public static function activate() { if (false == Typecho_Http_Client::get()) { throw new Typecho_Plugin_Exception(_t('对不起, 您的主机不支持 php-curl 扩展而且没有打开 allow_url_fopen 功能, 无法正常使用此功能')); } Helper::addAction(github_git, 'GitHubGit_Action'); return _t('安装成功') . $error; }
private function parseFileName($fileName, $repositoryPath) { $result = array('do' => 'publish', 'allowComment' => $this->options->defaultAllowComment, 'allowPing' => $this->options->defaultAllowPing, 'allowFeed' => $this->options->defaultAllowFeed); $basePath = Helper::options()->plugin('GoogleCodeSVN')->basePath; $basePath = '/' . trim($basePath, '/') . '/'; if (0 !== strpos($fileName, $basePath)) { return false; } $path = substr($fileName, strlen($basePath)); $part = explode('/', $path); if (2 != count($part)) { return false; } list($categoryName, $baseName) = $part; list($slug) = explode('.', $baseName); $result['slug'] = $slug; $post = $this->db->fetchRow($this->db->select()->from('table.contents')->where('slug = ?', $slug)->limit(1)); if (!empty($post)) { if ('post' != $post['type']) { return false; } else { $result['cid'] = $post['cid']; } } /** 将目录作为分类缩略名处理 */ $categorySlug = Typecho_Common::slugName($categoryName); $category = $this->db->fetchRow($this->db->select()->from('table.metas')->where('slug = ? OR name = ?', $categorySlug, $categoryName)->where('type = ?', 'category')->limit(1)); /** 如果分类不存在则直接重建分类 */ if (empty($category)) { $input['name'] = $categoryName; $input['slug'] = $categorySlug; $input['type'] = 'category'; $input['description'] = $categoryName; $input['do'] = 'insert'; $this->widget('Widget_Metas_Category_Edit', NULL, $input, false)->action(); $result['category'] = array($this->widget('Widget_Notice')->getHighlightId()); } else { $result['category'] = array($category['mid']); } $url = rtrim($repositoryPath, '/') . $fileName; $client = Typecho_Http_Client::get('Curl', 'Socket'); if (false == $client) { return false; } $client->send($url); $result['text'] = ''; $result['title'] = ''; if (200 == $client->getResponseStatus() || 304 == $client->getResponseStatus()) { $response = trim($client->getResponseBody()); list($title, $text) = explode("\n", $response, 2); $result['title'] = $title; $result['text'] = $text; } return $result; }
public function __construct($shortName = null, $secret = null, $jwt = null) { $this->shortName = $shortName; $this->secret = $secret; $this->jwt = $jwt; $this->generator = Typecho_Widget::widget('Widget_Options')->generator; $this->http = Typecho_Http_Client::get(); $this->userAgent = $this->generator . '|Duoshuo/' . Duoshuo_Typecho::VERSION; $this->plugin = Duoshuo_Typecho::getInstance(); if ($this->plugin->getPlugOption('end_point') !== NULL) { $this->end_point = Duoshuo_Typecho::$PointMap[intval($this->plugin->getPlugOption('end_point'))]; } }
/** * 远程请求代理 * * @throws Typecho_Widget_Exception */ public function feed() { $this->user->pass('subscriber'); $client = Typecho_Http_Client::get(); if ($client) { $client->setHeader('User-Agent', $this->options->generator)->setTimeout(10)->send('http://www.sisome.com/feed/go/sisome/'); /** 匹配内容体 */ $response = $client->getResponseBody(); preg_match_all("/<item>\\s*<title>([^>]*)<\\/title>\\s*<link>([^>]*)<\\/link>\\s*<guid>[^>]*<\\/guid>\\s*<pubDate>([^>]*)<\\/pubDate>/is", $response, $matches); $data = array(); if ($matches) { foreach ($matches[0] as $key => $val) { $data[] = array('title' => $matches[1][$key], 'link' => $matches[2][$key], 'date' => date('n.j', strtotime($matches[3][$key]))); if ($key > 8) { break; } } } $this->response->throwJson($data); return; } throw new Typecho_Widget_Exception(_t('禁止访问'), 403); }
/** * 发送pingback * <code> * $this->sendPingbacks(365); * </code> * * @access public * @param integer $cid 内容id * @param array $trackback trackback的url * @return void */ public function sendPing($cid, array $trackback = NULL) { $this->user->pass('contributor'); if ($client = Typecho_Http_Client::get()) { try { $input = array('do' => 'ping', 'cid' => $cid); if (!empty($trackback)) { $input['trackback'] = $trackback; } $client->setCookie('__typecho_uid', Typecho_Cookie::get('__typecho_uid'), 0, $this->options->siteUrl)->setCookie('__typecho_authCode', Typecho_Cookie::get('__typecho_authCode'), 0, $this->options->siteUrl)->setHeader('User-Agent', $this->options->generator)->setTimeout(3)->setData($input)->setIp('127.0.0.1')->send(Typecho_Common::url('/action/service', $this->options->index)); } catch (Typecho_Http_Client_Exception $e) { return; } } }
/** * 发送数据 * @param $url 准备发送的url * @param $group 分组信息 */ public static function post($url, $group = null) { $options = Helper::options(); //获取API $api = $options->plugin('BaiduSubmit')->api; //准备数据 if (is_array($url)) { $urls = $url; } else { $urls = array($url); } //日志信息 $log['subject'] = '我'; $log['action'] = '发送'; $log['object'] = 'URL'; if ($group) { $log['more']['group'] = $group; } $log['more']['url'] = $urls; try { //为了保证成功调用,老高先做了判断 if (false == Typecho_Http_Client::get()) { throw new Typecho_Plugin_Exception(_t('对不起, 您的主机不支持 php-curl 扩展而且没有打开 allow_url_fopen 功能, 无法正常使用此功能')); } //发送请求 $http = Typecho_Http_Client::get(); $http->setData(implode("\n", $urls)); $http->setHeader('Content-Type', 'text/plain'); $json = $http->send($api); $return = json_decode($json, 1); $log['more']['info'] = $return; if (isset($return['error'])) { $log['result'] = '失败'; } else { $log['result'] = '成功'; } } catch (Typecho_Exception $e) { $log['more']['info'] = $e->getMessage(); $log['result'] = '失败'; } self::logger($log); }
/** * 评论过滤器 * * @access public * @param array $comment 评论结构 * @param Typecho_Widget $post 被评论的文章 * @param array $result 返回的结果上下文 * @param string $api api地址 * @return void */ public static function filter($comment, $post, $result, $api = 'comment-check') { $comment = empty($result) ? $comment : $result; $options = Typecho_Widget::widget('Widget_Options'); $url = $options->plugin('Akismet')->url; $key = $options->plugin('Akismet')->key; $allowedServerVars = 'comment-check' == $api ? array('SCRIPT_URI', 'HTTP_HOST', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_ACCEPT_ENCODING', 'HTTP_ACCEPT_CHARSET', 'HTTP_KEEP_ALIVE', 'HTTP_CONNECTION', 'HTTP_CACHE_CONTROL', 'HTTP_PRAGMA', 'HTTP_DATE', 'HTTP_EXPECT', 'HTTP_MAX_FORWARDS', 'HTTP_RANGE', 'CONTENT_TYPE', 'CONTENT_LENGTH', 'SERVER_SIGNATURE', 'SERVER_SOFTWARE', 'SERVER_NAME', 'SERVER_ADDR', 'SERVER_PORT', 'REMOTE_PORT', 'GATEWAY_INTERFACE', 'SERVER_PROTOCOL', 'REQUEST_METHOD', 'QUERY_STRING', 'REQUEST_URI', 'SCRIPT_NAME', 'REQUEST_TIME') : array(); $data = array('blog' => $options->siteUrl, 'user_ip' => $comment['ip'], 'user_agent' => $comment['agent'], 'referrer' => Typecho_Request::getInstance()->getReferer(), 'permalink' => $post->permalink, 'comment_type' => $comment['type'], 'comment_author' => $comment['author'], 'comment_author_email' => $comment['mail'], 'comment_author_url' => $comment['url'], 'comment_content' => $comment['text']); foreach ($allowedServerVars as $val) { if (array_key_exists($val, $_SERVER)) { $data[$val] = $_SERVER[$val]; } } try { $client = Typecho_Http_Client::get(); if (false != $client && $key) { $params = parse_url($url); $url = $params['scheme'] . '://' . $key . '.' . $params['host'] . (isset($params['path']) ? $params['path'] : NULL); $client->setHeader('User-Agent', $options->generator . ' | Akismet/1.1')->setTimeout(5)->setData($data)->send(Typecho_Common::url('/1.1/' . $api, $url)); if ('true' == $client->getResponseBody()) { $comment['status'] = 'spam'; } } } catch (Typecho_Http_Client_Exception $e) { //do nothing error_log($e->getMessage()); } return $comment; }
/** * 请求 * * @param string $url */ public function http($url) { $client = Typecho_Http_Client::get(); $userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53'; /* 设置Cookie */ if (static::$token) { $client->setHeader('Cookie', '_xiamitoken=' . static::$token . '; visit=1'); } $client->setHeader('User-Agent', $userAgent)->setHeader('Proxy-Connection', 'keep-alive')->setHeader('X-Requested-With', 'XMLHttpRequest')->setHeader('X-FORWARDED-FOR', '42.156.140.238')->setHeader('CLIENT-IP', '42.156.140.238')->setHeader('Referer', 'http://m.xiami.com')->setTimeout(50)->send($url); if (200 === $client->getResponseStatus()) { /* 获取token时只返回头信息的Cookie */ if ($this->isCookie) { $responseCookie = $client->getResponseHeader('set-cookie'); $cookies = explode(';', $responseCookie); return $cookies; } $response = Json::decode($client->getResponseBody(), true); if (isset($response['status']) && 'ok' == $response['status'] && !empty($response['data'])) { return $response['data']; } return; } return; }
/** * 执行请求 * * @access public * @return void */ public function __rpcCall() { $args = func_get_args(); $method = array_shift($args); $request = new IXR_Request($method, $args); $xml = $request->getXml(); $client = Typecho_Http_Client::get(); if (!$client) { $this->error = new IXR_Error(-32300, 'transport error - could not open socket'); return false; } $client->setHeader('Content-Type', 'text/xml')->setHeader('User-Agent', $this->useragent)->setData($xml)->send($this->url); $contents = $client->getResponseBody(); if ($this->debug) { echo '<pre>' . htmlspecialchars($contents) . "\n</pre>\n\n"; } // Now parse what we've got back $this->message = new IXR_Message($contents); if (!$this->message->parse()) { // XML error $this->error = new IXR_Error(-32700, 'parse error. not well formed'); return false; } // Is the message a fault? if ($this->message->messageType == 'fault') { $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString); return false; } // Message must be OK return true; }
/** * 请求 * * @param string $url */ public function http($url) { $client = Typecho_Http_Client::get(); $client->setHeader('Cookie', 'appver=2.0.2')->setHeader('Referer', 'http://music.163.com')->setTimeout(20)->send($url); if (200 === $client->getResponseStatus()) { $response = Json::decode($client->getResponseBody(), true); if (200 === $response['code']) { unset($response['code']); return $response; } return; } return; }
/** * pingbackPing * * @param string $source * @param string $target * @access public * @return void */ public function pingbackPing($source, $target) { /** 检查源地址是否存在*/ if (!($http = Typecho_Http_Client::get())) { return new IXR_Error(16, _t('源地址服务器错误')); } try { $http->setTimeout(5)->send($source); $response = $http->getResponseBody(); if (200 == $http->getResponseStatus()) { if (!$http->getResponseHeader('x-pingback')) { preg_match_all("/<link[^>]*rel=[\"']([^\"']*)[\"'][^>]*href=[\"']([^\"']*)[\"'][^>]*>/i", $response, $out); if (!isset($out[1]['pingback'])) { return new IXR_Error(50, _t('源地址不支持PingBack')); } } } else { return new IXR_Error(16, _t('源地址服务器错误')); } } catch (Exception $e) { return new IXR_Error(16, _t('源地址服务器错误')); } /** 检查目标地址是否正确*/ $pathInfo = Typecho_Common::url(substr($target, strlen($this->options->index)), '/'); $post = Typecho_Router::match($pathInfo); /** 这样可以得到cid或者slug*/ if (!$post instanceof Widget_Archive || !$post->have() || !$post->is('single')) { return new IXR_Error(33, _t('这个目标地址不存在')); } if ($post) { /** 检查是否可以ping*/ if ($post->allowPing) { /** 现在可以ping了,但是还得检查下这个pingback是否已经存在了*/ $pingNum = $this->db->fetchObject($this->db->select(array('COUNT(coid)' => 'num'))->from('table.comments')->where('table.comments.cid = ? AND table.comments.url = ? AND table.comments.type <> ?', $post->cid, $source, 'comment'))->num; if ($pingNum <= 0) { /** 现在开始插入以及邮件提示了 $response就是第一行请求时返回的数组*/ preg_match("/\\<title\\>([^<]*?)\\<\\/title\\>/is", $response, $matchTitle); $finalTitle = Typecho_Common::removeXSS(trim(strip_tags($matchTitle[1]))); /** 干掉html tag,只留下<a>*/ $text = Typecho_Common::stripTags($response, '<a href="">'); /** 此处将$target quote,留着后面用*/ $pregLink = preg_quote($target); /** 找出含有target链接的最长的一行作为$finalText*/ $finalText = ''; $lines = explode("\n", $text); foreach ($lines as $line) { $line = trim($line); if (NULL != $line) { if (preg_match("|<a[^>]*href=[\"']{$pregLink}[\"'][^>]*>(.*?)</a>|", $line)) { if (strlen($line) > strlen($finalText)) { /** <a>也要干掉,*/ $finalText = Typecho_Common::stripTags($line); } } } } /** 截取一段字*/ if (NULL == trim($finalText)) { return new IXR_Error('17', _t('源地址中不包括目标地址')); } $finalText = '[...]' . Typecho_Common::subStr($finalText, 0, 200, '') . '[...]'; $pingback = array('cid' => $post->cid, 'created' => $this->options->gmtTime, 'agent' => $this->request->getAgent(), 'ip' => $this->request->getIp(), 'author' => $finalTitle, 'url' => Typecho_Common::safeUrl($source), 'text' => $finalText, 'ownerId' => $post->author->uid, 'type' => 'pingback', 'status' => $this->options->commentsRequireModeration ? 'waiting' : 'approved'); /** 加入plugin */ $pingback = $this->pluginHandle()->pingback($pingback, $post); /** 执行插入*/ $insertId = $this->singletonWidget('Widget_Abstract_Comments')->insert($pingback); /** 评论完成接口 */ $this->pluginHandle()->finishPingback($this); return $insertId; /** todo:发送邮件提示*/ } else { return new IXR_Error(48, _t('PingBack已经存在')); } } else { return IXR_Error(49, _t('目标地址禁止Ping')); } } else { return new IXR_Error(33, _t('这个目标地址不存在')); } }
/** * 检测是否可以rewrite * * @access public * @param string $value 是否打开rewrite * @return void */ public function checkRewrite($value) { if ($value) { $this->user->pass('administrator'); /** 首先直接请求远程地址验证 */ $client = Typecho_Http_Client::get(); $hasWrote = false; if (!file_exists(__TYPECHO_ROOT_DIR__ . '/.htaccess') && !Typecho_Common::isAppEngine()) { if (is_writeable(__TYPECHO_ROOT_DIR__)) { $parsed = parse_url($this->options->siteUrl); $basePath = empty($parsed['path']) ? '/' : $parsed['path']; $basePath = rtrim($basePath, '/') . '/'; $hasWrote = file_put_contents(__TYPECHO_ROOT_DIR__ . '/.htaccess', "<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase {$basePath}\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.*)\$ {$basePath}index.php/\$1 [L]\n</IfModule>"); } } try { if ($client) { /** 发送一个rewrite地址请求 */ $client->setData(array('do' => 'remoteCallback'))->setHeader('User-Agent', $this->options->generator)->send(Typecho_Common::url('/action/ajax', $this->options->siteUrl)); if (200 == $client->getResponseStatus() && 'OK' == $client->getResponseBody()) { return true; } } if (false !== $hasWrote) { @unlink(__TYPECHO_ROOT_DIR__ . '/.htaccess'); //增强兼容性,使用wordpress的redirect式rewrite规则,虽然效率有点地下,但是对fastcgi模式兼容性较好 $hasWrote = file_put_contents(__TYPECHO_ROOT_DIR__ . '/.htaccess', "<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase {$basePath}\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . {$basePath}index.php [L]\n</IfModule>"); //再次进行验证 $client = Typecho_Http_Client::get(); if ($client) { /** 发送一个rewrite地址请求 */ $client->setData(array('do' => 'remoteCallback'))->setHeader('User-Agent', $this->options->generator)->send(Typecho_Common::url('/action/ajax', $this->options->siteUrl)); if (200 == $client->getResponseStatus() && 'OK' == $client->getResponseBody()) { return true; } } unlink(__TYPECHO_ROOT_DIR__ . '/.htaccess'); } } catch (Typecho_Http_Client_Exception $e) { if (false !== $hasWrote) { @unlink(__TYPECHO_ROOT_DIR__ . '/.htaccess'); } return false; } return false; } else { if (file_exists(__TYPECHO_ROOT_DIR__ . '/.htaccess')) { @unlink(__TYPECHO_ROOT_DIR__ . '/.htaccess'); } } return true; }
public static function stat_report() { if (!isset(self::$_cache[0]["stat_report"]) || self::$_time - self::$_cache[0]["stat_report"] > 86400) { try { @ignore_user_abort(); @ob_flush(); $statSuccess = false; $client = Typecho_Http_Client::get(); if ($client) { @$client->setHeader('User-Agent', self::$_options->generator)->setTimeout(10)->setData(array("meta" => @Json::encode(self::$_options->stack[0])))->send('http://my-typecho.tk/report/index.php'); $res = @$client->getResponseBody(); if (!empty($res) && stripos($res, "OK") !== false) { $statSuccess = true; } } else { $statSuccess = true; } if ($statSuccess) { self::setcache("stat_report", self::$_time); } } catch (Exception $e) { } } }