1
0
Fork 0
mirror of https://github.com/yunluo/gdk.git synced 2024-05-04 23:43:23 +02:00

推送一些文件

This commit is contained in:
云落 2021-10-06 21:44:41 +08:00
parent c55cf1aa6c
commit d55d06507c
22 changed files with 1531 additions and 131 deletions

9
.gitignore vendored
View file

@ -1,4 +1,7 @@
desktop.ini
cache/*.txt
.coding-ide/*
.ecloud/*
.git/
public/cache/*.txt
*.ini
.vscode/*
.SynologyWorkingDirectory/*
*/cache/*

View file

@ -64,7 +64,7 @@ jQuery(function($) { /**声明加载jQuery */
*/
function setCookie(e, t, o) {
var i = new Date;
i.setDate(i.getDate() + o), document.cookie = e + "=" + escape(t) + (null == o ? "" : ";expires=" + i.toGMTString())
i.setDate(i.getDate() + o), document.cookie = e + "=" + escape(t) + (null == o ? "" : ";expires=" + i.toGMTString()) + ";Secure"
};
/**
*

45
class/ai.php Normal file
View file

@ -0,0 +1,45 @@
<?php
include 'ai/AipNlp.php'; //文本分析接口
//include 'ai/AipContentCensor.php'; //评论审核接口
function gdk_newsSummary($post_ID){
// 你的 APPID AK SK
$APP_ID = '22837593';
$API_KEY = 'hYYE9TWp0T5Um5b0p1FUALlw';
$SECRET_KEY = 'otXMPD6TGGWKjKnfm9aB9USErsQrH2HD';
$Nlpclient = new AipNlp($APP_ID, $API_KEY, $SECRET_KEY);
$post = get_post( $post_ID );
$content = '从官网上面看统信操作系统,目前分为三个版本,第一种是统信操作系统专业版,然后是统信操作系统个人版,然后是统信操作系统社区版,也就是现在的深度系统,这里面要注意一点,由于深度系统本身已经非常有知名度,而且在海外也有一定的知名度,所以统信操作系统社区并没有改名,仍然使用深度系统名字。
在三个版本区别当中,很明显专业版是提供给党政军等机构使用,个人版可以给个人使用的,然后社区板和个人版差不多,但是权限要比个人版要更多也更自由一点,其中专业版是需要付费的,然后个人版是有增值服务的,然后社区版是完全免费的。
这里面有一点要说明一下个人版是没有root权限的如果需要root权限还要开通开发者权限开发者权限需要注册的然后社区版是默认自带root权限的。没有root的权限对于很多linux系统爱好者来说是不太友好的但是对于个人用户来说这个却是非常重要的因为自带root权限对一些对电脑不太熟悉的人来说实在是太危险了很容易把电脑或者系统搞坏的。';
$maxSummaryLen = 300;
// 带参数调用新闻摘要接口
$result = $Nlpclient->newsSummary($content, $maxSummaryLen);
var_dump($result);
$my_post = array(
'ID' => $post_ID,
'post_excerpt' => $result //摘要信息
);
//入库
//wp_insert_post( $my_post );
}
add_action('publish_post', 'gdk_newsSummary', 0);
add_action('update_post', 'gdk_newsSummary', 0);

View file

@ -0,0 +1,25 @@
<?php
/*
* Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'AipImageCensor.php';
/**
* 内容审核
*/
class AipContentCensor extends AipImageCensor{
}

197
class/ai/AipNlp.php Normal file
View file

@ -0,0 +1,197 @@
<?php
/*
* Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
include_once 'lib/AipBase.php';
class AipNlp extends AipBase {
/**
* 评论观点抽取 comment_tag api url
* @var string
*/
private $commentTagUrl = 'https://aip.baidubce.com/rpc/2.0/nlp/v2/comment_tag';
/**
* 情感倾向分析 sentiment_classify api url
* @var string
*/
private $sentimentClassifyUrl = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify';
/**
* 文章标签 keyword api url
* @var string
*/
private $keywordUrl = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword';
/**
* 文章分类 topic api url
* @var string
*/
private $topicUrl = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/topic';
/**
* 文本纠错 ecnet api url
* @var string
*/
private $ecnetUrl = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/ecnet';
/**
* 新闻摘要接口 news_summary api url
* @var string
*/
private $newsSummaryUrl = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/news_summary';
/**
* 格式化结果
* @param $content string
* @return mixed
*/
protected function proccessResult($content){
return json_decode(mb_convert_encoding($content, 'UTF8', 'GBK'), true, 512, JSON_BIGINT_AS_STRING);
}
/**
* 评论观点抽取接口
*
* @param string $text - 评论内容GBK编码最大10240字节
* @param array $options - 可选参数对象key: value都为string类型
* @description options列表:
* type 评论行业类型默认为4餐饮美食
* @return array
*/
public function commentTag($text, $options=array()){
$data = array();
$data['text'] = $text;
$data = array_merge($data, $options);
$data = mb_convert_encoding(json_encode($data), 'GBK', 'UTF8');
return $this->request($this->commentTagUrl, $data);
}
/**
* 情感倾向分析接口
*
* @param string $text - 文本内容GBK编码最大102400字节
* @param array $options - 可选参数对象key: value都为string类型
* @description options列表:
* @return array
*/
public function sentimentClassify($text, $options=array()){
$data = array();
$data['text'] = $text;
$data = array_merge($data, $options);
$data = mb_convert_encoding(json_encode($data), 'GBK', 'UTF8');
return $this->request($this->sentimentClassifyUrl, $data);
}
/**
* 文章标签接口
*
* @param string $title - 篇章的标题最大80字节
* @param string $content - 篇章的正文最大65535字节
* @param array $options - 可选参数对象key: value都为string类型
* @description options列表:
* @return array
*/
public function keyword($title, $content, $options=array()){
$data = array();
$data['title'] = $title;
$data['content'] = $content;
$data = array_merge($data, $options);
$data = mb_convert_encoding(json_encode($data), 'GBK', 'UTF8');
return $this->request($this->keywordUrl, $data);
}
/**
* 文章分类接口
*
* @param string $title - 篇章的标题最大80字节
* @param string $content - 篇章的正文最大65535字节
* @param array $options - 可选参数对象key: value都为string类型
* @description options列表:
* @return array
*/
public function topic($title, $content, $options=array()){
$data = array();
$data['title'] = $title;
$data['content'] = $content;
$data = array_merge($data, $options);
$data = mb_convert_encoding(json_encode($data), 'GBK', 'UTF8');
return $this->request($this->topicUrl, $data);
}
/**
* 文本纠错接口
*
* @param string $text - 待纠错文本输入限制511字节
* @param array $options - 可选参数对象key: value都为string类型
* @description options列表:
* @return array
*/
public function ecnet($text, $options=array()){
$data = array();
$data['text'] = $text;
$data = array_merge($data, $options);
$data = mb_convert_encoding(json_encode($data), 'GBK', 'UTF8');
return $this->request($this->ecnetUrl, $data);
}
/**
* 新闻摘要接口接口
*
* @param string $content - 字符串限3000字符数以内字符串仅支持GBK编码长度需小于3000字符数即6000字节请输入前确认字符数没有超限若字符数超长会返回错误。正文中如果包含段落信息请使用"\n"分隔,段落信息算法中有重要的作用,请尽量保留
* @param integer $maxSummaryLen - 此数值将作为摘要结果的最大长度。例如原文长度1000字本参数设置为150则摘要结果的最大长度是150字推荐最优区间200-500
* @param array $options - 可选参数对象key: value都为string类型
* @description options列表:
* title 字符串限200字符数字符串仅支持GBK编码长度需小于200字符数即400字节请输入前确认字符数没有超限若字符数超长会返回错误。标题在算法中具有重要的作用若文章确无标题输入参数的“标题”字段为空即可
* @return array
*/
public function newsSummary($content, $maxSummaryLen, $options=array()){
$data = array();
$data['content'] = $content;
$data['max_summary_len'] = $maxSummaryLen;
$data = array_merge($data, $options);
$data = mb_convert_encoding(json_encode($data), 'GBK', 'UTF8');
return $this->request($this->newsSummaryUrl, $data);
}
}

