From 1689917714e86a8f9f28a9b4c48232c18b5851c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BE=BD=E4=B8=AD?= Date: Wed, 22 Jul 2020 16:26:16 +0800 Subject: [PATCH] Squashed 'AMP/' changes from a3e75db..f9d751b MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit f9d751b Fix 4dc3488 增加版本检查,修改sitemap分页数量。 df7e1aa Fix XiongZhangHao, fixes #39. 去除已下线的熊掌号相关功能,将自动提交和批量提交功能修改为 提交到快速收录接口和普通收录接口。 版本更新为0.7.6。 git-subtree-dir: AMP git-subtree-split: f9d751ba5fa8db916b803670f15387c668e1c376 --- Action.php | 306 ++++++++++++++++++++++++++++------------------------- Links.php | 76 +++++++------ Plugin.php | 40 ++++--- README.md | 76 +++++++------ 4 files changed, 268 insertions(+), 230 deletions(-) diff --git a/Action.php b/Action.php index ddaef72e..a650dfe9 100644 --- a/Action.php +++ b/Action.php @@ -13,7 +13,7 @@ public function __construct($request, $response, $params = NULL) parent::__construct($request, $response, $params); $this->LOGO = Helper::options()->plugin('AMP')->LOGO;//同时为默认图片 $this->db = Typecho_Db::get(); - $this->tablename = $this->db->getPrefix().'PageCache'; + $this->tablename = $this->db->getPrefix() . 'PageCache'; $this->baseurl = Helper::options()->index; $this->baseurl = str_replace("https://", "//", $this->baseurl); $this->baseurl = str_replace("http://", "//", $this->baseurl); @@ -29,7 +29,7 @@ public function __construct($request, $response, $params = NULL) public static function headlink() { $widget = Typecho_Widget::widget('Widget_Archive'); - $headurl='';//初始化输出内容 + $headurl = '';//初始化输出内容 if ($widget->is('index') and !isset($widget->request->page)) {//输出AMP首页 if (Helper::options()->plugin('AMP')->ampIndex == 1) { @@ -39,17 +39,17 @@ public static function headlink() } if ($widget->is('post')) {//文章页 - $targetTemp=Typecho_Widget::widget('AMP_Action')->getUrlRule();//静态函数调用动态函数 - if(isset($widget->request->cid)){ - $cid=$widget->request->cid; - $target = str_replace('[cid:digital]',$cid , $targetTemp); + $targetTemp = Typecho_Widget::widget('AMP_Action')->getUrlRule();//静态函数调用动态函数 + if (isset($widget->request->cid)) { + $cid = $widget->request->cid; + $target = str_replace('[cid:digital]', $cid, $targetTemp); } - if(isset($widget->request->slug)){ - $slug=$widget->request->slug; + if (isset($widget->request->slug)) { + $slug = $widget->request->slug; $target = str_replace('[slug]', $slug, $targetTemp); } - if(isset($target)){//输出文章页对应的AMP/MIP页面 + if (isset($target)) {//输出文章页对应的AMP/MIP页面 $ampurl = Typecho_Common::url("amp/{$target}", Helper::options()->index); $mipurl = Typecho_Common::url("mip/{$target}", Helper::options()->index); $headurl = "\n\n"; @@ -107,13 +107,13 @@ public function MIPsitemap() public function MIPpage() { $requestHash = $this->request->getPathinfo(); - $context=$this->get($requestHash); //查找是否已经缓存 + $context = $this->get($requestHash); //查找是否已经缓存 $this->article = $this->getArticle($this->request->target); if (isset($this->article['isblank'])) { throw new Typecho_Widget_Exception("不存在或已删除。返回首页"); } - if (Helper::options()->plugin('AMP')->OnlyForSpiders == 1){//判断是否是对应的爬虫来访 + if (Helper::options()->plugin('AMP')->OnlyForSpiders == 1) {//判断是否是对应的爬虫来访 $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']); $spider = strtolower('Baiduspider'); if (strpos($userAgent, $spider) == false) {//不是百度的蜘蛛 @@ -121,28 +121,28 @@ public function MIPpage() } } - if(!is_null($context)){//有缓存的情况直接输出 + if (!is_null($context)) {//有缓存的情况直接输出 print($context); - }else{//没缓存的生成页面再进行缓存 - $MIPpage=array( - 'title'=>$this->article['title'], - 'permalink'=>$this->article['permalink'], - 'mipurl'=>$this->article['mipurl'], - 'modified'=>date('Y-m-d\TH:i:s',$this->article['modified']), - 'date'=>$this->article['date']->format('Y-m-d\TH:i:s'), - 'isMarkdown'=>$this->article['isMarkdown'], - 'imgData'=>$this->GetPostImg(),//MIP页面的结果化数据可以没有图片 - 'APPID'=>Helper::options()->plugin('AMP')->baiduAPPID, - 'mip_stats_token'=> trim(Helper::options()->plugin('AMP')->mip_stats_token), - 'desc'=>self::cleanUp($this->article['text']), - 'publisher'=>Helper::options()->title, - 'MIPtext'=>$this->MIPInit($this->article['text']), - 'version'=>$this->version + } else {//没缓存的生成页面再进行缓存 + $MIPpage = array( + 'title' => $this->article['title'], + 'permalink' => $this->article['permalink'], + 'mipurl' => $this->article['mipurl'], + 'modified' => date('Y-m-d\TH:i:s', $this->article['modified']), + 'date' => $this->article['date']->format('Y-m-d\TH:i:s'), + 'isMarkdown' => $this->article['isMarkdown'], + 'imgData' => $this->GetPostImg(),//MIP页面的结果化数据可以没有图片 + 'APPID' => Helper::options()->plugin('AMP')->baiduAPPID,//熊掌号的APPID + 'mip_stats_token' => trim(Helper::options()->plugin('AMP')->mip_stats_token), + 'desc' => self::cleanUp($this->article['text']), + 'publisher' => Helper::options()->title, + 'MIPtext' => $this->MIPInit($this->article['text']), + 'version' => $this->version ); ob_start(); require_once('templates/MIPpage.php'); $cache = ob_get_contents(); - $this->set($requestHash,$cache); + $this->set($requestHash, $cache); } } @@ -183,16 +183,17 @@ public function AMPlist() ); } $arr = array('items' => $article_data); - header("Access-Control-Allow-Origin: *"); - print(json_encode($arr)); + header("Access-Control-Allow-Origin: *"); + print(json_encode($arr)); } - public function AMPindex(){ + public function AMPindex() + { if (Helper::options()->plugin('AMP')->ampIndex == 0) { header("Location: {$this->baseurl}"); } - require_once ('templates/AMPindex.php'); + require_once('templates/AMPindex.php'); } /** @@ -205,49 +206,47 @@ public function AMPindex(){ public function AMPpage() { $requestHash = $this->request->getPathinfo(); - $context=$this->get($requestHash); //查找是否已经缓存 + $context = $this->get($requestHash); //查找是否已经缓存 $this->article = $this->getArticle($this->request->target); if (isset($this->article['isblank'])) { throw new Typecho_Widget_Exception('不存在或已删除'); } - if (Helper::options()->plugin('AMP')->OnlyForSpiders == 1){//判断是否是对应的爬虫来访 + if (Helper::options()->plugin('AMP')->OnlyForSpiders == 1) {//判断是否是对应的爬虫来访 $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']); $spider = strtolower('Googlebot'); $spider2 = strtolower('google-amphtml'); - if (strpos($userAgent, $spider) == false or strpos($userAgent, $spider2) == false) {//不是Google的蜘蛛 + if (strpos($userAgent, $spider) == false or strpos($userAgent, $spider2) == false) {//不是Google的蜘蛛 header("Location: {$this->article['permalink']}"); } } - if(!is_null($context)){//有缓存的情况直接输出 + if (!is_null($context)) {//有缓存的情况直接输出 print($context); - } - else{ - $AMPpage=array( - 'title'=>$this->article['title'], - 'permalink'=>$this->article['permalink'], - 'mipurl'=>$this->article['mipurl'], - 'modified'=>date('F j, Y',$this->article['modified']), - 'date'=>$this->article['date']->format('F j, Y'), - 'author'=>$this->article['author'], - 'LOGO'=>$this->LOGO, - 'isMarkdown'=>$this->article['isMarkdown'], - 'imgData'=>$this->GetPostImg(), - 'APPID'=>Helper::options()->plugin('AMP')->baiduAPPID, - 'desc'=>self::cleanUp($this->article['text']), - 'publisher'=>Helper::options()->title, - 'AMPtext'=>$this->AMPInit($this->article['text']), - 'version'=>$this->version + } else { + $AMPpage = array( + 'title' => $this->article['title'], + 'permalink' => $this->article['permalink'], + 'mipurl' => $this->article['mipurl'], + 'modified' => date('F j, Y', $this->article['modified']), + 'date' => $this->article['date']->format('F j, Y'), + 'author' => $this->article['author'], + 'LOGO' => $this->LOGO, + 'isMarkdown' => $this->article['isMarkdown'], + 'imgData' => $this->GetPostImg(), + 'desc' => self::cleanUp($this->article['text']), + 'publisher' => Helper::options()->title, + 'AMPtext' => $this->AMPInit($this->article['text']), + 'version' => $this->version ); //AMP页面的结果化数据必须有图片 - if(!is_array($AMPpage['imgData'])){ - $AMPpage['imgData']=self::getSizeArr($AMPpage['LOGO'],'1200','1200');//如果找不到图片就用LOGO + if (!is_array($AMPpage['imgData'])) { + $AMPpage['imgData'] = self::getSizeArr($AMPpage['LOGO'], '1200', '1200');//如果找不到图片就用LOGO } ob_start(); - require_once ('templates/AMPpage.php'); + require_once('templates/AMPpage.php'); $cache = ob_get_contents(); - $this->set($requestHash,$cache); + $this->set($requestHash, $cache); } } @@ -257,9 +256,10 @@ public function AMPpage() * date: 2020/3/13 11:44 * 清理缓存 */ - public function cleancache(){ + public function cleancache() + { $user = Typecho_Widget::widget('Widget_User'); - if(!$user->pass('administrator')){ + if (!$user->pass('administrator')) { die('未登录用户!'); } $this->del('*'); @@ -286,50 +286,61 @@ public static function sendRealtime($contents, $class) } //如果没有开启自动提交功能 则不推送 - if ($options->plugin('AMP')->mipAutoSubmit == 0) { + $mipAutoSubmit = $options->plugin('AMP')->mipAutoSubmit; + if ($mipAutoSubmit == 0) { return; } //判断是否配置相关信息 - if (is_null($options->plugin('AMP')->baiduAPPID) or is_null($options->plugin('AMP')->baiduTOKEN)) { - throw new Typecho_Plugin_Exception(_t('参数未正确配置,自动提交失败')); - }else{ - $appid = trim($options->plugin('AMP')->baiduAPPID);//过滤空格 - $token = trim($options->plugin('AMP')->baiduTOKEN);//过滤空格 - $api = "http://data.zz.baidu.com/urls?appid={$appid}&token={$token}&type=realtime";//构建实时提交的地址 +// if (is_null($options->plugin('AMP')->baiduAPPID) or is_null($options->plugin('AMP')->baiduTOKEN)) { + if (is_null($options->plugin('AMP')->baiduAPI)) { + throw new Typecho_Plugin_Exception(_t('未配置 快速收录接口地址,自动提交失败')); + } else { +// $appid = trim($options->plugin('AMP')->baiduAPPID);//过滤空格 +// $token = trim($options->plugin('AMP')->baiduTOKEN);//过滤空格 + //熊掌号下线后,修改未快速收录接口 2020.06.07 + + $api = trim($options->plugin('AMP')->baiduAPI);//默认填写的是快速收录地址 + if ($mipAutoSubmit == 2) {//如果选择了普通收录地址,则进行替换 + $api = preg_replace("/&type=[a-z]+/", "", $api);//将快速收录接口换成普通收录接口 + } } $article = Typecho_Widget::widget('AMP_Action')->getArticleByCid($class->cid);//根据cid获取文章内容 - - if((int)$article['created']+86400 < (int)$article['modified'] ){//之前判断忽略了自动保存草稿的问题 + if ((int)$article['created'] + 86400 < (int)$article['modified']) {//之前判断忽略了自动保存草稿的问题 return;//草稿在一天之内的文章推送,否则不推送。 } - $url=$article['mipurl']; + + //获取文章链接 + $url = $article['mipurl']; $hash = array(//发布之前清除对应的MIP/AMP缓存 'mip' => str_replace(Helper::options()->index, "", $article['mipurl']), 'amp' => str_replace(Helper::options()->index, "", $article['ampurl']) ); + Typecho_Widget::widget('AMP_Action')->del($hash); - //发送自动提交请求 - $http = Typecho_Http_Client::get(); - $http->setData($url); - $http->setHeader('Content-Type', 'text/plain'); + //发送自动提交 try { - $result = $http->send($api); + $http = Typecho_Http_Client::get(); + $http->setData($url);//改为Post发送模式 + $http->setHeader('Content-Type', 'text/plain'); + + $result = $http->send($api); $json = json_decode($result); - if(isset($json->error)){//提交出错时返回错误信息 - throw new Typecho_Plugin_Exception(_t("错误代码:".$json->error."
出错原因:".$json->message),$json->error); + + if (isset($json->error)) {//提交出错时返回错误信息 + throw new Typecho_Plugin_Exception(_t("错误代码:" . $json->error . "
出错原因:" . $json->message), $json->error); } } catch (Exception $e) { @@ -375,9 +386,9 @@ private function ArticleBase($select) ->where('uid = ?', $article['authorId']); $author = $this->db->fetchRow($select); $article['author'] = $author['screenName']; - if($article['isMarkdown']==True){ + if ($article['isMarkdown'] == True) { $article['text'] = Markdown::convert($article['text']); - }else{ + } else { $article['text'] = Typecho_Widget::widget("Widget_Abstract_Contents")->autoP($article['text']); } $targetTemp = $this->getUrlRule(); @@ -401,7 +412,7 @@ private function ArticleBase($select) public function MakeArticleList($linkType = 'amp', $page = 0, $pageSize = 0) { $db = Typecho_Db::get(); - $thismoment=time();//Fix sqlite不支持生成时间戳 + $thismoment = time();//Fix sqlite不支持生成时间戳 $sql = $db->select()->from('table.contents') ->where('table.contents.status = ?', 'publish') ->where('table.contents.type = ?', 'post') @@ -419,7 +430,7 @@ public function MakeArticleList($linkType = 'amp', $page = 0, $pageSize = 0) $targetTemp = $this->getUrlRule(); - foreach ($articles AS $article) { + foreach ($articles as $article) { $article['categories'] = $db->fetchAll($db->select()->from('table.metas') ->join('table.relationships', 'table.relationships.mid = table.metas.mid') ->where('table.relationships.cid = ?', $article['cid']) @@ -467,21 +478,21 @@ private function GetPostImg() $img_url = $img[1]; } else { //正文里没找到图片就去附件里找 - $attsrc=Typecho_Widget::widget('Widget_Contents_Attachment_Related', 'parentId=' . $this->article['cid'])->stack; - $att=''; - foreach ($attsrc as $attimg){ - $att=$att.$attimg['text']; + $attsrc = Typecho_Widget::widget('Widget_Contents_Attachment_Related', 'parentId=' . $this->article['cid'])->stack; + $att = ''; + foreach ($attsrc as $attimg) { + $att = $att . $attimg['text']; } if (preg_match($pattern, $att, $img)) {//附件里只需要匹配img标签的内容 preg_match("/(?:\()(.*)(?:\))/i", $img[0], $result); $img_url = $img[1]; - }else{//附件里再找不到就调LOGO了 + } else {//附件里再找不到就调LOGO了 // $img_url = $this->defaultPIC; - $img_url=null;//熊掌号修改了规则,如果图不对文的话会被惩罚,所以没有图片则不出图 + $img_url = null;//熊掌号修改了规则,如果图不对文的话会被惩罚,所以没有图片则不出图 } } - if(is_null($img_url)){//如果没有找到图片则返回空 + if (is_null($img_url)) {//如果没有找到图片则返回空 return null; } else {//如果找到文章图片则返回图片数组 return self::getSizeArr($img_url); @@ -489,7 +500,8 @@ private function GetPostImg() } //获取图片尺寸 - private static function getSizeArr($img_url,$width='700',$height='400'){ + private static function getSizeArr($img_url, $width = '700', $height = '400') + { try {//尝试获取图片尺寸 list($width, $height, $type, $attr) = @getimagesize($img_url); $imgData = array( @@ -520,7 +532,7 @@ private function MIPInit($text) $text = str_replace('', '', $text); $text = str_replace('stripHtmlTags(array('font','color','input','size'),$text,true) ;//清理指定HTML标签 + $text = $this->stripHtmlTags(array('font', 'color', 'input', 'size'), $text, true);//清理指定HTML标签 return $text; } @@ -535,7 +547,7 @@ private function AMPInit($text) $text = str_replace('', '', $text); $text = str_replace('javascript:content_index_toggleToc()', '#', $text); - $text = $this->stripHtmlTags(array('font','color','input','size'),$text,true) ;//清理指定HTML标签 + $text = $this->stripHtmlTags(array('font', 'color', 'input', 'size'), $text, true);//清理指定HTML标签 return $text; } @@ -569,7 +581,7 @@ function ($m) { return $html; } - /** + /** * @param $text * @return string|string[] * author:Holmesian @@ -579,12 +591,11 @@ function ($m) { private function closeTags($text) { preg_match_all('//', $text, $mat); - $src=array_unique($mat[0]); - for ($i = 0; $i < count($src); $i++) - { - if (isset($src[$i])){ - $plus = $src[$i].''; - $text = str_replace( $mat[0][$i],$plus, $text); + $src = array_unique($mat[0]); + for ($i = 0; $i < count($src); $i++) { + if (isset($src[$i])) { + $plus = $src[$i] . ''; + $text = str_replace($mat[0][$i], $plus, $text); } } return $text; @@ -602,15 +613,15 @@ private function MakeSiteMap($maptype = 'amp') //changefreq -> always、hourly、daily、weekly、monthly、yearly、never //priority -> 0.0优先级最低、1.0最高 $root_url = Helper::options()->rootUrl; - if (isset($_GET['page'])){//Sitemap分页 + if (isset($_GET['page'])) {//Sitemap分页 - $page=$_GET['page']; - }else{ - $page=1; + $page = $_GET['page']; + } else { + $page = 1; } if (isset($_GET['txt'])) {//增加纯文本地址列表 - $articles = $this->MakeArticleList($maptype,$page,5000); - foreach ($articles AS $article) { + $articles = $this->MakeArticleList($maptype, $page, 1000); + foreach ($articles as $article) { echo $article['permalink'] . "\n\r
"; } } else { @@ -623,8 +634,8 @@ private function MakeSiteMap($maptype = 'amp') echo "\t\tdaily\n"; echo "\t\t1\n"; echo "\t\n"; - $articles = $this->MakeArticleList($maptype,$page,5000); - foreach ($articles AS $article) { + $articles = $this->MakeArticleList($maptype, $page, 1000); + foreach ($articles as $article) { echo "\t\n"; echo "\t\t" . $article['permalink'] . "\n"; echo "\t\t" . date('Y-m-d', $article['modified']) . "\n"; @@ -638,13 +649,12 @@ private function MakeSiteMap($maptype = 'amp') } - /** * 截取功能函数 - * @param string $text 截取的对象 - * @param string $length 保留长度 - * @param string $replace 替换结尾表示 - * @param string $encoding 编码类型 + * @param string $text 截取的对象 + * @param string $length 保留长度 + * @param string $replace 替换结尾表示 + * @param string $encoding 编码类型 * @return mixed */ @@ -658,22 +668,22 @@ private function substrFormat($text, $length, $replace = '...', $encoding = 'UTF /** * 清理指定HTML标签函数 - * @param array $tags 删除的标签 array('font','color','input','size') - * @param string $str html字符串 - * @param bool $type 是否保留标签的内容 + * @param array $tags 删除的标签 array('font','color','input','size') + * @param string $str html字符串 + * @param bool $type 是否保留标签的内容 * @return mixed */ - private function stripHtmlTags($tags, $str, $content=false) + private function stripHtmlTags($tags, $str, $content = false) { $html = []; - if($content){ + if ($content) { foreach ($tags as $tag) { - $html[] = "/(<(?:\/" .$tag. "|" .$tag. ")[^>]*>)/is"; + $html[] = "/(<(?:\/" . $tag . "|" . $tag . ")[^>]*>)/is"; } - }else{ + } else { foreach ($tags as $tag) { - $html[] = '/<' .$tag. '.*?>[\s|\S]*?<\/' .$tag. '>/is'; - $html[] = '/<' .$tag. '.*?>/is'; + $html[] = '/<' . $tag . '.*?>[\s|\S]*?<\/' . $tag . '>/is'; + $html[] = '/<' . $tag . '.*?>/is'; } } $data = preg_replace($html, '', $str); @@ -681,7 +691,6 @@ private function stripHtmlTags($tags, $str, $content=false) } - /** * 根据自定义文章路径生成amp/mip的地址规则 * @return mixed @@ -696,22 +705,22 @@ private function getUrlRule() } //清理自定义格式 - $URLarr=explode('.',$slugtemp); - $target=''; - foreach ($URLarr as $x){//寻找别名标记 - if(strstr($x,'[slug]')){ - $target='[slug]'; + $URLarr = explode('.', $slugtemp); + $target = ''; + foreach ($URLarr as $x) {//寻找别名标记 + if (strstr($x, '[slug]')) { + $target = '[slug]'; } } - if ($target!=='[slug]'){//没找到别名标记则用文章序号 - $target='[cid:digital]'; + if ($target !== '[slug]') {//没找到别名标记则用文章序号 + $target = '[cid:digital]'; } //根据后缀名情况拼接文章路径 - if(count($URLarr)>1){ - $slugtemp=$target.'.'.$URLarr[count($URLarr)-1]; - }else{ - $slugtemp=$target; + if (count($URLarr) > 1) { + $slugtemp = $target . '.' . $URLarr[count($URLarr) - 1]; + } else { + $slugtemp = $target; } return $slugtemp; @@ -720,13 +729,14 @@ private function getUrlRule() /** * 清理文章摘要内容 - * @param array $desc 文章内容 + * @param array $desc 文章内容 * @return mixed */ - private static function cleanUp($desc){ - $desc= str_replace(array("\r\n", "\r", "\n"), "", strip_tags($desc));//获取纯内容后去除换行 - $desc=mb_substr($desc, 0, 150).'...';//截取前150个字符 - $desc= str_replace('"', '\"', $desc);//转义传递给json的 " + private static function cleanUp($desc) + { + $desc = str_replace(array("\r\n", "\r", "\n"), "", strip_tags($desc));//获取纯内容后去除换行 + $desc = mb_substr($desc, 0, 150) . '...';//截取前150个字符 + $desc = str_replace('"', '\"', $desc);//转义传递给json的 " return $desc; } @@ -740,8 +750,9 @@ private static function cleanUp($desc){ * author:Holmesian * date: 2020/3/13 11:40 */ - private function set($key, $cache){ - if(Helper::options()->plugin('AMP')->cacheTime>0) { + private function set($key, $cache) + { + if (Helper::options()->plugin('AMP')->cacheTime > 0) { $installDb = $this->db; $time = (int)Helper::options()->plugin('AMP')->cacheTime; $expire = $time * 60 * 60; @@ -753,15 +764,16 @@ private function set($key, $cache){ // $sql = "REPLACE INTO $table (`hash`,`cache`,`dateline`,`expire`) VALUES ('$key','$cache','$time','$expire')"; // $installDb->query($sql); - $installDb->query($installDb->insert($this->tablename)->rows(array("hash"=>$key,"cache"=>$cache,"dateline"=>$time,"expire"=>$expire)));//更换写入方法 + $installDb->query($installDb->insert($this->tablename)->rows(array("hash" => $key, "cache" => $cache, "dateline" => $time, "expire" => $expire)));//更换写入方法 - }else{ + } else { return null; } } - private function del($key){ - if(Helper::options()->plugin('AMP')->cacheTime>0) { + private function del($key) + { + if (Helper::options()->plugin('AMP')->cacheTime > 0) { $installDb = $this->db; if (is_array($key)) { foreach ($key as $k => $v) { @@ -774,13 +786,14 @@ private function del($key){ $installDb->query($installDb->delete($this->tablename)->where('hash = ?', $key)->limit(1)); } } - }else{ + } else { return null; } } - private function get($key){ - if(Helper::options()->plugin('AMP')->cacheTime>0) { + private function get($key) + { + if (Helper::options()->plugin('AMP')->cacheTime > 0) { $installDb = $this->db; $condition = $installDb->select('cache', 'dateline', 'expire')->from($this->tablename)->where('hash = ?', $key); @@ -790,7 +803,7 @@ private function get($key){ $cache = $row['cache']; $arr = json_decode($cache, true); return is_array($arr) ? $arr : $cache; - }else{ + } else { return null; } } @@ -798,7 +811,6 @@ private function get($key){ //------------页面缓存功能函数end------------ - } ?> \ No newline at end of file diff --git a/Links.php b/Links.php index fdf8b24a..00547edb 100644 --- a/Links.php +++ b/Links.php @@ -4,8 +4,13 @@ include 'menu.php'; date_default_timezone_set('PRC'); +Typecho_Widget::widget('Widget_Notice')->set(_t('熊掌号已经下线'), 'success'); + + + + $user = Typecho_Widget::widget('Widget_User'); -if(!$user->pass('administrator')){ +if (!$user->pass('administrator')) { die('未登录用户!'); } @@ -20,45 +25,49 @@ $page = 1; } //URL类型 - if ((isset($_GET['type']) and $_GET['type'] == 'amp') OR (isset($_POST['type']) and $_POST['type'] == 'amp')) { + if ((isset($_GET['type']) and $_GET['type'] == 'amp') or (isset($_POST['type']) and $_POST['type'] == 'amp')) { $sendtype = 'amp'; $type = 'amp'; - } elseif ((isset($_GET['type']) and $_GET['type'] == 'mip') OR (isset($_POST['type']) and $_POST['type'] == 'mip')) { + } elseif ((isset($_GET['type']) and $_GET['type'] == 'mip') or (isset($_POST['type']) and $_POST['type'] == 'mip')) { $sendtype = 'mip'; $type = 'mip'; - } elseif ((isset($_GET['type']) and $_GET['type'] == 'batch') OR (isset($_POST['type']) and $_POST['type'] == 'batch')) { - $sendtype = 'mip'; - $type = 'batch'; - if (isset(Helper::options()->plugin('AMP')->baiduAPPID) and isset(Helper::options()->plugin('AMP')->baiduTOKEN)) { - $appid = trim(Helper::options()->plugin('AMP')->baiduAPPID);//过滤空格 - $token = trim(Helper::options()->plugin('AMP')->baiduTOKEN);//过滤空格 - $api = "http://data.zz.baidu.com/urls?appid={$appid}&token={$token}&type=batch"; - } else { - throw new Typecho_Widget_Exception('未设置熊掌号参数!'); - } - } else { + } + //熊掌号下线,删除相关内容 2020.06.07 +// elseif ((isset($_GET['type']) and $_GET['type'] == 'batch') OR (isset($_POST['type']) and $_POST['type'] == 'batch')) { +// $sendtype = 'mip'; +// $type = 'batch'; +// if (isset(Helper::options()->plugin('AMP')->baiduAPPID) and isset(Helper::options()->plugin('AMP')->baiduTOKEN)) { +// $appid = trim(Helper::options()->plugin('AMP')->baiduAPPID);//过滤空格 +// $token = trim(Helper::options()->plugin('AMP')->baiduTOKEN);//过滤空格 +// $api = "http://data.zz.baidu.com/urls?appid={$appid}&token={$token}&type=batch"; +// } else { +// throw new Typecho_Widget_Exception('未设置熊掌号参数!'); +// } +// } + else { $sendtype = 'mip'; $type = 'mip'; } - $articleList = Typecho_Widget::widget('AMP_Action')->MakeArticleList($sendtype, $page, 20); + //构造提交api地址 + if (empty(Helper::options()->plugin('AMP')->baiduAPI)) { + throw new Typecho_Widget_Exception('未设置 快速收录接口地址!'); + } else { + //熊掌号下线后换成了快速收录 2020.06.07 修改此处为快速收录 接口 + //默认为快速收录的接口地址 + $api = trim(Helper::options()->plugin('AMP')->baiduAPI); //过滤空格 +// $api = preg_replace("/&type=[a-z]+/", "&type={$sendtype}", $api);//替换接口中的类型 + $api = preg_replace("/&type=[a-z]+/", "", $api);//将快速收录接口换成普通收录接口 + } - //接口类型 - if (!isset($api)) { - if (empty(Helper::options()->plugin('AMP')->baiduAPI)) { - throw new Typecho_Widget_Exception('未设置MIP/AMP推送接口调用地址!'); - } else { - $api = trim(Helper::options()->plugin('AMP')->baiduAPI); //过滤空格 - $api = preg_replace("/&type=[a-z]+/", "&type={$sendtype}", $api);//替换接口中的类型 - } - } $urls = array(); - foreach ($articleList AS $article) { - if(Helper::options()->plugin('AMP')->PostURL !== Helper::options()->index){ - $article['permalink']=str_replace(Helper::options()->index,Helper::options()->plugin('AMP')->PostURL,$article['permalink']);//替换提交的前缀 + $articleList = Typecho_Widget::widget('AMP_Action')->MakeArticleList($sendtype, $page, 20); + foreach ($articleList as $article) { + if (Helper::options()->plugin('AMP')->PostURL !== Helper::options()->index) { + $article['permalink'] = str_replace(Helper::options()->index, Helper::options()->plugin('AMP')->PostURL, $article['permalink']);//替换提交的前缀 } echo '正在提交:' . $article['permalink'] . "
"; $urls[] = $article['permalink']; @@ -72,7 +81,7 @@ $api = trim($api); //经过单步调试,发现api这个字符串前面多了一个空格,导致parse_url无法解析正确的`host` $result = $http->send($api); } catch (Exception $e) { - throw new Typecho_Plugin_Exception(_t('对不起, 您的主机不支持远程访问。
请检查 curl 扩展、allow_url_fopen和防火墙设置!

出错信息:'.$e->getMessage())); + throw new Typecho_Plugin_Exception(_t('对不起, 您的主机不支持远程访问。
请检查 curl 扩展、allow_url_fopen和防火墙设置!

出错信息:' . $e->getMessage())); } // string '{"remain":4999960,"success":0,"not_valid":[""]}' @@ -81,13 +90,12 @@ // string(43) "{"success_batch":20,"remain_batch":4999960}" $obj = json_decode($result, true); - $name = "success_{$type}"; - if (isset($obj[$name])) { + if (isset($obj["success"])) { echo '
'; echo "第{$page}页提交成功,"; - $count = $obj["remain_{$type}"]; + $count = $obj["remain"]; echo "还可提交{$count}条URL,准备提交下一页>>>"; $page += 1; @@ -124,21 +132,21 @@
+

本页将所选类型的地址批量提交到百度的 普通收录 资源提交接口

1.AMP(Accelerated Mobile Pages),是谷歌的一项开放源代码计划,可在移动设备上快速加载的轻便型网页,旨在使网页在移动设备上快速加载并且看起来非常美观。选择该项为自动向百度提交AMP页面地址。

2.MIP(Mobile Instant Page - 移动网页加速器),是一套应用于移动网页的开放性技术标准。通过提供MIP-HTML规范、MIP-JS运行环境以及MIP-Cache页面缓存系统,实现移动网页加速。选择该项为自动向百度提交页面地址。

- 3.熊掌号,是百度熊掌号是内容和服务提供者入驻百度生态的实名账号。通过历史内容接口,每天可提交最多500万条有价值的内容,所提交内容会进入百度搜索统一处理流程。请先设置好APPID和TOKEN后再进行提交。

+ 3.熊掌号(已下线),是百度熊掌号是内容和服务提供者入驻百度生态的实名账号。通过历史内容接口,每天可提交最多500万条有价值的内容,所提交内容会进入百度搜索统一处理流程。请先设置好APPID和TOKEN后再进行提交。

如果因服务器环境无法自动提交,可打开AMP网址列表AMP网址列表MIP网址列表,手动复制URL提交到百度站长后台。

diff --git a/Plugin.php b/Plugin.php index 481a6bd9..b3dd547b 100644 --- a/Plugin.php +++ b/Plugin.php @@ -4,14 +4,14 @@ * * @package AMP-MIP * @author Holmesian - * @version 0.7.5.3 + * @version 0.7.6.1 * @link https://holmesian.org/AMP-for-Typecho */ if (!defined('__TYPECHO_ROOT_DIR__')) exit; class AMP_Plugin implements Typecho_Plugin_Interface { - public static $version = '0.7.5.3'; + public static $version = '0.7.6.1'; public static function activate() { @@ -55,43 +55,52 @@ public static function index() public static function config(Typecho_Widget_Helper_Form $form) { + $newVer=self::call_me("check"); + if(self::$version!=$newVer && $newVer!="Error"){ + Typecho_Widget::widget('Widget_Notice')->set(_t('请到 https://github.com/holmesian/Typecho-AMP 更新插件,当前最新版:'.$newVer), 'success'); + } - $element = new Typecho_Widget_Helper_Form_Element_Text('cacheTime', null, '0', _t('缓存时间'), '单位:小时(设置成 0 表示关闭)
此项为缓存过期时间,建议值 24。如果需要重建缓存,请点击 删除所有缓存'); - $form->addInput($element); - $element = new Typecho_Widget_Helper_Form_Element_Text('baiduAPI', null, '', _t('MIP/AMP推送接口调用地址'), '打开页面后 点击 MIP -> 数据提交 -> 提交新数据 获取接口调用地址(填写 AMP 或 MIP 的任意一个的提交地址即可)'); + $element = new Typecho_Widget_Helper_Form_Element_Text('cacheTime', null, '0', _t('缓存时间'), '单位:小时(设置成 0 表示关闭)
此项为缓存过期时间,建议值 24。如果需要重建缓存,请点击 删除所有缓存'); $form->addInput($element); - $element = new Typecho_Widget_Helper_Form_Element_Text('baiduAPPID', null, '', _t('熊掌号识别ID'), '打开页面后 点击 我的功能->资源提交 根据接口调用地址 获取 APPID'); + $element = new Typecho_Widget_Helper_Form_Element_Text('baiduAPI', null, '', _t('快速收录接口地址'), '打开页面后 快速收录 -> API提交 获取接口调用地址
地址类似 http://data.zz.baidu.com/urls?site=https://holmesian.org/&token=xxxxxxx&type=daily '); $form->addInput($element); - $element = new Typecho_Widget_Helper_Form_Element_Text('baiduTOKEN', null, '', _t('熊掌号准入密钥'), '打开页面后 点击 我的功能->资源提交 根据接口调用地址 获取 TOKEN'); + $element = new Typecho_Widget_Helper_Form_Element_Radio('mipAutoSubmit', array(0 => '不开启', 1 => '提交到快速收录',2=>'提交到普通收录'), 0, _t('新文章自动提交'), '请填写 快速收录接口地址 再开启
说明:如果文章属性为 隐藏 或 定时发布 或 编辑 则不推送,新文章 和 草稿在一天之内发表的文章会自动推送'); $form->addInput($element); $element = new Typecho_Widget_Helper_Form_Element_Text('mip_stats_token', null, '', _t('百度统计token'), '点击了解如何获取 TOKEN'); $form->addInput($element); - $element = new Typecho_Widget_Helper_Form_Element_Radio('AMPsitemap', array(0 => '不开启', 1 => '开启'), 1, _t('是否开启 AMP 的 SiteMap'), 'AMP SiteMap 地址:' . Helper::options()->index . '/amp_sitemap.xml'); - $form->addInput($element); - $element = new Typecho_Widget_Helper_Form_Element_Radio('MIPsitemap', array(0 => '不开启', 1 => '开启'), 1, _t('是否开启 MIP 的 SiteMap'), 'MIP SiteMap 地址:'. Helper::options()->index . '/mip_sitemap.xml'); + $element = new Typecho_Widget_Helper_Form_Element_Radio('OnlyForSpiders', array(0 => '不开启', 1 => '开启'), 0, _t('是否只允许百度和谷歌的爬虫访问 AMP/MIP 页面'), '启用后需要伪造 UA 才能访问 AMP/MIP 页面'); $form->addInput($element); - $element = new Typecho_Widget_Helper_Form_Element_Radio('ampIndex', array(0 => '不开启', 1 => '开启'), 1, _t('是否开启 AMP 版的首页'), 'AMP Index 地址:' . Helper::options()->index . '/ampindex (受 AMP-LIST 控件限制,非 HTTPS 站点请勿开启 AMP 版的首页)'); + + $element = new Typecho_Widget_Helper_Form_Element_Radio('AMPsitemap', array(0 => '不开启', 1 => '开启'), 1, _t('开启 AMP 的 SiteMap'), 'AMP SiteMap 地址:' . Helper::options()->index . '/amp_sitemap.xml'); $form->addInput($element); - $element = new Typecho_Widget_Helper_Form_Element_Radio('mipAutoSubmit', array(0 => '不开启', 1 => '开启'), 0, _t('是否开启新文章自动提交到熊掌号'), '请填写熊掌号的 APPID 和 TOKEN 后再开启'); + $element = new Typecho_Widget_Helper_Form_Element_Radio('MIPsitemap', array(0 => '不开启', 1 => '开启'), 1, _t('开启 MIP 的 SiteMap'), 'MIP SiteMap 地址:'. Helper::options()->index . '/mip_sitemap.xml'); $form->addInput($element); - $element = new Typecho_Widget_Helper_Form_Element_Radio('OnlyForSpiders', array(0 => '不开启', 1 => '开启'), 0, _t('是否只允许百度和谷歌的爬虫访问 AMP/MIP 页面'), '启用后需要伪造 UA 才能访问 AMP/MIP 页面'); + $element = new Typecho_Widget_Helper_Form_Element_Radio('ampIndex', array(0 => '不开启', 1 => '开启'), 1, _t('开启 AMP 版的首页'), 'AMP Index 地址:' . Helper::options()->index . '/ampindex
受 AMP-LIST 控件限制,非 HTTPS 站点请勿开启 AMP 版首页'); $form->addInput($element); + $element = new Typecho_Widget_Helper_Form_Element_Text('LOGO', null, 'https://holmesian.org/usr/themes/Holmesian/images/holmesian.png', _t('默认 LOGO 地址'), '根据 AMP 的限制,尺寸不超过 60*60'); $form->addInput($element); $element = new Typecho_Widget_Helper_Form_Element_Text('PostURL', null, Helper::options()->index , _t('替换自动提交的前缀地址'), '作用看这里,无需求勿动'); $form->addInput($element); + + $element = new Typecho_Widget_Helper_Form_Element_Text('baiduAPPID', null, '', _t('熊掌号识别ID(已失效)'), '随着熊掌号已下线,已成无效项,后续将删除。'); + $form->addInput($element); + + $element = new Typecho_Widget_Helper_Form_Element_Text('baiduTOKEN', null, '', _t('熊掌号准入密钥(已失效)'), '随着熊掌号已下线,已成无效项,后续将删除。'); + $form->addInput($element); + } public static function personalConfig(Typecho_Widget_Helper_Form $form) @@ -129,6 +138,7 @@ public static function uninstall() } + public static function call_me($type){//远程通知 $api="https://holmesian.org/m/?action={$type}"; @@ -146,7 +156,7 @@ public static function call_me($type){//远程通知 return $msg; } catch (Exception $e){ - $msg='通知出错!'; + $msg='Error'; return $msg; } } @@ -164,7 +174,7 @@ public static function DBsetup() $installDb = Typecho_Db::get(); if(stristr($installDb->getAdapterName(),'mysql')== false){ - return('缓存暂不支持 MySQL 以外的数据库.'); + return('[缓存]暂不支持 MySQL 以外的数据库.'); } $cacheTable = $installDb->getPrefix() . 'PageCache'; try { diff --git a/README.md b/README.md index ace96e08..8d59b68c 100644 --- a/README.md +++ b/README.md @@ -12,38 +12,11 @@ A Typecho plugin for Google AMP / Baidu MIP 点击下载[最新版][2] ------- -## 支持 +2020.06.30 增加版本检查,修改sitemap分页数量。 -如果本插件帮到了你,不妨给点赞赏鼓励一下作者 ^-^ +2020.06.07 去除已下线的熊掌号相关功能,将自动提交和批量提交功能修改为 提交到快速收录接口和普通收录接口。 版本更新为0.7.6。 - - - ------- - -## 功能 - -- 生成符合 Google AMP/Baidu MIP 标准的 AMP/MIP 页面,并与标准页面建立关联。 - -- 生成 AMP/MIP 的 SiteMap,及所有 URL 的纯文本列表(支持分页)。 - -- 生成 AMP 版的首页。 - -- 后台批量提交 URL 到百度站长平台,可选手动或自动。 - -- MIP 页面完美支持百度熊掌号页面标准,新发表文章自动提交到熊掌号。 - -- (新增)用户决定是否只允许百度和谷歌的爬虫访问 MIP/AMP 页面。 - -- (新增)插件版本判断。 - -- (新增)自定义 MIP/AMP 页面样式。 - -- (新增)缓存功能,缓存访问过的 MIP/AMP 页面,可显著提高性能(默认关闭)。 - -- 自动解析自定义文章路径。 ------ @@ -57,17 +30,18 @@ A Typecho plugin for Google AMP / Baidu MIP ### 升级 -> 注意:**请先禁用插件后再升级!** +> 注意:已安装旧版本的 **请先禁用插件后再升级!** -非 MarkDown 编辑器书写的文章由于存在诸多不可预见的情况,生成的 AMP/MIP 页面可能不能完全符合标准,如果有遇到请及时反馈。 + +> 非 MarkDown 编辑器书写的文章由于存在诸多不可预见的情况,生成的 AMP/MIP 页面可能不能完全符合标准,如果有遇到请及时反馈。 ------ ## 使用说明 -- 在插件后台设置默认 LOGO 以及选择是否开启 SiteMap、AMP 首页、自动提交到熊掌号等功能(除自动提交到熊掌号外的功能都默认开启)。 +- 在插件后台设置默认 LOGO 以及选择是否开启 SiteMap、AMP 首页、~~自动提交到熊掌号等功能(除自动提交到熊掌号外的功能都默认开启)~~。 -- 从[百度站长][3]获取接口调用地址、熊掌号 APPID/TOKEN,填写到插件设置中(使用提交 URL功能时需要)。 +- 从[百度站长][3]获取接口调用地址、~~熊掌号 APPID/TOKEN~~,填写到插件设置中(使用提交 URL功能时需要)。 - AMP/MIP 的页面缓存默认关闭,可在插件设置页面修改缓存时间。修改文章会自动更新页面缓存,重建缓存开关在插件设置页,设置缓存时间的下方。 @@ -88,8 +62,42 @@ AMP 页面为: http(s)://xxx/amp/slug/ MIP 页面为: http(s)://xxx/mip/slug/ + +------ + +## 功能 + +- 生成符合 Google AMP/Baidu MIP 标准的 AMP/MIP 页面,并与标准页面建立关联。 + +- 生成 AMP/MIP 的 SiteMap,及所有 URL 的纯文本列表(支持分页)。 + +- 生成 AMP 版的首页。 + +- 后台批量提交 URL 到百度站长平台,可选手动或自动。 + +- MIP 页面完美支持百度熊掌号页面标准,~~新发表文章自动提交到熊掌号~~。 + +- (新增)用户决定是否只允许百度和谷歌的爬虫访问 MIP/AMP 页面。 + +- (新增)插件版本判断。 + +- (新增)自定义 MIP/AMP 页面样式。 + +- (新增)缓存功能,缓存访问过的 MIP/AMP 页面,可显著提高性能(默认关闭)。 + +- 自动解析自定义文章路径。 + + ------ +## 支持 + +如果本插件帮到了你,不妨给点赞赏鼓励一下作者 ^-^ + + + + +------ ## 效果预览 MIP内容页: @@ -109,5 +117,5 @@ AMP首页: [1]: https://holmesian.org/typecho-upgrade-AMP [2]: https://github.com/typecho-fans/plugins/releases/download/plugins-A_to_C/AMP.zip - [3]: http://ziyuan.baidu.com/mip/index + [3]: https://ziyuan.baidu.com/dailysubmit/index [4]: https://www.ampproject.org/docs/reference/components/amp-list