-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAction.php
124 lines (112 loc) · 2.94 KB
/
Action.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
<?php
/**
* 自动生成缩略名
*
* @package BaiduSlug
* @author Chuck
* @version 1.0
*/
class BaiduSlug_Action extends Typecho_Widget implements Widget_Interface_Do
{
/**
* 插件配置
*
* @access private
* @var Typecho_Config
*/
private $_config;
/**
* 构造方法
*
* @access public
* @var void
*/
public function __construct($request, $response, $params = NULL)
{
parent::__construct($request, $response, $params);
/* 获取插件配置 */
$this->_config = parent::widget('Widget_Options')->plugin('BaiduSlug');
}
/**
* 转换为英文或拼音
*
* @access public
* @return void
*/
public function transform()
{
$word = $this->request->filter('strip_tags', 'trim', 'xss')->q;
if (empty($word)) {
return;
}
$result = call_user_func(array($this, $this->_config->mode), $word);
$result = preg_replace('/[[:punct:]]/', '', $result);
$result = str_replace(array(' ', ' '), '-', strtolower(trim($result)));
$message = array('result' => $result);
$this->response->throwJson($message);
}
//百度加密
public function buildSign($query, $appID, $salt, $secKey)
{
$str = $appID . $query . $salt . $secKey;
$ret = md5($str);
return $ret;
}
/**
* 百度翻译
*
* @access public
* @param string $word 待翻译的字符串
* @return string
*/
public function baidu($word)
{
$data = array('appid' => $this->_config->bdappid, 'q' => $word, 'from' => 'zh', 'to' => 'en', 'salt' => rand(10000,99999));
$data['sign'] = $this->buildSign($word, $this->_config->bdappid, $data['salt'], $this->_config->bdkey);
$data = http_build_query($data);
$url = 'http://api.fanyi.baidu.com/api/trans/vip/translate' . '?' . $data;
$result = $this->translate($url);
if (isset($result['error_code'])) {
return;
}
return $result['trans_result'][0]['dst'];
}
/**
* 发送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
* @param string $word 待转换的字符串
* @return string
*/
public function pinyin($word)
{
require_once 'Pinyin.php';
$pinyin = new Pinyin();
return $pinyin->stringToPinyin($word);
}
/**
* 绑定动作
*
* @access public
* @return void
*/
public function action()
{
$this->on($this->request->isAjax())->transform();
}
}