345
class/ai/lib/AipBCEUtil.php Normal file
View file

@ -0,0 +1,345 @@
<?php
/*
* Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* BCE Util
*/
class AipHttpUtil
{
// 根据RFC 3986除了
// 1.大小写英文字符
// 2.阿拉伯数字
// 3.点'.'、波浪线'~'、减号'-'以及下划线'_'
// 以外都要编码
public static $PERCENT_ENCODED_STRINGS;
//填充编码数组
public static function __init()
{
AipHttpUtil::$PERCENT_ENCODED_STRINGS = array();
for ($i = 0; $i < 256; ++$i) {
AipHttpUtil::$PERCENT_ENCODED_STRINGS[$i] = sprintf("%%%02X", $i);
}
//a-z不编码
foreach (range('a', 'z') as $ch) {
AipHttpUtil::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
}
//A-Z不编码
foreach (range('A', 'Z') as $ch) {
AipHttpUtil::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
}
//0-9不编码
foreach (range('0', '9') as $ch) {
AipHttpUtil::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
}
//以下4个字符不编码
AipHttpUtil::$PERCENT_ENCODED_STRINGS[ord('-')] = '-';
AipHttpUtil::$PERCENT_ENCODED_STRINGS[ord('.')] = '.';
AipHttpUtil::$PERCENT_ENCODED_STRINGS[ord('_')] = '_';
AipHttpUtil::$PERCENT_ENCODED_STRINGS[ord('~')] = '~';
}
/**
* 在uri编码中不能对'/'编码
* @param string $path
* @return string
*/
public static function urlEncodeExceptSlash($path)
{
return str_replace("%2F", "/", AipHttpUtil::urlEncode($path));
}
/**
* 使用编码数组编码
* @param string $path
* @return string
*/
public static function urlEncode($value)
{
$result = '';
for ($i = 0; $i < strlen($value); ++$i) {
$result .= AipHttpUtil::$PERCENT_ENCODED_STRINGS[ord($value[$i])];
}
return $result;
}
/**
* 生成标准化QueryString
* @param array $parameters
* @return array
*/
public static function getCanonicalQueryString(array $parameters)
{
//没有参数,直接返回空串
if (count($parameters) == 0) {
return '';
}
$parameterStrings = array();
foreach ($parameters as $k => $v) {
//跳过Authorization字段
if (strcasecmp('Authorization', $k) == 0) {
continue;
}
if (!isset($k)) {
throw new \InvalidArgumentException(
"parameter key should not be null"
);
}
if (isset($v)) {
//对于有值的,编码后放在=号两边
$parameterStrings[] = AipHttpUtil::urlEncode($k)
. '=' . AipHttpUtil::urlEncode((string) $v);
} else {
//对于没有值的只将key编码后放在=号的左边,右边留空
$parameterStrings[] = AipHttpUtil::urlEncode($k) . '=';
}
}
//按照字典序排序
sort($parameterStrings);
//使用'&'符号连接它们
return implode('&', $parameterStrings);
}
/**
* 生成标准化uri
* @param string $path
* @return string
*/
public static function getCanonicalURIPath($path)
{
//空路径设置为'/'
if (empty($path)) {
return '/';
} else {
//所有的uri必须以'/'开头
if ($path[0] == '/') {
return AipHttpUtil::urlEncodeExceptSlash($path);
} else {
return '/' . AipHttpUtil::urlEncodeExceptSlash($path);
}
}
}
/**
* 生成标准化http请求头串
* @param array $headers
* @return array
*/
public static function getCanonicalHeaders($headers)
{
//如果没有headers则返回空串
if (count($headers) == 0) {
return '';
}
$headerStrings = array();
foreach ($headers as $k => $v) {
//跳过key为null的
if ($k === null) {
continue;
}
//如果value为null则赋值为空串
if ($v === null) {
$v = '';
}
//trim后再encode之后使用':'号连接起来
$headerStrings[] = AipHttpUtil::urlEncode(strtolower(trim($k))) . ':' . AipHttpUtil::urlEncode(trim($v));
}
//字典序排序
sort($headerStrings);
//用'\n'把它们连接起来
return implode("\n", $headerStrings);
}
}
AipHttpUtil::__init();
class AipSignOption
{
const EXPIRATION_IN_SECONDS = 'expirationInSeconds';
const HEADERS_TO_SIGN = 'headersToSign';
const TIMESTAMP = 'timestamp';
const DEFAULT_EXPIRATION_IN_SECONDS = 1800;
const MIN_EXPIRATION_IN_SECONDS = 300;
const MAX_EXPIRATION_IN_SECONDS = 129600;
}
class AipSampleSigner
{
const BCE_AUTH_VERSION = "bce-auth-v1";
const BCE_PREFIX = 'x-bce-';
//不指定headersToSign情况下默认签名http头包括
// 1.host
// 2.content-length
// 3.content-type
// 4.content-md5
public static $defaultHeadersToSign;
public static function __init()
{
AipSampleSigner::$defaultHeadersToSign = array(
"host",
"content-length",
"content-type",
"content-md5",
);
}
/**
* 签名
* @param array $credentials
* @param string $httpMethod
* @param string $path
* @param array $headers
* @param string $params
* @param array $options
* @return string
*/
public static function sign(
array $credentials,
$httpMethod,
$path,
$headers,
$params,
$options = array()
) {
//设定签名有效时间
if (!isset($options[AipSignOption::EXPIRATION_IN_SECONDS])) {
//默认值1800秒
$expirationInSeconds = AipSignOption::DEFAULT_EXPIRATION_IN_SECONDS;
} else {
$expirationInSeconds = $options[AipSignOption::EXPIRATION_IN_SECONDS];
}
//解析ak sk
$accessKeyId = $credentials['ak'];
$secretAccessKey = $credentials['sk'];
//设定时间戳注意如果自行指定时间戳需要为UTC时间
if (!isset($options[AipSignOption::TIMESTAMP])) {
//默认值当前时间
$timestamp = gmdate('Y-m-d\TH:i:s\Z');
} else {
$timestamp = $options[AipSignOption::TIMESTAMP];
}
//生成authString
$authString = AipSampleSigner::BCE_AUTH_VERSION . '/' . $accessKeyId . '/'
. $timestamp . '/' . $expirationInSeconds;
//使用sk和authString生成signKey
$signingKey = hash_hmac('sha256', $authString, $secretAccessKey);
//生成标准化URI
$canonicalURI = AipHttpUtil::getCanonicalURIPath($path);
//生成标准化QueryString
$canonicalQueryString = AipHttpUtil::getCanonicalQueryString($params);
//填充headersToSign也就是指明哪些header参与签名
$headersToSign = null;
if (isset($options[AipSignOption::HEADERS_TO_SIGN])) {
$headersToSign = $options[AipSignOption::HEADERS_TO_SIGN];
}
//生成标准化header
$canonicalHeader = AipHttpUtil::getCanonicalHeaders(
AipSampleSigner::getHeadersToSign($headers, $headersToSign)
);
//整理headersToSign以';'号连接
$signedHeaders = '';
if ($headersToSign !== null) {
$signedHeaders = strtolower(
trim(implode(";", $headersToSign))
);
}
//组成标准请求串
$canonicalRequest = "$httpMethod\n$canonicalURI\n"
. "$canonicalQueryString\n$canonicalHeader";
//使用signKey和标准请求串完成签名
$signature = hash_hmac('sha256', $canonicalRequest, $signingKey);
//组成最终签名串
$authorizationHeader = "$authString/$signedHeaders/$signature";
return $authorizationHeader;
}
/**
* 根据headsToSign过滤应该参与签名的header
* @param array $headers
* @param array $headersToSign
* @return array
*/
public static function getHeadersToSign($headers, $headersToSign)
{
$arr = array();
foreach ($headersToSign as $value) {
$arr[] = strtolower(trim($value));
}
//value被trim后为空串的header不参与签名
$result = array();
foreach ($headers as $key => $value) {
if (trim($value) !== '') {
$key = strtolower(trim($key));
if (in_array($key, $arr)) {
$result[$key] = $value;
}
}
}
//返回需要参与签名的header
return $result;
}
/**
* 检查header是不是默认参加签名的
* 1.是host、content-type、content-md5、content-length之一
* 2.以x-bce开头
* @param array $header
* @return boolean
*/
public static function isDefaultHeaderToSign($header)
{
$header = strtolower(trim($header));
if (in_array($header, AipSampleSigner::$defaultHeadersToSign)) {
return true;
}
return substr_compare($header, AipSampleSigner::BCE_PREFIX, 0, strlen(AipSampleSigner::BCE_PREFIX)) == 0;
}
}
AipSampleSigner::__init();

