├── logo.png ├── README.md ├── Action.php ├── LICENSE └── Plugin.php /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nyarime/DDSBLinks/HEAD/logo.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DDSBLinks 2 | 3 | ![DDSBLinks](https://img.itxe.net/images/2020/07/07/0789b5526128cead569790c5257aeec2.png) 4 | 5 | 有时候我们为了减少权重的流失,或者是为了隐藏某些推荐链接(比如:淘宝客、主机推荐),因此需要将外链转化为内链(淘宝客、主机推荐都是隐藏 AFF)。 6 | 7 | 此时 DD.SB 就可以为您的Typecho隐藏真实链接, 并提供无广告且极速的跳转 8 | 9 | 本插件与其他外链插件都不兼容, 安装前请确保其他外链插件禁用 10 | 11 | ## 获取 Download 12 | 13 | [最稳定版下载地址](https://github.com/Nyarime/DDSBLinks/releases/latest) 14 | 15 | ## 简介 Introduction 16 | 17 | 1. 把外部链接转换为 https://dd.sb/xxx ,撰写链接页面支持修改 18 | 2. 通过菜单“创建->DDSBLinks”设置; 19 | 3. 无需配置token, 可直接食用于Typecho; 20 | 4. 支持 referer 白名单和外链转换白名单; 21 | 5. 支持自定义字段转换(实验性功能); 22 | 6. 支持关闭指定页面的链接转换功能。添加自定义字段 `noshort` 即可; 23 | 24 | ## 使用方法 Usage 25 | 26 | - 使用 Git 命令直接克隆至插件目录即可,例如: `/var/www/html/usr/plugins/` 下 27 | - 然后启用插件即可 28 | 29 | ## 其他 Others 30 | 31 | ### 模板使用 Template Usage 32 | 33 | 模板功能自 1.1.0 b2 开始支持更多的字段替换。 34 | 35 | 支持 Typecho 选项和主题选项字段替换。 36 | 37 | 就是平常用 `$this->options->logoUrl` 这样的形式调用的字段,可以直接在模板里使用 `{{logoUrl}}` 定义,DDSBLinks 插件会自动替换。 38 | 39 | 如果发现有不支持的字段,别尝试了,就是 DDSBLinks 没适配。 40 | 41 | ### 计划功能 Todo 42 | 43 | - 自定义短链接增加密码功能 44 | 45 | ### 感谢 Thanks 46 | 47 | - [BBLeae](https://baka.studio "BakaStudio") 48 | 49 | - [DD.SB](https://dd.sb "DD.SB") 50 | 51 | - [Typecho](https://typecho.org "左岸") 52 | 53 | ### 预览 Preview 54 | 55 | 暂无 56 | -------------------------------------------------------------------------------- /Action.php: -------------------------------------------------------------------------------- 1 | db = Typecho_Db::get(); 18 | $this->options = self::getOptions(); 19 | $this->options->setDefault('logoUrl=' . Helper::options()->pluginUrl . '/DDSBLinks/logo.png&siteCreatedYear=' . Helper::options()->plugin('DDSBLinks')->siteCreatedYear . '¤tYear=' . date('Y')); 20 | } 21 | 22 | /** 23 | * 链接重定向 24 | * 25 | */ 26 | public function shortlink() 27 | { 28 | $requestString = $this->request->key; 29 | $siteUrl = preg_replace("/https?:\/\//", "", Typecho_Widget::widget('Widget_Options')->siteUrl); 30 | $pOption = Typecho_Widget::widget('Widget_Options')->Plugin('DDSBLinks'); // 插件选项 31 | $referer = $this->request->getReferer(); 32 | $template = $pOption->goTemplate == 'NULL' ? null : $pOption->goTemplate; 33 | // 允许空 referer 34 | if (empty($referer) && $pOption->nullReferer === "1") { 35 | $referer = $siteUrl; 36 | } 37 | 38 | $refererList = DDSBLinks_Plugin::textareaToArr($pOption->refererList); // 允许的referer列表 39 | $target = $this->getTarget($requestString); 40 | // 设置nofollow属性 41 | $this->response->setHeader('X-Robots-Tag', 'noindex, nofollow'); 42 | if ($target) { 43 | // 自定义短链 44 | // 增加统计 45 | $count = $this->db->fetchObject($this->db->select('count') 46 | ->from('table.ddsblinks') 47 | ->where('key = ?', $requestString))->count; 48 | $count = $count + 1; 49 | $this->db->query($this->db->update('table.ddsblinks') 50 | ->rows(array('count' => $count)) 51 | ->where('key = ?', $requestString)); 52 | } else if ($requestString === DDSBLinks_Plugin::urlSafeB64Encode(DDSBLinks_Plugin::urlSafeB64Decode($requestString))) { 53 | // 自动转换链接处理 54 | $target = DDSBLinks_Plugin::urlSafeB64Decode($requestString); 55 | $allow_redirect = false; // 默认不允许跳转 56 | // 检查 referer 57 | $allow_redirect = DDSBLinks_Plugin::checkDomain($referer, $refererList); 58 | if (strpos($referer, $siteUrl) !== false) { 59 | $allow_redirect = true; 60 | } 61 | if (!$allow_redirect) { 62 | // referer 非法跳转到首页 63 | $this->response->redirect($siteUrl, 301); 64 | exit(); 65 | } 66 | } else { 67 | throw new Typecho_Widget_Exception(_t('您访问的网页不存在'), 404); 68 | } 69 | $this->response->redirect(htmlspecialchars_decode($target), 301); 70 | } 71 | /** 72 | * 获取目标链接 73 | * 74 | * @param string $key 75 | * @return void 76 | */ 77 | public function getTarget($key) 78 | { 79 | $target = $this->db->fetchRow($this->db->select('target') 80 | ->from('table.ddsblinks') 81 | ->where(' key = ?', $key)); 82 | if (isset($target['target'])) { 83 | return $target['target']; 84 | } else { 85 | return false; 86 | } 87 | } 88 | 89 | /** 90 | * 重设自定义链接 91 | */ 92 | public function resetLink() 93 | { 94 | Typecho_Response::throwJson('success'); 95 | } 96 | 97 | public function action() 98 | { 99 | $this->widget('Widget_User')->pass('administrator'); 100 | $this->response->goBack(); 101 | } 102 | 103 | public function getOptions() 104 | { 105 | $values = $this->db->fetchAll($this->db->select('name', 'value')->from('table.options')->where('user = 0')); 106 | $options = array(); 107 | foreach ($values as $value) { 108 | if (strpos($value['name'], "plugin:") === 0) { 109 | continue; 110 | } 111 | 112 | $options[$value['name']] = $value['value']; 113 | } 114 | /** 主题变量重载 */ 115 | if (!empty($options['theme:' . $options['theme']])) { 116 | $themeOptions = null; 117 | 118 | /** 解析变量 */ 119 | if ($themeOptions = unserialize($options['theme:' . $options['theme']])) { 120 | /** 覆盖变量 */ 121 | $options = array_merge($options, $themeOptions); 122 | } 123 | } 124 | $options['rootUrl'] = defined('__TYPECHO_ROOT_URL__') ? __TYPECHO_ROOT_URL__ : $this->request->getRequestRoot(); 125 | if (defined('__TYPECHO_ADMIN__')) { 126 | /** 识别在admin目录中的情况 */ 127 | $adminDir = '/' . trim(defined('__TYPECHO_ADMIN_DIR__') ? __TYPECHO_ADMIN_DIR__ : '/admin/', '/'); 128 | $options['rootUrl'] = substr($options['rootUrl'], 0, -strlen($adminDir)); 129 | } 130 | if (defined('__TYPECHO_SITE_URL__')) { 131 | $options['siteUrl'] = __TYPECHO_SITE_URL__; 132 | } else if (defined('__TYPECHO_DYNAMIC_SITE_URL__') && __TYPECHO_DYNAMIC_SITE_URL__) { 133 | $options['siteUrl'] = $options['rootUrl']; 134 | } 135 | $options['originalSiteUrl'] = $options['siteUrl']; 136 | $options['siteUrl'] = Typecho_Common::url(null, $options['siteUrl']); 137 | 138 | return Typecho_Config::factory($options); 139 | } 140 | /** 141 | * 替换回调 142 | * 143 | * @param Array $matches 144 | * @return String 145 | * @date 2020-05-01 146 | */ 147 | private function __relpaceCallback($matches) 148 | { 149 | return $this->options->{$matches[1]}; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Plugin.php: -------------------------------------------------------------------------------- 1 | getPrefix() . 'ddsblinks'; 24 | $adapter = $db->getAdapterName(); 25 | if ("Pdo_SQLite" === $adapter || "SQLite" === $adapter) { 26 | $db->query(" CREATE TABLE IF NOT EXISTS " . $ddsblinks . "( 27 | id INTEGER PRIMARY KEY, 28 | longurl TEXT, 29 | shorturl TEXT)"); 30 | } 31 | if ("Pdo_Mysql" === $adapter || "Mysql" === $adapter) { 32 | $dbConfig = Typecho_Db::get()->getConfig()[0]; 33 | $charset = $dbConfig->charset; 34 | $db->query("CREATE TABLE IF NOT EXISTS " . $ddsblinks . "( 35 | `id` int(8) NOT NULL AUTO_INCREMENT, 36 | `longurl` TEXT NOT NULL, 37 | `shorturl` varchar(64) NOT NULL, 38 | PRIMARY KEY (`id`) 39 | ) DEFAULT CHARSET=${charset} AUTO_INCREMENT=1"); 40 | } 41 | Typecho_Plugin::factory('Widget_Abstract_Contents')->contentEx = array('DDSBLinks_Plugin', 'replace'); 42 | Typecho_Plugin::factory('Widget_Abstract_Contents')->excerptEx = array('DDSBLinks_Plugin', 'replace'); 43 | Typecho_Plugin::factory('Widget_Abstract_Contents')->filter = array('DDSBLinks_Plugin', 'replace'); 44 | Typecho_Plugin::factory('Widget_Abstract_Comments')->filter = array('DDSBLinks_Plugin', 'replace'); 45 | Typecho_Plugin::factory('Widget_Archive')->singleHandle = array('DDSBLinks_Plugin', 'replace'); 46 | return ('数据表 ' . $ddsblinks . ' 创建成功,插件已经成功激活!'); 47 | } 48 | 49 | /** 50 | * 禁用插件方法,如果禁用失败,直接抛出异常 51 | * 52 | * @static 53 | * @access public 54 | * @return String 55 | * @throws Typecho_Plugin_Exception 56 | */ 57 | public static function deactivate() 58 | { 59 | $config = Typecho_Widget::widget('Widget_Options')->plugin('DDSBLinks'); 60 | $db = Typecho_Db::get(); 61 | $db->query("DROP TABLE `{$db->getPrefix()}ddsblinks`", Typecho_Db::WRITE); 62 | return ('DDSBLinks已被禁用,其表(_ddsblinks)已被删除!'); 63 | } 64 | 65 | /** 66 | * 获取插件配置面板 67 | * 68 | * @access public 69 | * @param Typecho_Widget_Helper_Form $form 配置面板 70 | * @return void 71 | */ 72 | public static function config(Typecho_Widget_Helper_Form $form) 73 | { 74 | $radio = new Typecho_Widget_Helper_Form_Element_Radio('convert', array('1' => _t('开启'), '0' => _t('关闭')), '1', _t('外链转DD.SB链接'), _t('开启后会帮你把外链转换成DD.SB链接')); 75 | $form->addInput($radio); 76 | $radio = new Typecho_Widget_Helper_Form_Element_Radio('convertCommentLink', array('1' => _t('开启'), '0' => _t('关闭')), '1', _t('转换评论者链接'), _t('开启后会帮你把评论者链接转换成DD.SB链接')); 77 | $form->addInput($radio); 78 | 79 | $radio = new Typecho_Widget_Helper_Form_Element_Radio('target', array('1' => _t('开启'), '0' => _t('关闭')), '1', _t('新窗口打开文章中的链接'), _t('开启后给文章中的链接新增 target 属性')); 80 | $form->addInput($radio); 81 | 82 | $radio = new Typecho_Widget_Helper_Form_Element_Radio('authorPermalinkTarget', array('1' => _t('开启'), '0' => _t('关闭')), '0', _t('新窗口打开评论者链接'), _t('开启后给评论者链接新增 target 属性。(URL 中 target 属性,开启可能会引起主题异常)')); 83 | $form->addInput($radio); 84 | 85 | $textarea = new Typecho_Widget_Helper_Form_Element_Textarea('convertCustomField', null, null, _t('需要处理的自定义字段'), _t('在这里设置需要处理的自定义字段,一行一个(实验性功能)')); 86 | $form->addInput($textarea); 87 | $radio = new Typecho_Widget_Helper_Form_Element_Radio('nullReferer', array('1' => _t('开启'), '0' => _t('关闭')), '1', _t('允许空 referer'), _t('开启后会允许空 referer')); 88 | $form->addInput($radio); 89 | $refererList = new Typecho_Widget_Helper_Form_Element_Textarea('refererList', null, null, _t('referer 白名单'), _t('在这里设置 referer 白名单,一行一个')); 90 | $form->addInput($refererList); 91 | $nonConvertList = new Typecho_Widget_Helper_Form_Element_Textarea('nonConvertList', null, _t("itxe.net" . PHP_EOL . "idc.moe" . PHP_EOL . "dd.sb" . PHP_EOL . "idc.cy"), _t('外链转换白名单'), _t('在这里设置外链转换白名单(评论者链接不生效)')); 92 | $form->addInput($nonConvertList); 93 | } 94 | 95 | /** 96 | * 个人用户的配置面板 97 | * 98 | * @access public 99 | * @param Typecho_Widget_Helper_Form $form 100 | * @return void 101 | */ 102 | public static function personalConfig(Typecho_Widget_Helper_Form $form) 103 | { 104 | } 105 | 106 | /** 107 | * 外链转DD.SB链接 108 | * 109 | * @access public 110 | * @param $content 111 | * @param $class 112 | * @return $content 113 | */ 114 | public static function replace($text, $widget, $lastResult) 115 | { 116 | $text = empty($lastResult) ? $text : $lastResult; 117 | $pluginOption = Typecho_Widget::widget('Widget_Options')->Plugin('DDSBLinks'); // 插件选项 118 | $siteUrl = Helper::options()->siteUrl; 119 | $target = ($pluginOption->target) ? ' target="_blank" ' : ''; // 新窗口打开 120 | if ($pluginOption->convert == 1) { 121 | if (!is_string($text) && $text instanceof Widget_Archive) { 122 | // 自定义字段处理 123 | $fieldsList = self::textareaToArr($pluginOption->convertCustomField); 124 | if ($fieldsList) { 125 | foreach ($fieldsList as $field) { 126 | if (isset($text->fields[$field])) { 127 | @preg_match_all('//', $text->fields[$field], $matches); 128 | if ($matches) { 129 | foreach ($matches[2] as $link) { 130 | $text->fields[$field] = str_replace("href=\"$link\"", "href=\"" . self::convertLink($link) . "\"", $text->fields[$field]); 131 | } 132 | } 133 | } 134 | } 135 | } 136 | } 137 | if (($widget instanceof Widget_Archive) || ($widget instanceof Widget_Abstract_Comments)) { 138 | $fields = unserialize($widget->fields); 139 | if (is_array($fields) && array_key_exists("noshort", $fields)) { 140 | return $text; 141 | } 142 | 143 | // 文章内容和评论内容处理 144 | @preg_match_all('//', $text, $matches); 145 | if ($matches) { 146 | foreach ($matches[2] as $link) { 147 | $text = str_replace("href=\"$link\"", "href=\"" . self::convertLink($link) . "\"" . $target, $text); 148 | } 149 | } 150 | } 151 | if ($pluginOption->convertCommentLink == 1 && $widget instanceof Widget_Abstract_Comments) { 152 | // 评论者链接处理 153 | $url = $text['url']; 154 | if (strpos($url, '://') !== false && strpos($url, rtrim($siteUrl, '/')) === false) { 155 | $text['url'] = self::convertLink($url, false); 156 | if ($pluginOption->authorPermalinkTarget) { 157 | $text['url'] = $text['url'] . '" target="_blank'; 158 | } 159 | } 160 | } 161 | } 162 | return $text; 163 | } 164 | 165 | /** 166 | * 转换链接形式 167 | * 168 | * @access public 169 | * @param $link 170 | * @return $string 171 | */ 172 | public static function convertLink($link, $check = true) 173 | { 174 | $rewrite = (Helper::options()->rewrite) ? '' : 'index.php/'; // 伪静态处理 175 | $pluginOption = Typecho_Widget::widget('Widget_Options')->Plugin('DDSBLinks'); // 插件选项 176 | $linkBase = ltrim(rtrim(Typecho_Router::get('go')['url'], '/'), '/'); // 防止链接形式修改后不能用 177 | $siteUrl = Helper::options()->siteUrl; 178 | $target = ($pluginOption->target) ? ' target="_blank" ' : ''; // 新窗口打开 179 | $nonConvertList = self::textareaToArr($pluginOption->nonConvertList); // 不转换列表 180 | if ($check) { 181 | if (strpos($link, '://') !== false && strpos($link, rtrim($siteUrl, '/')) !== false) { 182 | return $link; 183 | } 184 | //本站链接不处理 185 | if (self::checkDomain($link, $nonConvertList)) { 186 | return $link; 187 | } 188 | // 不转换列表中的不处理 189 | if (preg_match('/\.(jpg|jepg|png|ico|bmp|gif|tiff)/i', $link)) { 190 | return $link; 191 | } 192 | // 图片不处理 193 | } 194 | return self::DdsbUrl($link); 195 | } 196 | 197 | /** 198 | * 检查域名是否在数组中存在 199 | * 200 | * @access public 201 | * @param $url $arr 202 | * @param $class 203 | * @return boolean 204 | */ 205 | public static function checkDomain($url, $arr) 206 | { 207 | if ($arr === null) { 208 | return false; 209 | } 210 | 211 | if (count($arr) === 0) { 212 | return false; 213 | } 214 | 215 | foreach ($arr as $a) { 216 | if (strpos($url, $a) !== false) { 217 | return true; 218 | } 219 | } 220 | return false; 221 | } 222 | 223 | /** 224 | * 一行一个文本框转数组 225 | * 226 | * @access public 227 | * @param $textarea 228 | * @param $class 229 | * @return $arr 230 | */ 231 | public static function textareaToArr($textarea) 232 | { 233 | $str = str_replace(array("\r\n", "\r", "\n"), "|", $textarea); 234 | if ($str == "") { 235 | return null; 236 | } 237 | 238 | return explode("|", $str); 239 | } 240 | /** 241 | * Base64 解码 242 | * 243 | * @param string $str 244 | * @return string 245 | * @date 2020-05-01 246 | */ 247 | public static function urlSafeB64Decode($str) 248 | { 249 | $data = str_replace(array('-', '_'), array('+', '/'), $str); 250 | $mod = strlen($data) % 4; 251 | if ($mod) { 252 | $data .= substr('====', $mod); 253 | } 254 | return base64_decode($data); 255 | } 256 | /** 257 | * Base64 编码 258 | * 259 | * @param string $str 260 | * @return string 261 | * @date 2020-05-01 262 | */ 263 | public static function urlSafeB64Encode($str) 264 | { 265 | $data = base64_encode($str); 266 | $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data); 267 | return $data; 268 | } 269 | public static function DdsbUrl($url){ 270 | $db = Typecho_Db::get(); 271 | $cache = $db->fetchObject($db->select() 272 | ->from('table.ddsblinks') 273 | ->where('longurl = ?', $url)); 274 | if ($cache->longurl == $url) { 275 | return $cache->shorturl; 276 | } else { 277 | $requestUrl = "https://dd.sb/api.php?url=$url"; 278 | $res = file_get_contents($requestUrl); 279 | $result = json_decode(self::checkBOM($res), TRUE); 280 | if ($result['error'] != 0) { 281 | return $link; 282 | } else { 283 | self::addCache($url, $result['shorturl']); 284 | return $result['shorturl']; 285 | } 286 | } 287 | } 288 | 289 | /** 290 | * 添加新的链接缓存 291 | * 292 | */ 293 | public static function addCache($longurl, $shorturl) 294 | { 295 | if (!$shorturl) { 296 | return; 297 | } 298 | $db = Typecho_Db::get(); 299 | $db->query($db->insert('table.ddsblinks')->rows(array( 300 | 'longurl' => $longurl, 301 | 'shorturl' => $shorturl, 302 | ))); 303 | } 304 | 305 | public static function checkBOM($contents) { 306 | $charset[1] = substr($contents, 0, 1); 307 | $charset[2] = substr($contents, 1, 1); 308 | $charset[3] = substr($contents, 2, 1); 309 | if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) { 310 | return substr($contents, 3); 311 | } else { 312 | return $contents; 313 | } 314 | } 315 | } 316 | --------------------------------------------------------------------------------