forked from typecho-fans/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Plugin.php
381 lines (348 loc) · 13.9 KB
/
Plugin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
/**
* CSDN博客导入插件
* @author MDY
* @package CSDN
* @version 1.0.0
* @license GNU General Public License 2.0
*/
class CSDN_Plugin extends Widget_Abstract_Contents implements Typecho_Plugin_Interface
{
//爬虫的header
protected static $context;
//文章id的正则
protected static $r_article_id = '/^https\:\/\/blog\.csdn\.net\/.+\/article\/details\//';
//文章链接的正则
protected static $r_article;
//博客列表的地址
protected static $source_url;
//博客的地址
protected static $article_url;
/**
* 启用插件方法,如果启用失败,直接抛出异常
*
* @static
* @access public
* @return void
*/
public static function activate()
{
// TODO: Implement activate() method.
Typecho_Plugin::factory('admin/menu.php')->navBar = array('CSDN_Plugin', 'render');
Typecho_Plugin::factory('admin/menu.php')->navBar = array('CSDN_Plugin', 'header');
Helper::addRoute('get-articles-id', '/get-articles-id', 'CSDN_Plugin', 'get_articles_id');
Helper::addRoute('add-article', '/add-article', 'CSDN_Plugin', 'add_article');
}
/**
* 禁用插件方法,如果禁用失败,直接抛出异常
*
* @static
* @access public
* @return void
*/
public static function deactivate()
{
// TODO: Implement deactivate() method.
Helper::removeRoute('get-articles-id');
Helper::removeRoute('add-article');
}
/**
* 获取插件配置面板
*
* @static
* @access public
* @param Typecho_Widget_Helper_Form $form 配置面板
* @return void
*/
public static function config(Typecho_Widget_Helper_Form $form)
{
// TODO: Implement config() method.
$UserName = new Typecho_Widget_Helper_Form_Element_Text('UserName', NULL, '', _t('UserName(在浏览器开发者模式下csdn的网站找到这个cookie,下同)'));
$UserToken = new Typecho_Widget_Helper_Form_Element_Text('UserToken', NULL, '', _t('UserToken'));
$UserInfo = new Typecho_Widget_Helper_Form_Element_Text('UserInfo', NULL, '', _t('UserInfo'));
$form->addInput($UserName);
$form->addInput($UserToken);
$form->addInput($UserInfo);
}
/**
* 个人用户的配置面板
*
* @access public
* @param Typecho_Widget_Helper_Form $form
* @return void
*/
public static function personalConfig(Typecho_Widget_Helper_Form $form)
{
// TODO: Implement personalConfig() method.
}
/**
* 插件实现方法
*
* @access public
* @return void
*/
public static function render()
{
echo '<a href="#" onclick="add_post();return false;" style="color: #ff0007">点击导入博文'
. '</a>';
}
/**
* 添加文章
*/
public function add_article()
{
header('Content-Type:text/json;charset=utf-8');
//得到config的输入框的值
$csdn = Helper::options()->plugin('CSDN');
$username = $csdn->UserName;
$usertoken = $csdn->UserToken;
$userinfo = $csdn->UserInfo;
//初始化cookie
CSDN_Plugin::$context = CSDN_Plugin::init_header($username, $userinfo, $usertoken);
$aid = $_POST['aid'];
$date = $_POST['date'];
try {
$result = CSDN_Plugin::get_post_info($aid, $date);
if (gettype($result) == 'array') {
//数据库获取
$db = Typecho_Db::get();
$user = Typecho_Widget::widget('Widget_User');
$user->execute();
$userId = $user->uid;
$result['post']['allowComment'] = "1";
$result['post']['allowPing'] = "1";
$result['post']['allowFeed'] = "1";
$result['post']['authorId'] = $userId;
$result['post']['slug'] = $result['post']['cid'];
//文章是否存在
$temp = $db->fetchRow($db->select('cid')
->from('table.contents')
->where('table.contents.cid = ?', $result['post']['cid'])->limit(1));
if ($temp) {
$update = $db->update('table.contents')->rows($result['post'])->where('table.contents.cid = ?', $result['post']['cid'])->limit(1);
$db->query($update);
} else {
$insert = $db->insert('table.contents')
->rows($result['post']);
$db->query($insert);
}
//插入tag
Widget_Abstract_Comments::widget('Widget_Contents_Post_Edit')->setTags($result["post"]["cid"], $result['tags']);
//插入分类,得到分类id
foreach ($result['categories'] as &$category) {
$t = $db->fetchRow($db->select('table.metas.mid')
->from('table.metas')->where('name <=> ? and type <=> ?', $category, 'category')->limit(1));
if (!$t) {
$options['name'] = $category;
$options['slug'] = $category;
$options['type'] = 'category';
$options['order'] = 0;
$category = $db->query($db->insert('table.metas')->rows($options));
} else {
$category = $t['mid'];
}
}
Widget_Abstract_Comments::widget('Widget_Contents_Post_Edit')->setCategories($result["post"]["cid"], $result['categories']);
$str = array('msg' => "success", 'code' => 1, 'data' => $aid);
} else {
if ($result != null) {
$str = array('msg' => $result . "(如果是没有操作权限,请查看是否为cookie错误或者过期)", 'code' => 0, 'data' => $aid);
} else {
$str = array('msg' => "result is null", 'code' => 0, 'data' => $aid);
@error_log(json_encode($result));
}
}
} catch (Error $e) {
$str = array('msg' => $e->getMessage(), 'code' => 0, 'data' => $aid);
} catch (Typecho_Exception $e) {
$str = array('msg' => $e->getMessage(), 'code' => 0, 'data' => $aid);
} catch (Exception $e) {
$str = array('msg' => $e->getMessage(), 'code' => 0, 'data' => $aid);
}
//返回json数据
$json = json_encode($str);
echo $json;
}
/**
* 添加文章id列表
* @throws Typecho_Exception
* @throws Typecho_Plugin_Exception
*/
public function get_articles_id()
{
header('Content-Type:text/json;charset=utf-8');
$user = Typecho_Widget::widget('Widget_User');
if (!$user->pass('administrator', false)) {
return;
}
$user->execute();
//得到config的输入框的值
$csdn = Helper::options()->plugin('CSDN');
$username = $csdn->UserName;
$usertoken = $csdn->UserToken;
$userinfo = $csdn->UserInfo;
if ($username == null || $usertoken == null || $userinfo == null) {
$str = array('msg' => '请在设置界面填写所需参数', 'code' => 0);
//返回json数据
$jsonencode = json_encode($str);
echo $jsonencode;
return;
}
//初始化cookie
CSDN_Plugin::$context = CSDN_Plugin::init_header($username, $userinfo, $usertoken);
//得到文章链接的正则
CSDN_Plugin::$r_article = '/https\:\/\/blog\.csdn\.net\/' . $username . '\/article\/details\/[0-9]+/';
//得到文章id的正则
CSDN_Plugin::$source_url = "https://blog.csdn.net/$username/phoenix/article/list/";
CSDN_Plugin::$article_url = "https://blog.csdn.net/$username/article/details/";
//博客页面页数
$i = 1;
$str = null;
$a_list = array();
do {
$content = file_get_contents(CSDN_Plugin::$source_url . $i);
// $json = CSDN_Plugin::decodeUnicode($content);
$json = json_decode($content, true);
if ($json['status'] == 1) {
$article_list = $json['data']['article_list'];
//取得页数
$page_num = ceil($json['data']['total'] / 20);
foreach ($article_list as $article) {
$a_list = array_merge($a_list, array(array($article['ArticleId'], $article['PostTime'])));
}
$i += 1;
} else {
$str = array('msg' => '用户不存在或者网络不好', 'code' => 0);
break;
}
} while ($page_num >= $i);
//返回博客id的列表
if (!$str) {
$str = array('data' => $a_list, 'code' => 1);
}
//返回json数据
$jsonencode = json_encode($str);
echo $jsonencode;
}
/**
* 得到要输入数据库中的文章信息
* @param $aid
* @param $date
* @return array 文章的信息
*/
function get_post_info($aid, $date)
{
//得到日期
$create_date = strtotime($date);
//获取markdown格式的字符串
$content = file_get_contents("https://blog-console-api.csdn.net/v1/editor/getArticle?id=$aid", false, CSDN_Plugin::$context);
$json = json_decode($content, true);
//解析
if (strcmp($json["msg"], "success") == 0) {
$description = $json["data"]["description"];
$markdown = '<!--markdown-->' . $description . '<!--more-->' . $json["data"]["markdowncontent"];
$title = $json["data"]["title"];
$categories = $json['data']['categories'];
str_replace(',', ',', $categories);
$categories = array_unique(array_map('trim', explode(',', $categories)));
$tags = $json['data']['tags'];
$post = array('title' => $title, 'type' => 'post', 'cid' => $aid, 'text' => $markdown, 'created' => $create_date, 'modified' => time());
return array('post' => $post, "tags" => $tags, "categories" => $categories, "description" => $description);
} else {
return $json['msg'];
}
}
/**
* 用到的js和css
*
* @access public
* @return void
*/
public
static function header()
{
$Path = Helper::options()->pluginUrl . '/CSDN/';
echo '<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />';
echo '<link rel="stylesheet" type="text/css" href="' . $Path . 'css/my_bar.css"/>' . "\n\r";;
echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/nanobar/0.4.2/nanobar.min.js" integrity="sha512-1Al+dnfE+1gI7IBmpUZ8XnZ3l3Nv6cyA+XgdtlaptVNxJcWWRzHxOPzT+2pbp52qtXa2jkwk0MWYSmxslMsHCQ==" crossorigin="anonymous"></script>' . "\n\r";
echo '<script type="text/javascript" src="' . $Path . 'js/add_post.js"></script>' . "\n\r";
echo '<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>' . "\n\r";
echo '<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>' . "\n\r";
}
/**
* 初始化header
* @param $username
* @param $userinfo
* @param $usertoken
* @return resource
*/
static function init_header($username, $userinfo, $usertoken)
{
$cookie = "UserName=$username;UserInfo=$userinfo;UserToken=$usertoken;";
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Accept-language: en\r\n" .
"Cookie:" . $cookie . "\r\n"
)
);
return stream_context_create($opts);
}
/**
* unicode解码
* @param $str
* @return null|string|string[]
*/
static function decodeUnicode($str)
{
$callbacks[$str] = function ($matches) use ($str) {
return iconv("UCS-2BE", "UTF-8", pack("H*", $matches[1]));
};
return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', $callbacks[$str], $str);
}
// 失败
// function publish($result)
// {
// //填充文章的相关字段信息。
// $contents =
// array(
// 'title' => $result["post"]["title"],
// 'text' => $result["post"]["title"],
// 'fieldNames' => array(),
// 'fieldTypes' => array(),
// 'fieldValues' => array(),
// 'cid' => '',
// 'do' => 'publish',
// 'markdown' => '1',
// 'date' => $result["post"]["data"],
// 'category' => array($result["post"]["categories"]),
// 'tags' => $result["post"]["tags"],
// 'visibility' => 'publish',
// 'password' => '',
// 'allowComment' => '1',
// 'allowPing' => '1',
// 'allowFeed' => '1',
// 'trackback' => '',
// );
//
// $request = Typecho_Request::getInstance();
// //设置token,绕过安全限制
// $security = Typecho_Widget::widget('Widget_Security');
// $request->setParam('_', $security->getToken($this->request->getReferer()));
// $request->setParams($contents);
// //设置时区,否则文章的发布时间会查8H
// date_default_timezone_set('PRC');
//
// //执行添加文章操作
// $widgetName = 'Widget_Contents_Post_Edit';
// $reflectionWidget = new ReflectionClass($widgetName);
// if ($reflectionWidget->implementsInterface('Widget_Interface_Do')) {
// Typecho_Widget::widget($widgetName)->action();
// return true;
// } else {
// return false;
// }
//
// }
}