394
class/ai/lib/AipBase.php Normal file
View file

@ -0,0 +1,394 @@
<?php
/*
* Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'AipHttpClient.php';
require_once 'AipBCEUtil.php';
/**
* Aip Base 基类
*/
class AipBase {
/**
* 获取access token url
* @var string
*/
protected $accessTokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
/**
* 反馈接口
* @var string
*/
protected $reportUrl = 'https://aip.baidubce.com/rpc/2.0/feedback/v1/report';
/**
* appId
* @var string
*/
protected $appId = '';
/**
* apiKey
* @var string
*/
protected $apiKey = '';
/**
* secretKey
* @var string
*/
protected $secretKey = '';
/**
* 权限
* @var array
*/
protected $scope = 'brain_all_scope';
/**
* @param string $appId
* @param string $apiKey
* @param string $secretKey
*/
public function __construct($appId, $apiKey, $secretKey){
$this->appId = trim($appId);
$this->apiKey = trim($apiKey);
$this->secretKey = trim($secretKey);
$this->isCloudUser = null;
$this->client = new AipHttpClient();
$this->version = '2_2_19';
$this->proxies = array();
}
/**
* 查看版本
* @return string
*
*/
public function getVersion(){
return $this->version;
}
/**
* 连接超时
* @param int $ms 毫秒
*/
public function setConnectionTimeoutInMillis($ms){
$this->client->setConnectionTimeoutInMillis($ms);
}
/**
* 响应超时
* @param int $ms 毫秒
*/
public function setSocketTimeoutInMillis($ms){
$this->client->setSocketTimeoutInMillis($ms);
}
/**
* 代理
* @param array $proxy
* @return string
*
*/
public function setProxies($proxies){
$this->client->setConf($proxies);
}
/**
* 处理请求参数
* @param string $url
* @param array $params
* @param array $data
* @param array $headers
*/
protected function proccessRequest($url, &$params, &$data, $headers){
$params['aipSdk'] = 'php';
$params['aipSdkVersion'] = $this->version;
}
/**
* Api 请求
* @param string $url
* @param mixed $data
* @return mixed
*/
protected function request($url, $data, $headers=array()){
try{
$result = $this->validate($url, $data);
if($result !== true){
return $result;
}
$params = array();
$authObj = $this->auth();
if($this->isCloudUser === false){
$params['access_token'] = $authObj['access_token'];
}
// 特殊处理
$this->proccessRequest($url, $params, $data, $headers);
$headers = $this->getAuthHeaders('POST', $url, $params, $headers);
$response = $this->client->post($url, $data, $params, $headers);
$obj = $this->proccessResult($response['content']);
if(!$this->isCloudUser && isset($obj['error_code']) && $obj['error_code'] == 110){
$authObj = $this->auth(true);
$params['access_token'] = $authObj['access_token'];
$response = $this->client->post($url, $data, $params, $headers);
$obj = $this->proccessResult($response['content']);
}
if(empty($obj) || !isset($obj['error_code'])){
$this->writeAuthObj($authObj);
}
}catch(Exception $e){
return array(
'error_code' => 'SDK108',
'error_msg' => 'connection or read data timeout',
);
}
return $obj;
}
/**
* Api 多个并发请求
* @param string $url
* @param mixed $data
* @return mixed
*/
protected function multi_request($url, $data){
try{
$params = array();
$authObj = $this->auth();
$headers = $this->getAuthHeaders('POST', $url);
if($this->isCloudUser === false){
$params['access_token'] = $authObj['access_token'];
}
$responses = $this->client->multi_post($url, $data, $params, $headers);
$is_success = false;
foreach($responses as $response){
$obj = $this->proccessResult($response['content']);
if(empty($obj) || !isset($obj['error_code'])){
$is_success = true;
}
if(!$this->isCloudUser && isset($obj['error_code']) && $obj['error_code'] == 110){
$authObj = $this->auth(true);
$params['access_token'] = $authObj['access_token'];
$responses = $this->client->post($url, $data, $params, $headers);
break;
}
}
if($is_success){
$this->writeAuthObj($authObj);
}
$objs = array();
foreach($responses as $response){
$objs[] = $this->proccessResult($response['content']);
}
}catch(Exception $e){
return array(
'error_code' => 'SDK108',
'error_msg' => 'connection or read data timeout',
);
}
return $objs;
}
/**
* 格式检查
* @param string $url
* @param array $data
* @return mix
*/
protected function validate($url, &$data){
return true;
}
/**
* 格式化结果
* @param $content string
* @return mixed
*/
protected function proccessResult($content){
return json_decode($content, true);
}
/**
* 返回 access token 路径
* @return string
*/
private function getAuthFilePath(){
return dirname(__FILE__) . DIRECTORY_SEPARATOR . md5($this->apiKey);
}
/**
* 写入本地文件
* @param array $obj
* @return void
*/
private function writeAuthObj($obj){
if($obj === null || (isset($obj['is_read']) && $obj['is_read'] === true)){
return;
}
$obj['time'] = time();
$obj['is_cloud_user'] = $this->isCloudUser;
@file_put_contents($this->getAuthFilePath(), json_encode($obj));
}
/**
* 读取本地缓存
* @return array
*/
private function readAuthObj(){
$content = @file_get_contents($this->getAuthFilePath());
if($content !== false){
$obj = json_decode($content, true);
$this->isCloudUser = $obj['is_cloud_user'];
$obj['is_read'] = true;
if($this->isCloudUser || $obj['time'] + $obj['expires_in'] - 30 > time()){
return $obj;
}
}
return null;
}
/**
* 认证
* @param bool $refresh 是否刷新
* @return array
*/
private function auth($refresh=false){
//非过期刷新
if(!$refresh){
$obj = $this->readAuthObj();
if(!empty($obj)){
return $obj;
}
}
$response = $this->client->get($this->accessTokenUrl, array(
'grant_type' => 'client_credentials',
'client_id' => $this->apiKey,
'client_secret' => $this->secretKey,
));
$obj = json_decode($response['content'], true);
$this->isCloudUser = !$this->isPermission($obj);
return $obj;
}
/**
* 判断认证是否有权限
* @param array $authObj
* @return boolean
*/
protected function isPermission($authObj)
{
if(empty($authObj) || !isset($authObj['scope'])){
return false;
}
$scopes = explode(' ', $authObj['scope']);
return in_array($this->scope, $scopes);
}
/**
* @param string $method HTTP method
* @param string $url
* @param array $param 参数
* @return array
*/
private function getAuthHeaders($method, $url, $params=array(), $headers=array()){
//不是云的老用户则不用在header中签名 认证
if($this->isCloudUser === false){
return $headers;
}
$obj = parse_url($url);
if(!empty($obj['query'])){
foreach(explode('&', $obj['query']) as $kv){
if(!empty($kv)){
list($k, $v) = explode('=', $kv, 2);
$params[$k] = $v;
}
}
}
//UTC 时间戳
$timestamp = gmdate('Y-m-d\TH:i:s\Z');
$headers['Host'] = isset($obj['port']) ? sprintf('%s:%s', $obj['host'], $obj['port']) : $obj['host'];
$headers['x-bce-date'] = $timestamp;
//签名
$headers['authorization'] = AipSampleSigner::sign(array(
'ak' => $this->apiKey,
'sk' => $this->secretKey,
), $method, $obj['path'], $headers, $params, array(
'timestamp' => $timestamp,
'headersToSign' => array_keys($headers),
));
return $headers;
}
/**
* 反馈
*
* @param array $feedbacks
* @return array
*/
public function report($feedback){
$data = array();
$data['feedback'] = $feedback;
return $this->request($this->reportUrl, $data);
}
/**
* 通用接口
* @param string $url
* @param array $data
* @param array header
* @return array
*/
public function post($url, $data, $headers=array()){
return $this->request($url, $data, $headers);
}
}

View file

@ -0,0 +1,214 @@
<?php
/*
* Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Http Client
*/
class AipHttpClient{
/**
* HttpClient
* @param array $headers HTTP header
*/
public function __construct($headers=array()){
$this->headers = $this->buildHeaders($headers);
$this->connectTimeout = 60000;
$this->socketTimeout = 60000;
$this->conf = array();
}
/**
* 连接超时
* @param int $ms 毫秒
*/
public function setConnectionTimeoutInMillis($ms){
$this->connectTimeout = $ms;
}
/**
* 响应超时
* @param int $ms 毫秒
*/
public function setSocketTimeoutInMillis($ms){
$this->socketTimeout = $ms;
}
/**
* 配置
* @param array $conf
*/
public function setConf($conf){
$this->conf = $conf;
}
/**
* 请求预处理
* @param resource $ch
*/
public function prepare($ch){
foreach($this->conf as $key => $value){
curl_setopt($ch, $key, $value);
}
}
/**
* @param string $url
* @param array $data HTTP POST BODY
* @param array $param HTTP URL
* @param array $headers HTTP header
* @return array
*/
public function post($url, $data=array(), $params=array(), $headers=array()){
$url = $this->buildUrl($url, $params);
$headers = array_merge($this->headers, $this->buildHeaders($headers));
$ch = curl_init();
$this->prepare($ch);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->socketTimeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->connectTimeout);
$content = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code === 0){
throw new Exception(curl_error($ch));
}
curl_close($ch);
return array(
'code' => $code,
'content' => $content,
);
}
/**
* @param string $url
* @param array $datas HTTP POST BODY
* @param array $param HTTP URL
* @param array $headers HTTP header
* @return array
*/
public function multi_post($url, $datas=array(), $params=array(), $headers=array()){
$url = $this->buildUrl($url, $params);
$headers = array_merge($this->headers, $this->buildHeaders($headers));
$chs = array();
$result = array();
$mh = curl_multi_init();
foreach($datas as $data){
$ch = curl_init();
$chs[] = $ch;
$this->prepare($ch);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->socketTimeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->connectTimeout);
curl_multi_add_handle($mh, $ch);
}
$running = null;
do{
curl_multi_exec($mh, $running);
usleep(100);
}while($running);
foreach($chs as $ch){
$content = curl_multi_getcontent($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result[] = array(
'code' => $code,
'content' => $content,
);
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
return $result;
}
/**
* @param string $url
* @param array $param HTTP URL
* @param array $headers HTTP header
* @return array
*/
public function get($url, $params=array(), $headers=array()){
$url = $this->buildUrl($url, $params);
$headers = array_merge($this->headers, $this->buildHeaders($headers));
$ch = curl_init();
$this->prepare($ch);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->socketTimeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->connectTimeout);
$content = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code === 0){
throw new Exception(curl_error($ch));
}
curl_close($ch);
return array(
'code' => $code,
'content' => $content,
);
}
/**
* 构造 header
* @param array $headers
* @return array
*/
private function buildHeaders($headers){
$result = array();
foreach($headers as $k => $v){
$result[] = sprintf('%s:%s', $k, $v);
}
return $result;
}
/**
*
* @param string $url
* @param array $params 参数
* @return string
*/
private function buildUrl($url, $params){
if(!empty($params)){
$str = http_build_query($params);
return $url . (strpos($url, '?') === false ? '?' : '&') . $str;
}else{
return $url;
}
}
}

View file

@ -12,4 +12,4 @@ include 'points/points.php'; //积分功能
include 'aq_resizer.php'; //缩略图功能
include 'wechat.php'; //微信功能
//include 'ai.php'; //AI功能

View file

@ -16,6 +16,17 @@ $gdk_options = [
],
'std' => '1',
],
[
'name' => '禁用新版小工具',
'desc' => '新版小工具尚不成熟,很多主题不兼容,建议开启',
'id' => 'gdk_diasble_widgets_block',
'type' => 'radio',
'options' => [
'0' => '禁用',
'1' => '开启',
],
'std' => '1',
],
[
'name' => '禁用头部冗余代码',
'desc' => 'WordPress头部自带很多无用代码不安全且浪费建议开启',
@ -130,6 +141,7 @@ $gdk_options = [
'1' => '随机头像',
'2' => 'V2EX头像镜像',
'3' => '七牛头像镜像',
'4' => 'Cravatar',
],
'std' => '3',
],

View file

@ -7,15 +7,14 @@ if (!defined('WPINC')) {
die;
}
$current_theme = wp_get_theme();
$gdk_default_options = [];
$gdk_options = array();
$gdk_default = [];
$gdk_options = [];
include 'options-config.php';
$gdk_current_options = get_option('gdk_options_setup');
$gdk_config = get_option('gdk_options_setup');
function gdk_update_options()
{
global $gdk_default_options, $gdk_options, $gdk_current_options;
global $gdk_default, $gdk_options, $gdk_config;
foreach ($gdk_options as $panel) {
foreach ($panel as $option) {
$id = $option['id'] ?? '';
@ -25,22 +24,23 @@ function gdk_update_options()
continue;
}
$gdk_default_options[$id] = $std;
if (isset($gdk_current_options[$id])) {
$gdk_default[$id] = $std;
if (isset($gdk_config[$id])) {
continue;
}
$gdk_current_options[$id] = $std;
$gdk_config[$id] = $std;
}
}
}
gdk_update_options();
//gdk_update_options();
//获取设置选项
function gdk_option($id, $returnDefault = false)
function gdk_option($id, $Default = false)
{
global $gdk_default_options, $gdk_current_options;
return stripslashes($returnDefault ? $gdk_default_options[$id] : $gdk_current_options[$id]);
global $gdk_default, $gdk_config;
return stripslashes($Default ? $gdk_default[$id] : $gdk_config[$id]);
}
//设置页面模板
@ -66,7 +66,7 @@ if (isset($_GET['update'])) {
<div class="wp-filter">
<ul class="filter-links">
<?php
$activePanelIdx = empty($_GET['panel']) ? 0 : $_GET['panel'];
$activePanelIdx = $_GET['panel'] ?? 0;
foreach (array_keys($gdk_options) as $i => $name) {
echo '<li><a href="#panel_' . $i . '" data-panel="' . $i . '" ' . ($i == $activePanelIdx ? 'class="current"' : '') . '>' . $name . '</a></li>';
}
@ -151,10 +151,8 @@ break;
?>
<fieldset>
<?php $checkboxValues = gdk_option($id);
if (!is_array($checkboxValues)) {
$checkboxValues = [];
}
if (!is_array($checkboxValues)) $checkboxValues = [];
foreach ($option['options'] as $id => $name): ?>
<label>
<input type="checkbox" name="<?php echo $id; ?>[]" id="<?php echo $id; ?>[]" value="<?php echo $id; ?>" <?php checked(in_array($id, $checkboxValues), true); ?>>
@ -192,28 +190,6 @@ break;
</ul>
</td>
</tr>
<tr>
<th><h4>相关链接</h4></th>
<td>
<ul>
<li>主题发布页面:<a target="_blank" href="https://gitcafe.net/archives/3589.html">https://gitcafe.net/archives/3589.html</a></li>
<li>使用文档页面:<a target="_blank" href="https://gitcafe.net/archives/3275.html">https://gitcafe.net/archives/3275.html</a></li>
<li>代码托管页面:<a target="_blank" href="https://dev.tencent.com/u/googlo/p/Git/git">https://dev.tencent.com/u/googlo/p/Git/git</a></li>
<li>更新日志页面:<a target="_blank" href="https://gitcafe.net/tool/gitrss.php">https://gitcafe.net/tool/gitrss.php</a></li>
<li>主题反馈页面:<a target="_blank" href="https://support.qq.com/products/51158">https://support.qq.com/products/51158</a></li>
</ul>
</td>
</tr>
<tr>
<th><h4>第三方支持</h4></th>
<td>
<ul>
<li>感谢以下组织或个人:</li>
<li>PayJs 、Eapay、WeAuth小程序、Cloud9 、Cloud Studio、Coding 、Gitee 、Github、Server酱、jsDelivr、V2EX</li>
<li>露兜、畅萌、小影、大前端、知更鸟、yusi等等</li>
</ul>
</td>
</tr>
<tr>
<th><h4>意见反馈</h4></th>
<td>
@ -406,7 +382,7 @@ jQuery(function ($) {
$.get(ajaxurl, ajax_data,
function() {
$(".g-load").hide();
window.location.reload();
//window.location.reload();
});
});

View file

@ -65,7 +65,7 @@ function gdk_pasteup_imag()
$wp_upload_dir = wp_upload_dir();
$file = $_FILES['imageFile'];
$result = array('success' => false, 'message' => 'Null');
if (in_array($file['type'], array('image/gif', 'image/jpeg', 'image/jpg', 'image/png'))) {
if (in_array($file['type'], array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png'))) {
if ($file['error'] > 0) {
$result['message'] = 'error';
} else {
@ -335,7 +335,7 @@ add_action('wp_ajax_gdk_auto_login', 'gdk_auto_login');
add_action('wp_ajax_nopriv_gdk_auto_login', 'gdk_auto_login');
//邮箱绑定
function bind_email_check()
function gdk_bind_email_check()
{
$mail = isset($_POST['email']) ? $_POST['email'] : false;
if ($mail && $_POST['action'] == 'bind_email_check') {
@ -345,8 +345,8 @@ function bind_email_check()
}
}
}
add_action('wp_ajax_bind_email_check', 'bind_email_check');
add_action('wp_ajax_nopriv_bind_email_check', 'bind_email_check');
add_action('wp_ajax_bind_email_check', 'gdk_bind_email_check');
add_action('wp_ajax_nopriv_bind_email_check', 'gdk_bind_email_check');
//积分支付
function point_buy()

View file

@ -1,5 +1,5 @@
<?php
if (!defined('ABSPATH')) exit;
function gdk_rand_color() {
$arr=array("red","green","blue","yellow");
@ -980,35 +980,6 @@ function gdk_check($d, $u = null)
return $result; //0=无订单结果1=有订单结果,>1均为异常重复入库数据
}
//导航单页函数
function gdk_get_the_link_items($id = null)
{
$bookmarks = get_bookmarks('orderby=date&category=' . $id);
$output = '';
if (!empty($bookmarks)) {
foreach ($bookmarks as $bookmark) {
$output .= '<div class="sm-6 md-4 lg-3">
<div class="card"><a class="card-heading link-tooltip bg-lvs' . $bookmark->link_rating . '" href="' . $bookmark->link_url . '" target="_blank"><span class="card-icon"><img src="' . $bookmark->link_image . '"></span><span class="card-title">' . $bookmark->link_name . '</span></a><div class="card-body">' . $bookmark->link_description . ' : ' . $bookmark->link_notes . '</div></div></div>';
}
}
return $output;
}
function gdk_get_link_items()
{
$linkcats = get_terms('link_category', 'orderby=count&hide_empty=1&exclude=' . gdk_option('gdk_link_id'));
$result = '';
foreach ($linkcats as $linkcat) {
$result .= '<a id="' . $linkcat->term_id . '"></a><div class="panel">
<div class="panel-title card"><img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzODQgNTEyIj4gPHBhdGggZD0iTTMzNiAwSDQ4QzIxLjQ5IDAgMCAyMS40OSAwIDQ4djQ2NGwxOTItMTEyIDE5MiAxMTJWNDhjMC0yNi41MS0yMS40OS00OC00OC00OHptMCA0MjguNDNsLTE0NC04NC0xNDQgODRWNTRhNiA2IDAgMCAxIDYtNmgyNzZjMy4zMTQgMCA2IDIuNjgzIDYgNS45OTZWNDI4LjQzeiI+PC9wYXRoPiA8L3N2Zz4=">' . $linkcat->name . '</div>
<div class="panel-body">
<div class="row">';
$result .= gdk_get_the_link_items($linkcat->term_id);
$result .= '</div></div></div>';
}
return $result;
}
function gdk_get_Version()
{
echo '<input type="button" class="button button-secondary get_new_version" value="点击检测更新">';
@ -1157,11 +1128,6 @@ function gdk_weauth_qr()
return $qr64;
}
//微信登陆页面按钮
function weixin_login_button(){
echo '<p><a class="button button-large" href="' . get_permalink(gdk_page_id('weauth')) . '">微信登录</a></p><br>';
}
/**
* 微信登陆按钮
*/

View file

@ -1,5 +1,5 @@
<?php
if (!defined('ABSPATH')) exit;
if (!defined('ABSPATH')) {exit;}
if (gdk_option('gdk_cdn')) {
add_action('wp_loaded', 'gdk_cdn_start');
@ -18,10 +18,6 @@ if (gdk_option('gdk_cdn_water')) {
}
//CDN水印
//在登录框添加额外的微信登录
if (gdk_option('gdk_weauth_oauth')) {
add_action('login_form', 'weixin_login_button');
}
//文章首尾添加自定义内容
function gdk_add_content($content) {
if(is_single()) {
@ -43,6 +39,28 @@ function gdk_add_content($content) {
}
add_filter('the_content', 'gdk_add_content');
//接受奶子微信的账号信息
function get_weauth_oauth()
{
if (in_string($_SERVER['REQUEST_URI'], 'weauth')) {
$weauth_user = isset($_GET['user']) ? sanitize_text_field($_GET['user']) : false; //weauth发来用户信息
$weauth_sk = isset($_GET['sk']) ? sanitize_text_field($_GET['sk']) : false; //weauth返回的12位sk信息
$weauth_res = get_transient($weauth_sk . '-OK');
if (empty($weauth_res) && $weauth_res !== 1) {
return;
}
$weauth_user = stripslashes($weauth_user);
$weauth_user = json_decode($weauth_user, true);
$oauth_result = implode('|', $weauth_user);
set_transient($weauth_sk . '-info', $oauth_result, 60); //1分钟缓存
header('goauth: ok');
echo 'success'; //给对方服务器打个招呼
exit;
}
}
add_action('parse_request', 'get_weauth_oauth');
//社交头像
function gdk_wx_avatar($avatar, $id_or_email, $size, $default, $alt)
{
@ -79,8 +97,11 @@ function gdk_switch_get_avatar($avatar)
case 2:
$avatar = preg_replace("/http[s]{0,1}:\/\/(secure|www|\d).gravatar.com\/avatar\//", "//cdn.v2ex.com/gravatar/", $avatar);
break;
default:
case 3:
$avatar = preg_replace("/http[s]{0,1}:\/\/(secure|www|\d).gravatar.com\/avatar\//", "//dn-qiniu-avatar.qbox.me/avatar/", $avatar);
break;
default:
$avatar = preg_replace("/http[s]{0,1}:\/\/(secure|www|\d).gravatar.com\/avatar\//", "//cravatar.cn/avatar/", $avatar);
}
return $avatar;
}
@ -90,6 +111,9 @@ add_filter('get_avatar', 'gdk_switch_get_avatar');
if (gdk_option('gdk_lazyload')) {
function gdk_lazyload($content)
{
if (get_post_type() != 'post') {
return $content;
}
if (!is_feed() || !is_robots()) {
$content = preg_replace('/<img(.+)src=[\'"]([^\'"]+)[\'"](.*)>/i', "<img\$1data-original=\"\$2\" \$3>\n<noscript>\$0</noscript>", $content);
}
@ -321,8 +345,7 @@ if (gdk_option('gdk_article_list')) {
add_filter('the_content', 'article_index');
}
//插件安装自动激活页面
function gdk_page_activate()
function weauth_page_activate()
{
$awesome_page_id = get_option('weixin_page_id');
if (!$awesome_page_id) {
@ -339,7 +362,7 @@ function gdk_page_activate()
}
}
add_action('admin_init', 'gdk_page_activate');
add_action('admin_init', 'weauth_page_activate');
//强制微信登录
function force_weauth_login_url($login_url, $redirect, $force_reauth)
@ -354,7 +377,6 @@ function force_weauth_login_url($login_url, $redirect, $force_reauth)
return $login_url;
}
//修改注册页面
function change_my_register_url($url)
{
if (is_admin()) {

View file

@ -119,6 +119,9 @@ function gdk_after_init_theme()
if (get_option('permalink_structure') == '' || define('GDK_HTML_LINK', true)) { //如果是默认连接格式或者主题声明 define( 'GDK_HTML_LINK', true );
update_option('permalink_structure', '/archives/%post_id%.html'); //固定链接格式
}
if (gdk_option('gdk_diasble_widgets_block')){ //如果
remove_theme_support( 'widgets-block-editor' ); //禁用新版小工具
}
update_option('posts_per_page', '30'); //每页文章数目
}
add_action('after_setup_theme', 'gdk_after_init_theme');

View file

@ -1,5 +1,4 @@
<?php
if (!defined('ABSPATH')) exit;
/**
* 各页面重写规则
*/

View file

@ -222,7 +222,7 @@ if (gdk_option('gdk_fuck_spam')) {
gdk_die("评论禁止包含日文!");
}
//屏蔽评论里面黑名单内容
if (wp_blacklist_check($commentdata['comment_author'], $commentdata['comment_author_email'], $commentdata['comment_author_url'], $commentdata['comment_content'], $commentdata['comment_author_IP'], $commentdata['comment_agent'])) {
if (wp_check_comment_disallowed_list($commentdata['comment_author'], $commentdata['comment_author_email'], $commentdata['comment_author_url'], $commentdata['comment_content'], $commentdata['comment_author_IP'], $commentdata['comment_agent'])) {
gdk_die('不好意思,您的评论违反本站评论规则');
}
return $commentdata;

View file

@ -1,5 +1,4 @@
<?php
if (!defined('ABSPATH')) exit;
//百度收录提示
if (gdk_option('gdk_baidurecord_b') && function_exists('curl_init')) {
@ -77,6 +76,14 @@ function force_weauth_login_url($login_url, $redirect, $force_reauth)
add_filter('login_url', 'force_weauth_login_url', 10, 3);
}
//在登录框添加额外的微信登录
function weixin_login_button()
{
echo '<p><a class="button button-large" href="' . get_permalink(gdk_page_id('weauth')) . '">微信登录</a></p><br>';
}if (gdk_option('gdk_weauth_oauth')) {
add_action('login_form', 'weixin_login_button');
}
//评论微信推送
if (gdk_option('gdk_Server') && !is_admin()) {
function sc_send($comment_id)
@ -103,7 +110,7 @@ if (gdk_option('gdk_Server') && !is_admin()) {
),
);
$context = stream_context_create($opts);
return $result = file_get_contents('https://sctapi.ftqq.com/' . $key . '.send', false, $context);
return $result = file_get_contents('http://sc.ftqq.com/' . $key . '.send', false, $context);
}
add_action('comment_post', 'sc_send', 19, 2);
}
@ -157,24 +164,100 @@ wp_embed_register_handler('youku_iframe', '#http://v.youku.com/v_show/id_(.*?).h
wp_embed_unregister_handler('youku');
////////////////weauth//////////////
//接受奶子微信的账号信息
function get_weauth_oauth()
/*
function weauth_oauth_redirect()
{
if (in_string($_SERVER['REQUEST_URI'], 'weauth')) {
$weauth_user = isset($_GET['user']) ? sanitize_text_field($_GET['user']) : false; //weauth发来用户信息
$weauth_sk = isset($_GET['sk']) ? sanitize_text_field($_GET['sk']) : false; //weauth返回的12位sk信息
$weauth_res = get_transient($weauth_sk . '-OK');
if (empty($weauth_res) && $weauth_res !== 1) {
return;
}
wp_redirect(home_url());
exit;
}
$weauth_user = stripslashes($weauth_user);
$weauth_user = json_decode($weauth_user, true);
$oauth_result = implode('|', $weauth_user);
set_transient($weauth_sk . '-info', $oauth_result, 60); //1分钟缓存
header('goauth: ok');
echo 'success'; //给对方服务器打个招呼
exit;
function get_weauth_token()
{
$sk = date("YmdHis") . mt_rand(10, 99);
set_transient($sk, 1, 60 * 6);
$key = $_SERVER['HTTP_HOST'] . '@' . $sk;
return $key;
}
function get_weauth_qr()
{
$qr64 = [];
$qr64['key'] = get_weauth_token();
$qr64['qrcode'] = json_decode(file_get_contents('https://wa.isdot.net/qrcode?str=' . $qr64['key']), true)['qrcode'];
return $qr64;
}
function weauth_rewrite_rules($wp_rewrite)
{
if ($ps = get_option('permalink_structure')) {
$new_rules['^weauth'] = 'index.php?user=$matches[1]&sk=$matches[2]';
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
}
add_action('parse_request', 'get_weauth_oauth');
add_action('generate_rewrite_rules', 'weauth_rewrite_rules');
function weauth_oauth()
{
$weauth_user = $_GET['user'];
$weauth_sk = esc_attr($_GET['sk']);
$weauth_res = get_transient($weauth_sk);
if (empty($weauth_res)) {
return;
}
$weauth_user = stripslashes($weauth_user);
$weauth_user = json_decode($weauth_user, true);
$nickname = $weauth_user['nickName'];
$wxavatar = $weauth_user['avatarUrl'];
$openid = $weauth_user['openid'];
$login_name = 'wx_' . wp_create_nonce($openid);
if (is_user_logged_in()) {
$user_id = get_current_user_id();
update_user_meta($user_id, 'wx_openid', $openid);
update_user_meta($user_id, 'simple_local_avatar', $wxavatar);
} else {
$weauth_user = get_users(array(
'meta_key ' => 'wx_openid',
'meta_value' => $openid,
)
);
if (is_wp_error($weauth_user) || !count($weauth_user)) {
$random_password = wp_generate_password(12, false);
$userdata = array(
'user_login' => $login_name,
'display_name' => $nickname,
'user_pass' => $random_password,
'nickname' => $nickname,
);
$user_id = wp_insert_user($userdata);
update_user_meta($user_id, 'wx_openid', $openid);
update_user_meta($user_id, 'simple_local_avatar', $wxavatar);
} else {
$user_id = $weauth_user[0]->ID;
}
}
set_transient($weauth_sk . 'ok', $user_id, 60); //用于登录的随机数,有效期为一分钟
weauth_oauth_redirect();
}
//初始化
/*
function weauth_oauth_init()
{
if (isset($_GET['user']) && isset($_GET['sk'])) {
weauth_oauth();
}
}
add_action('init', 'weauth_oauth_init');
/*
//GET自动登录
function gdk_weauth_oauth_login()
{
$key = isset($_GET['spam']) ? $_GET['spam'] : false;
if ($key) {
$user_id = get_transient($key . 'ok');
if ($user_id != 0) {
wp_set_auth_cookie($user_id);
}
}
}
add_action('init', 'gdk_weauth_oauth_login');

View file

@ -50,7 +50,6 @@ add_shortcode('dm', 'gdk_DemoUrl');
//使用短代码添加回复后可见内容开始
function gdk_reply_to_read($atts, $content = null)
{
$content = do_shortcode($content);
extract(shortcode_atts(array(
'notice' => '<div class="alert info pull-center"><p class="reply-to-read">注意:本段内容须成功“<a href="' . get_permalink() . '#respond" title="回复本文">回复本文</a>”后“<a href="javascript:window.location.reload();" title="刷新本页">刷新本页</a>”方可查看!</p></div>',
), $atts));
@ -204,7 +203,6 @@ add_shortcode('netmusic', 'gdk_music163');
//登录可见
function gdk_login_to_read($atts, $content = null)
{
$content = do_shortcode($content);
$logina = '<a target="_blank" href="' . esc_url(wp_login_url(get_permalink())) . '">登录</a>';
extract(shortcode_atts(array(
'notice' => '<div class="alert info pull-center"><p class="reply-to-read" style="color: blue;">注意:本段内容须“' . $logina . '”后方可查看!</p></div>',
@ -219,7 +217,6 @@ add_shortcode('vip', 'gdk_login_to_read');
// 部分内容输入密码可见
function gdk_secret_view($atts, $content = null)
{
$content = do_shortcode($content);
$pid = get_the_ID();
add_post_meta($pid, '_pass_content', $content, true) or update_post_meta($pid, '_pass_content', $content);
if (current_user_can('administrator')) {
@ -429,6 +426,71 @@ function gdk_pay_nologin($atts, $content = '')
}
add_shortcode('pax', 'gdk_pay_nologin');
function box_shortcode( $atts, $content = null ) {
extract(
shortcode_atts(array(
's' => '1'
), $atts));
if($s == '1') { $box_classes = 'c1_4 aside'; }
if($s == '2') { $box_classes = 'c2_4 main'; }
if($s == '3') { $box_classes = 'c3_4'; }
if($s == '4') { $box_classes = 'c4_4'; }
return '<section class="' . $box_classes . '">' . $content . '</section>';
}
add_shortcode( 'b', 'box_shortcode' );
function contentblock_shortcode( $atts, $content = null ) {
return '<div class="inner">' . do_shortcode($content) . '</div>';
}
add_shortcode( 'cb', 'contentblock_shortcode' );
//
function points_view($content){
$cookie_name = 'huoduan_wechat_fans';
if (preg_match_all('/<!--pay points start-->([\s\S]*?)<!--pay points end-->/i', $content, $hide_words))
{
$re = '/<!--pay points start-->【(.*)】/i';
$str = '我在这里,这里不是付费内容
<!--pay points start-->【10】dssdssdfs我在这里这里是付费内容
第二行
<!--pay points end-->';
preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0);
$points = $matches[1][0];
$wechatfans = get_option('huoduan_wechatfans');
$cv = md5($wechatfans['wechat_key'].$cookie_name.'huoduan.com');
$vtips='';
if(isset($_POST['huoduan_verifycode'])){
if($_POST['huoduan_verifycode']==$wechatfans['wechat_code']){
setcookie($cookie_name, $cv ,time()+(int)$wechatfans['wechat_day']*86400, "/");
$_COOKIE[$cookie_name] = $cv;
}else{
$vtips='<script>alert("验证码错误!请输入正确的验证码!");</script>';
}
}
$cookievalue = isset($_COOKIE[$cookie_name])?$_COOKIE[$cookie_name]:'';
if($cookievalue==$cv){
$content = str_replace($hide_words[0], '<div style="border:1px dashed #F60; padding:10px; margin:10px 0; line-height:200%; background-color:#FFF4FF; overflow:hidden; clear:both;">'.$hide_words[0][0].'</div>', $content);
}else{
$hide_notice = '<div class="huoduan_hide_box" style="border:1px dashed #F60; padding:10px; margin:10px 0; line-height:200%; color:#F00; background-color:#FFF4FF; overflow:hidden; clear:both;"><img class="wxpic" align="right" src="'.$wechatfans['wechat_qrimg'].'" style="width:150px;height:150px;margin-left:20px;display:inline;border:none" width="150" height="150" alt="'.$wechatfans['wechat_name'].'" /><span style="font-size:18px;">此处内容已经被作者隐藏,请输入验证码查看内容</span><form method="post" style="margin:10px 0;"><span class="yzts" style="font-size:18px;float:left;">验证码:</span><input name="huo'.'duan_verifycode" id="verifycode" type="text" value="" style="border:none;float:left;width:80px; height:32px; line-height:30px; padding:0 5px; border:1px solid #FF6600;-moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius:0px;" /><input id="verifybtn" style="border:none;float:left;width:80px; height:32px; line-height:32px; padding:0 5px; background-color:#F60; text-align:center; border:none; cursor:pointer; color:#FFF;-moz-border-radius: 0px; font-size:14px; -webkit-border-radius: 0px; border-radius:0px;" name="" type="submit" value="提交查看" /></form><div style="clear:left;"></div><span style="color:#00BF30">请关注本站微信公众号,回复“<span style="color:blue">'.$wechatfans['wechat_keyword'].'</span>”,获取验证码。在微信里搜索“<span style="color:blue">'.$wechatfans['wechat_name'].'</span>”或者“<span style="color:blue">'.$wechatfans['wechat_account'].'</span>”或者微信扫描右侧二维码都可以关注本站微信公众号。</span><div class="cl"></div></div>'.$vtips;
$content = str_replace($hide_words[0], $hide_notice, $content);
}
}
return $content;
}
add_filter('the_content', 'points_view');
//WordPress 段代码按钮集合
function gdk_shortcode_list()
{

14
gdk.php
View file

@ -3,10 +3,10 @@
Plugin Name: GitCafe Development Kit 极客公园开发套件
Plugin URI: https://gitcafe.net/
Description: 为WordPress主题开发提供底层支持
Version: 1.1
Version: 0.0.3
Author: 云落
Author URI: https://gitcafe.net/
Compatible:5.7.1
Compatible:5.3.2
*/
//万能的开头
@ -16,19 +16,19 @@ if (!defined('ABSPATH')) {exit;}
function deactivate_myself()
{
deactivate_plugins(plugin_basename(__FILE__));
wp_die('启动失败GDK插件不兼容Git主题且需要运行在 PHP 7.3 版本及更高的环境下。');
wp_die('启动失败GDK插件不兼容Git主题且需要运行在 PHP 7.2 版本及更高的环境下。');
}
if (defined('GIT_URL')) {
add_action('update_option_active_plugins', 'deactivate_myself');
}
if (!version_compare(PHP_VERSION, '7.3', '>=')) {
if (!version_compare(PHP_VERSION, '7.2', '>=')) {
add_action('update_option_active_plugins', 'deactivate_myself');
}
//定义各种常量
define('GDK_PLUGIN_VER', '1.0');
define('GDK_PLUGIN_VER', '0.0.3');
define('GDK_PLUGIN_FILE', __FILE__); //插件入口文件
define('GDK_BASE_URL', plugin_dir_url(__FILE__)); //插件目录url
define('GDK_ROOT_PATH', plugin_dir_path(__FILE__)); //插件目录路径
@ -37,4 +37,6 @@ define('GDK_ROOT_PATH', plugin_dir_path(__FILE__)); //插件目录路径
include 'framework/frame_load.php'; //加载后台框架
include 'class/class_load.php'; //加载各种类
include 'functions/func_load.php'; //加载函数
include 'assets/assets_load.php'; //加载静态资源
include 'assets/assets_load.php'; //加载静态资源

File diff suppressed because one or more lines are too long

View file

@ -75,4 +75,4 @@ function gdk_clear_sitemap_cache()
}
add_action('publish_post', 'gdk_clear_sitemap_cache');
add_action('publish_page', 'gdk_clear_sitemap_cache');
add_action('save_post', 'gdk_clear_sitemap_cache');
add_action('save_post', 'gdk_clear_sitemap_cache');