From 5c6428e0a8af9f875cb26d9ce378d1f98e6beb3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=91=E8=90=BD?= Date: Sun, 10 Oct 2021 21:48:53 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=A8=E9=83=A8=E4=BB=A3=E7=A0=81=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/assets_load.php | 198 +- class/Payjs.php | 53 +- class/aq_resizer.php | 142 +- class/class_load.php | 6 +- class/local_avatars.php | 161 +- class/points/class-points-admin.php | 268 +-- class/points/class-points-shortcodes.php | 99 +- class/points/class-points.php | 113 +- class/points/points.php | 18 +- class/qrcode.class.php | 2665 ++++++++++++---------- class/updates.php | 111 +- class/wechat.php | 90 +- class/widget_cache.php | 41 +- framework/frame_load.php | 4 +- framework/metabox.php | 204 +- framework/options-config.php | 421 ++-- framework/plugin-options.php | 716 +++--- functions/Ajax.php | 182 +- functions/Common.php | 808 ++++--- functions/advanced.php | 240 +- functions/email.php | 93 +- functions/func_load.php | 15 +- functions/optimization.php | 204 +- functions/rewrite.php | 9 +- functions/security.php | 228 +- functions/seo.php | 140 +- functions/server.php | 112 +- functions/shortcode.php | 357 +-- functions/user.php | 153 +- public/download.php | 8 +- public/notify.php | 6 +- 31 files changed, 4193 insertions(+), 3672 deletions(-) diff --git a/assets/assets_load.php b/assets/assets_load.php index 235bf6d..29c0035 100644 --- a/assets/assets_load.php +++ b/assets/assets_load.php @@ -1,13 +1,15 @@ wp_create_nonce('pui-nonce'))); + wp_localize_script('paste-upload-image', 'pui_vars', ['pui_nonce' => wp_create_nonce('pui-nonce')]); } } add_action('admin_enqueue_scripts', 'gdk_admin_enqueue_script'); @@ -15,33 +17,33 @@ add_action('admin_enqueue_scripts', 'gdk_admin_enqueue_script'); function gdk_enqueue_script_frontend() { if (!is_admin()) { - wp_enqueue_style( 'uikit', 'https://cdn.jsdelivr.net/npm/uikit@3.7.4/dist/css/uikit.min.css', false, GDK_PLUGIN_VER, 'all' ); + wp_enqueue_style('uikit', 'https://cdn.jsdelivr.net/npm/uikit@3.7.4/dist/css/uikit.min.css', false, GDK_PLUGIN_VER, 'all'); - wp_enqueue_style('gdk', GDK_BASE_URL . 'assets/css/gdk.css', false, GDK_PLUGIN_VER, 'all'); + wp_enqueue_style('gdk', GDK_BASE_URL.'assets/css/gdk.css', false, GDK_PLUGIN_VER, 'all'); wp_deregister_script('jquery'); wp_enqueue_script('jquery', 'https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js', false, GDK_PLUGIN_VER, true); //加载自定义jQuery2.0.3 - // Comment Reply - if (is_singular() && comments_open() && get_option('thread_comments')) { - wp_enqueue_script('comment-reply'); - } - - wp_enqueue_script('libs', GDK_BASE_URL . 'assets/js/libs.min.js', ['jquery'], GDK_PLUGIN_VER, true); + // Comment Reply + if (is_singular() && comments_open() && get_option('thread_comments')) { + wp_enqueue_script('comment-reply'); + } + + wp_enqueue_script('libs', GDK_BASE_URL.'assets/js/libs.min.js', ['jquery'], GDK_PLUGIN_VER, true); wp_enqueue_script('uikit', 'https://cdn.jsdelivr.net/npm/uikit@3.7.4/dist/js/uikit.min.js', [], GDK_PLUGIN_VER, true); wp_enqueue_script('uikit-icon', 'https://cdn.jsdelivr.net/npm/uikit@3.7.4/dist/js/uikit-icons.min.js', [], GDK_PLUGIN_VER, true); - wp_enqueue_script('gdk', GDK_BASE_URL . 'assets/js/gdk.js', ['jquery'], GDK_PLUGIN_VER, true); + wp_enqueue_script('gdk', GDK_BASE_URL.'assets/js/gdk.js', ['jquery'], GDK_PLUGIN_VER, true); wp_localize_script('gdk', 'gdk', [ - 'ajaxurl' => admin_url('admin-ajax.php'), - 'pass_nonce' => wp_create_nonce('pass_nonce'), - 'pay_points' => wp_create_nonce('pay_points'), - 'check_pay_points' => wp_create_nonce('check_pay_points'), - 'check_pay_view' => wp_create_nonce('check_pay_view'), - 'check_code' => wp_create_nonce('check_code'), + 'ajaxurl' => admin_url('admin-ajax.php'), + 'pass_nonce' => wp_create_nonce('pass_nonce'), + 'pay_points' => wp_create_nonce('pay_points'), + 'check_pay_points' => wp_create_nonce('check_pay_points'), + 'check_pay_view' => wp_create_nonce('check_pay_view'), + 'check_code' => wp_create_nonce('check_code'), 'gdk_weauth_qr_gen' => wp_create_nonce('gdk_weauth_qr_gen'), - 'gdk_weauth_check' => wp_create_nonce('gdk_weauth_check'), - 'gdk_payjs_alipay' => gdk_option('gdk_payjs_alipay'), - 'user_id' => get_current_user_id(), - 'msg_nonce' => wp_create_nonce('msg_nonce'), + 'gdk_weauth_check' => wp_create_nonce('gdk_weauth_check'), + 'gdk_payjs_alipay' => gdk_option('gdk_payjs_alipay'), + 'user_id' => get_current_user_id(), + 'msg_nonce' => wp_create_nonce('msg_nonce'), ]); } } @@ -51,63 +53,115 @@ add_action('wp_enqueue_scripts', 'gdk_enqueue_script_frontend'); function gdk_admin_script() { ?> - - + - div>a:nth-child(20) { + background: #f6003c; + border-color: #f6003c; + color: #fff + } + + .wp-block { + max-width: 45pc + } + + .wp-block[data-align=wide] { + max-width: 810pt + } + + .wp-block[data-align=full] { + max-width: none + } + + #activity-widget #the-comment-list .avatar { + width: 50px + } + + .form-field-download_name, + .form-field-download_size { + width: 45%; + float: left + } + + .form-field-download_link { + clear: both + } + +mchid = $config['mchid']; - $this->key = $config['key']; - $api_url = $config['api_url'] ?? 'https://payjs.cn/api/'; - - $this->api_url_native = $api_url . 'native'; - $this->api_url_cashier = $api_url . 'cashier'; - $this->api_url_mweb = $api_url . 'mweb'; - $this->api_url_close = $api_url . 'close'; - $this->api_url_check = $api_url . 'check'; + $this->key = $config['key']; + $api_url = $config['api_url'] ?? 'https://payjs.cn/api/'; + $this->api_url_native = $api_url.'native'; + $this->api_url_cashier = $api_url.'cashier'; + $this->api_url_mweb = $api_url.'mweb'; + $this->api_url_close = $api_url.'close'; + $this->api_url_check = $api_url.'check'; } // 扫码支付 public function native(array $data) { $this->url = $this->api_url_native; + return $this->post($data); } + // MWEB(H5) 支付 public function mweb(array $data) { $this->url = $this->api_url_mweb; + return $this->post($data); } + // 收银台模式 public function cashier(array $data) { $this->url = $this->api_url_cashier; - $data = $this->sign($data); - $url = $this->url . '?' . http_build_query($data); - return $url; + $data = $this->sign($data); + + return $this->url.'?'.http_build_query($data); } // 检查订单 public function check($payjs_order_id) { $this->url = $this->api_url_check; - $data = ['payjs_order_id' => $payjs_order_id]; + $data = ['payjs_order_id' => $payjs_order_id]; + return $this->post($data); } @@ -57,11 +63,11 @@ class GDK_Payjs public function notify() { $data = $_POST; - if ($this->checkSign($data) === true) { + if (true === $this->checkSign($data)) { return $data; - } else { - exit("验签失败"); } + + exit('验签失败'); } // 数据签名 @@ -70,7 +76,8 @@ class GDK_Payjs $data['mchid'] = $this->mchid; array_filter($data); ksort($data); - $data['sign'] = strtoupper(md5(urldecode(http_build_query($data) . '&key=' . $this->key))); + $data['sign'] = strtoupper(md5(urldecode(http_build_query($data).'&key='.$this->key))); + return $data; } @@ -81,15 +88,17 @@ class GDK_Payjs unset($data['sign']); array_filter($data); ksort($data); - $sign = strtoupper(md5(urldecode(http_build_query($data) . '&key=' . $this->key))); + $sign = strtoupper(md5(urldecode(http_build_query($data).'&key='.$this->key))); + return $in_sign == $sign ? true : false; } // 数据发送 - public function post($data) { - $data = $this->sign($data); + public function post($data) + { + $data = $this->sign($data); $ch = curl_init(); - curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS ); + curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_USERAGENT, 'HTTP CLIENT'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); @@ -99,7 +108,7 @@ class GDK_Payjs curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $rst = curl_exec($ch); curl_close($ch); + return json_decode($rst, true); } - } diff --git a/class/aq_resizer.php b/class/aq_resizer.php index 5a39714..0e2da8f 100644 --- a/class/aq_resizer.php +++ b/class/aq_resizer.php @@ -7,57 +7,59 @@ * Author : Syamil MJ * Author URI : http://aquagraphite.com * License : WTFPL - http://sam.zoy.org/wtfpl/ - * Documentation : https://github.com/sy4mil/Aqua-Resizer/ + * Documentation : https://github.com/sy4mil/Aqua-Resizer/. + * + * @param string $url - (required) must be uploaded using wp media uploader + * @param int $width - (required) + * @param int $height - (optional) + * @param bool $crop - (optional) default to soft crop + * @param bool $single - (optional) returns an array if false + * @param bool $upscale - (optional) resizes smaller images * - * @param string $url - (required) must be uploaded using wp media uploader - * @param int $width - (required) - * @param int $height - (optional) - * @param bool $crop - (optional) default to soft crop - * @param bool $single - (optional) returns an array if false - * @param bool $upscale - (optional) resizes smaller images * @uses wp_upload_dir() * @uses image_resize_dimensions() * @uses wp_get_image_editor() * - * @return str|array + * @return array|string */ - if (!class_exists('Aq_Resize')) { class Aq_Exception extends Exception - {} + { + } class Aq_Resize { - /** - * The singleton instance - */ - private static $__instance = null; - /** * Should an Aq_Exception be thrown on error? * If false (default), then the error will just be logged. */ public $throwOnError = false; + /** + * The singleton instance. + */ + private static $__instance; /** - * No initialization allowed + * No initialization allowed. */ private function __construct() - {} + { + } /** - * No cloning allowed + * No cloning allowed. */ private function __clone() - {} + { + } /** - * For your custom default usage you may want to initialize an Aq_Resize object by yourself and then have own defaults + * For your custom default usage you may want to initialize an Aq_Resize object by yourself and then have own defaults. */ public static function getInstance() { - if (self::$instance == null) { - self::$instance = new self; + if (null == self::$instance) { + self::$instance = new self(); } return self::$instance; @@ -65,6 +67,13 @@ if (!class_exists('Aq_Resize')) { /** * Run, forest. + * + * @param mixed $url + * @param null|mixed $width + * @param null|mixed $height + * @param null|mixed $crop + * @param mixed $single + * @param mixed $upscale */ public function process($url, $width = null, $height = null, $crop = null, $single = true, $upscale = false) { @@ -80,17 +89,17 @@ if (!class_exists('Aq_Resize')) { // Caipt'n, ready to hook. if (true === $upscale) { - add_filter('image_resize_dimensions', array($this, 'aq_upscale'), 10, 6); + add_filter('image_resize_dimensions', [$this, 'aq_upscale'], 10, 6); } // Define upload path & dir. $upload_info = wp_upload_dir(); - $upload_dir = $upload_info['basedir']; - $upload_url = $upload_info['baseurl']; + $upload_dir = $upload_info['basedir']; + $upload_url = $upload_info['baseurl']; - $http_prefix = "http://"; - $https_prefix = "https://"; - $relative_prefix = "//"; // The protocol-relative URL + $http_prefix = 'http://'; + $https_prefix = 'https://'; + $relative_prefix = '//'; // The protocol-relative URL /* if the $url scheme differs from $upload_url scheme, make them match if the schemes differe, images don't show up. */ @@ -99,42 +108,42 @@ if (!class_exists('Aq_Resize')) { } elseif (!strncmp($url, $http_prefix, strlen($http_prefix))) { //if url begins with http:// make $upload_url begin with http:// as well $upload_url = str_replace($https_prefix, $http_prefix, $upload_url); } elseif (!strncmp($url, $relative_prefix, strlen($relative_prefix))) { //if url begins with // make $upload_url begin with // as well - $upload_url = str_replace(array(0 => "$http_prefix", 1 => "$https_prefix"), $relative_prefix, $upload_url); + $upload_url = str_replace([0 => "{$http_prefix}", 1 => "{$https_prefix}"], $relative_prefix, $upload_url); } // Check if $img_url is local. if (false === strpos($url, $upload_url)) { - throw new Aq_Exception('图片必须是本地图片: ' . $url); + throw new Aq_Exception('图片必须是本地图片: '.$url); } // Define path of image. $rel_path = str_replace($upload_url, '', $url); - $img_path = $upload_dir . $rel_path; + $img_path = $upload_dir.$rel_path; // Check if img path exists, and is an image indeed. if (!file_exists($img_path) or !getimagesize($img_path)) { - throw new Aq_Exception('图片不存在或者不是一个图片文件: ' . $img_path); + throw new Aq_Exception('图片不存在或者不是一个图片文件: '.$img_path); } // Get image info. - $info = pathinfo($img_path); - $ext = $info['extension']; + $info = pathinfo($img_path); + $ext = $info['extension']; list($orig_w, $orig_h) = getimagesize($img_path); // Get image size after cropping. - $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); + $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop); $dst_w = $dims[4]; $dst_h = $dims[5]; // Return the original image only if it exactly fits the needed measures. if (!$dims || (((null === $height && $orig_w == $width) xor (null === $width && $orig_h == $height)) xor ($height == $orig_h && $width == $orig_w))) { $img_url = $url; - $dst_w = $orig_w; - $dst_h = $orig_h; + $dst_w = $orig_w; + $dst_h = $orig_h; } else { // Use this to check if cropped image already exists, so we can return that instead. - $suffix = "{$dst_w}x{$dst_h}"; - $dst_rel_path = str_replace('.' . $ext, '', $rel_path); + $suffix = "{$dst_w}x{$dst_h}"; + $dst_rel_path = str_replace('.'.$ext, '', $rel_path); $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}"; if (!$dims || (true == $crop && false == $upscale && ($dst_w < $width || $dst_h < $height))) { @@ -142,34 +151,32 @@ if (!class_exists('Aq_Resize')) { throw new Aq_Exception('Unable to resize image because image_resize_dimensions() failed'); } // Else check if cache exists. - elseif (file_exists($destfilename) && getimagesize($destfilename)) { + if (file_exists($destfilename) && getimagesize($destfilename)) { $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}"; } // Else, we resize the image and return the new resized image url. else { - $editor = wp_get_image_editor($img_path); if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop))) { - throw new Aq_Exception('Unable to get WP_Image_Editor: ' . - $editor->get_error_message() . ' (is GD or ImageMagick installed?)'); + throw new Aq_Exception('Unable to get WP_Image_Editor: '. + $editor->get_error_message().' (is GD or ImageMagick installed?)'); } $resized_file = $editor->save(); if (!is_wp_error($resized_file)) { $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']); - $img_url = $upload_url . $resized_rel_path; + $img_url = $upload_url.$resized_rel_path; } else { - throw new Aq_Exception('Unable to save resized image file: ' . $editor->get_error_message()); + throw new Aq_Exception('Unable to save resized image file: '.$editor->get_error_message()); } - } } // Okay, leave the ship. if (true === $upscale) { - remove_filter('image_resize_dimensions', array($this, 'aq_upscale')); + remove_filter('image_resize_dimensions', [$this, 'aq_upscale']); } // Return the output. @@ -178,29 +185,35 @@ if (!class_exists('Aq_Resize')) { $image = $img_url; } else { // array return. - $image = array( + $image = [ 0 => $img_url, 1 => $dst_w, 2 => $dst_h, - ); + ]; } return $image; } catch (Aq_Exception $ex) { - error_log('Aq_Resize.process() error: ' . $ex->getMessage()); + error_log('Aq_Resize.process() error: '.$ex->getMessage()); if ($this->throwOnError) { // Bubble up exception. throw $ex; - } else { - // Return false, so that this patch is backwards-compatible. - return false; } + // Return false, so that this patch is backwards-compatible. + return false; } } /** - * Callback to overwrite WP computing of thumbnail measures + * Callback to overwrite WP computing of thumbnail measures. + * + * @param mixed $default + * @param mixed $orig_w + * @param mixed $orig_h + * @param mixed $dest_w + * @param mixed $dest_h + * @param mixed $crop */ public function aq_upscale($default, $orig_w, $orig_h, $dest_w, $dest_h, $crop) { @@ -211,8 +224,8 @@ if (!class_exists('Aq_Resize')) { // Here is the point we allow to use larger image size than the original one. $aspect_ratio = $orig_w / $orig_h; - $new_w = $dest_w; - $new_h = $dest_h; + $new_w = $dest_w; + $new_h = $dest_h; if (!$new_w) { $new_w = intval($new_h * $aspect_ratio); @@ -230,27 +243,34 @@ if (!class_exists('Aq_Resize')) { $s_x = floor(($orig_w - $crop_w) / 2); $s_y = floor(($orig_h - $crop_h) / 2); - return array(0, 0, (int)$s_x, (int)$s_y, (int)$new_w, (int)$new_h, (int)$crop_w, (int)$crop_h); + return [0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h]; } } } if (!function_exists('aq_resize')) { - /** * This is just a tiny wrapper function for the class above so that there is no - * need to change any code in your own WP themes. Usage is still the same :) + * need to change any code in your own WP themes. Usage is still the same :). + * + * @param mixed $url + * @param null|mixed $width + * @param null|mixed $height + * @param null|mixed $crop + * @param mixed $single + * @param mixed $upscale */ function aq_resize($url, $width = null, $height = null, $crop = null, $single = true, $upscale = false) { - /* WPML Fix */ + // WPML Fix if (defined('ICL_SITEPRESS_VERSION')) { global $sitepress; $url = $sitepress->convert_url($url, $sitepress->get_default_language()); } - /* WPML Fix */ + // WPML Fix $aq_resize = Aq_Resize::getInstance(); + return $aq_resize->process($url, $width, $height, $crop, $single, $upscale); } } diff --git a/class/class_load.php b/class/class_load.php index bc6a427..dd2f353 100644 --- a/class/class_load.php +++ b/class/class_load.php @@ -3,11 +3,13 @@ include 'local_avatars.php'; //本地头像 include 'updates.php'; //在线更新 -include( 'widget_cache.php' );//小工具缓存 + +include 'widget_cache.php'; //小工具缓存 include 'Payjs.php'; //支付功能 + include 'points/points.php'; //积分功能 include 'aq_resizer.php'; //缩略图功能 -include 'wechat.php'; //微信功能 +include 'wechat.php'; //微信功能 diff --git a/class/local_avatars.php b/class/local_avatars.php index 7f3d3ba..3f1bd9d 100644 --- a/class/local_avatars.php +++ b/class/local_avatars.php @@ -4,70 +4,76 @@ class gdk_local_avatars { private $__user_id_being_edited; + public function __construct() { - add_action('admin_init', array( + add_action('admin_init', [ $this, 'admin_init', - )); - add_action('show_user_profile', array( + ]); + add_action('show_user_profile', [ $this, 'edit_user_profile', - )); - add_action('edit_user_profile', array( + ]); + add_action('edit_user_profile', [ $this, 'edit_user_profile', - )); - add_action('personal_options_update', array( + ]); + add_action('personal_options_update', [ $this, 'edit_user_profile_update', - )); - add_action('edit_user_profile_update', array( + ]); + add_action('edit_user_profile_update', [ $this, 'edit_user_profile_update', - )); - add_filter('get_avatar', array( + ]); + add_filter('get_avatar', [ $this, 'get_avatar', - ), 10, 5); - add_filter('avatar_defaults', array( + ], 10, 5); + add_filter('avatar_defaults', [ $this, 'avatar_defaults', - )); + ]); } + public function admin_init() { - register_setting('discussion', 'gdk_local_avatars_caps', array( + register_setting('discussion', 'gdk_local_avatars_caps', [ $this, 'sanitize_options', - )); - add_settings_field('basic-user-avatars-caps', '本地上传头像权限管理', array( + ]); + add_settings_field('basic-user-avatars-caps', '本地上传头像权限管理', [ $this, 'avatar_settings_field', - ), 'discussion', 'avatars'); + ], 'discussion', 'avatars'); } + public function avatar_settings_field($args) { - $options = get_option('gdk_local_avatars_caps'); - ?> - - + +ID; } elseif (is_object($id_or_email) && !empty($id_or_email->user_id)) { - $user_id = (int)$id_or_email->user_id; + $user_id = (int) $id_or_email->user_id; } if (empty($user_id)) { @@ -79,41 +85,43 @@ checked($options['gdk_local_avatars_caps'], 1); ?>/>仅具有头像上传权限 return $avatar; } - $size = (int)$size; + $size = (int) $size; if (empty($alt)) { $alt = get_the_author_meta('display_name', $user_id); } if (empty($local_avatars[$size])) { - $upload_path = wp_upload_dir(); + $upload_path = wp_upload_dir(); $avatar_full_path = str_replace($upload_path['baseurl'], $upload_path['basedir'], $local_avatars['full']); - $image = wp_get_image_editor($avatar_full_path); + $image = wp_get_image_editor($avatar_full_path); if (!is_wp_error($image)) { $image->resize($size, $size, true); $image_sized = $image->save(); } $local_avatars[$size] = is_wp_error($image_sized) ? $local_avatars[$size] = $local_avatars['full'] : str_replace($upload_path['basedir'], $upload_path['baseurl'], $image_sized['path']); update_user_meta($user_id, 'simple_local_avatar', $local_avatars); - } elseif (substr($local_avatars[$size], 0, 4) != 'http') { + } elseif ('http' != substr($local_avatars[$size], 0, 4)) { $local_avatars[$size] = home_url($local_avatars[$size]); } $author_class = is_author($user_id) ? ' current-author' : ''; - $avatar = "" . esc_attr($alt) . ""; + $avatar = "".esc_attr($alt).""; + return apply_filters('simple_local_avatar', $avatar); } + public function edit_user_profile($profileuser) { ?> -

头像

- - - - + +
- 头像 + + + + - - -
+ ID); ?> - - + + 你没有头像上传权限,如需要修改本地头像,请联系站点管理员'; } - } - ?> -
- - +
+ + 'image/jpeg', - 'gif' => 'image/gif', - 'png' => 'image/png', - ); + 'gif' => 'image/gif', + 'png' => 'image/png', + ]; if (!function_exists('wp_handle_upload')) { - require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH.'wp-admin/includes/file.php'; } $this->avatar_delete($user_id); @@ -161,29 +173,32 @@ $options = get_option('gdk_local_avatars_caps'); } $this->user_id_being_edited = $user_id; - $avatar = wp_handle_upload($_FILES['basic-user-avatar'], array( - 'mimes' => $mimes, - 'test_form' => false, - 'unique_filename_callback' => array( + $avatar = wp_handle_upload($_FILES['basic-user-avatar'], [ + 'mimes' => $mimes, + 'test_form' => false, + 'unique_filename_callback' => [ $this, 'unique_filename_callback', - ), - )); - update_user_meta($user_id, 'simple_local_avatar', array( + ], + ]); + update_user_meta($user_id, 'simple_local_avatar', [ 'full' => $avatar['url'], - )); + ]); } elseif (!empty($_POST['basic-user-avatar-erase'])) { $this->avatar_delete($user_id); } } + public function avatar_defaults($avatar_defaults) { - remove_action('get_avatar', array( + remove_action('get_avatar', [ $this, 'get_avatar', - )); + ]); + return $avatar_defaults; } + public function avatar_delete($user_id) { $old_avatars = get_user_meta($user_id, 'simple_local_avatar', true); @@ -191,21 +206,23 @@ $options = get_option('gdk_local_avatars_caps'); if (is_array($old_avatars)) { foreach ($old_avatars as $old_avatar) { $old_avatar_path = str_replace($upload_path['baseurl'], $upload_path['basedir'], $old_avatar); - @unlink($old_avatar_path); + unlink($old_avatar_path); } } delete_user_meta($user_id, 'simple_local_avatar'); } + public function unique_filename_callback($dir, $name, $ext) { - $user = get_user_by('id', (int)$this->user_id_being_edited); - $name = $base_name = sanitize_file_name($user->ID . '_avatar'); + $user = get_user_by('id', (int) $this->user_id_being_edited); + $name = $base_name = sanitize_file_name($user->ID.'_avatar'); $number = 1; - while (file_exists($dir . "/$name$ext")) { - $name = $base_name . '_' . $number; - $number++; + while (file_exists($dir."/{$name}{$ext}")) { + $name = $base_name.'_'.$number; + ++$number; } - return $name . $ext; + + return $name.$ext; } } -$gdk_local_avatars = new gdk_local_avatars; \ No newline at end of file +$gdk_local_avatars = new gdk_local_avatars(); diff --git a/class/points/class-points-admin.php b/class/points/class-points-admin.php index 332ee28..7510f84 100644 --- a/class/points/class-points-admin.php +++ b/class/points/class-points-admin.php @@ -1,35 +1,33 @@ get_columns(); + $columns = $this->get_columns(); $sortable = $this->get_sortable_columns(); - $data = GDK_Points::get_points(null, null, null, ARRAY_A); - usort( $data, array( + $data = GDK_Points::get_points(null, null, null, ARRAY_A); + usort($data, [ &$this, - 'sort_data' - ) ); - $perPage = 30; //每页30个数据 + 'sort_data', + ]); + $perPage = 30; //每页30个数据 $currentPage = $this->get_pagenum(); - $totalItems = count($data); + $totalItems = count($data); $this->set_pagination_args([ 'total_items' => $totalItems, - 'per_page' => $perPage, + 'per_page' => $perPage, ]); $data = array_slice($data, (($currentPage - 1) * $perPage), $perPage); @@ -43,42 +41,40 @@ class GDK_Points_List_Table extends WP_List_Table /** * Override the parent columns method. - * Defines the columns to use in your listing table + * Defines the columns to use in your listing table. * - * @return Array + * @return array */ public function get_columns() { - $columns = [ - 'point_id' => 'ID', - 'user_id' => '用户ID', - 'points' => '金币', + return [ + 'point_id' => 'ID', + 'user_id' => '用户ID', + 'points' => '金币', 'description' => '描述', - 'datetime' => '日期&时间', - 'status' => '状态', - 'actions' => '操作', + 'datetime' => '日期&时间', + 'status' => '状态', + 'actions' => '操作', ]; - - return $columns; } /** - * Define the sortable columns + * Define the sortable columns. * - * @return Array + * @return array */ public function get_sortable_columns() { return [ - 'point_id' => [ + 'point_id' => [ 'point_id', false, ], - 'user_id' => [ + 'user_id' => [ 'user_id', false, ], - 'points' => [ + 'points' => [ 'points', false, ], @@ -86,28 +82,26 @@ class GDK_Points_List_Table extends WP_List_Table 'description', false, ], - 'datetime' => [ + 'datetime' => [ 'datetime', false, ], - 'status' => [ + 'status' => [ 'status', false, ], ]; } - - /** - * Define what data to show on each column of the table + * Define what data to show on each column of the table. * - * @param Array $item - * Data - * @param String $column_name - * - Current column name + * @param array $item + * Data + * @param string $column_name + * - Current column name * - * @return Mixed + * @return mixed */ public function column_default($item, $column_name) { @@ -119,33 +113,42 @@ class GDK_Points_List_Table extends WP_List_Table case 'datetime': case 'status': return $item[$column_name]; + break; + case 'actions': $actions = [ - 'edit' => sprintf('编辑', $_REQUEST['page'], 'edit', $item['point_id']), + 'edit' => sprintf('编辑', $_REQUEST['page'], 'edit', $item['point_id']), 'delete' => sprintf('删除', $_REQUEST['page'], 'delete', $item['point_id']), ]; //Return the title contents - return sprintf('%1$s%2$s', $item[$column_name] ?? "", + return sprintf( + '%1$s%2$s', + $item[$column_name] ?? '', $this->row_actions($actions, true) ); + break; + default: return print_r($item, true); } } /** - * Allows you to sort the data by the variables set in the $_GET + * Allows you to sort the data by the variables set in the $_GET. * - * @return Mixed + * @param mixed $a + * @param mixed $b + * + * @return mixed */ private function sort_data($a, $b) { // Set defaults $orderby = 'point_id'; - $order = 'desc';//desc asc + $order = 'desc'; //desc asc // If orderby is set, use this as the sort column if (!empty($_GET['orderby'])) { @@ -159,7 +162,7 @@ class GDK_Points_List_Table extends WP_List_Table $result = strnatcmp($a[$orderby], $b[$orderby]); - if ($order === 'asc') { + if ('asc' === $order) { return $result; } @@ -168,11 +171,10 @@ class GDK_Points_List_Table extends WP_List_Table } /** - * GDK_Points Admin class + * GDK_Points Admin class. */ class GDK_Points_Admin { - public static function init() { add_action('admin_notices', [__CLASS__, 'admin_notices']); @@ -198,47 +200,47 @@ class GDK_Points_Admin public static function points_menu() { - $alert = ""; + $alert = ''; if (isset($_POST['psearch'])) { $sdata = trim($_POST['psearch']); - if (preg_match('/E20/', $sdata) ) { + if (preg_match('/E20/', $sdata)) { //order id global $wpdb; - $point_id = $wpdb->get_row("SELECT point_id FROM " . GDK_Points_Database::points_get_table("users") . " WHERE description = '{$sdata}'", ARRAY_A)['point_id']; - $points = GDK_Points::get_point($point_id); - }elseif (preg_match('/(D|d)/', $sdata)){// description - $data = substr($sdata,1); - global $wpdb; - $points = $wpdb->get_results("SELECT * FROM " . GDK_Points_Database::points_get_table("users") . " WHERE description = '{$data}'"); - //var_dump($points); - $k[] = '
文章ID:' . $data . '    ||   文章名为:' . get_post($data)->post_title . '

'; - } elseif (filter_var($sdata, FILTER_VALIDATE_EMAIL)) { + $point_id = $wpdb->get_row('SELECT point_id FROM '.GDK_Points_Database::points_get_table('users')." WHERE description = '{$sdata}'", ARRAY_A)['point_id']; + $points = GDK_Points::get_point($point_id); + } elseif (preg_match('/(D|d)/', $sdata)) {// description + $data = substr($sdata, 1); + global $wpdb; + $points = $wpdb->get_results('SELECT * FROM '.GDK_Points_Database::points_get_table('users')." WHERE description = '{$data}'"); + //var_dump($points); + $k[] = '
文章ID:'.$data.'    ||   文章名为:'.get_post($data)->post_title.'

'; + } elseif (filter_var($sdata, FILTER_VALIDATE_EMAIL)) { //email - $user = get_user_by('email', $sdata); + $user = get_user_by('email', $sdata); $points = GDK_Points::get_points_by_user($user->ID); - $k[] = '
用户ID:' . $user->ID . '    ||   总金币为:' . GDK_Points::get_user_total_points($user->ID) . '
'; + $k[] = '
用户ID:'.$user->ID.'    ||   总金币为:'.GDK_Points::get_user_total_points($user->ID).'
'; } else { //userid $points = GDK_Points::get_points_by_user($sdata); - $k[] = '
用户ID:' . $sdata . '    ||   总金币为:' . GDK_Points::get_user_total_points($sdata) . '
'; + $k[] = '
用户ID:'.$sdata.'    ||   总金币为:'.GDK_Points::get_user_total_points($sdata).'
'; } if (is_array($points)) { foreach ($points as $point) { - $userid = $point->user_id; - $user_name = get_user_by('id', $userid)->display_name; - $k[] = '
用户ID:' . $userid . '   ||   金币:' . $point->points . '    ||   描述:' . $point->description . '    ||   日期:' . $point->datetime . '   ||   用户名:' . $user_name . '
'; + $userid = $point->user_id; + $user_name = get_user_by('id', $userid)->display_name; + $k[] = '
用户ID:'.$userid.'   ||   金币:'.$point->points.'    ||   描述:'.$point->description.'    ||   日期:'.$point->datetime.'   ||   用户名:'.$user_name.'
'; } } else { - $k[] = '
用户ID:' . $point->user_id . '  金币:' . $points->points . '   描述:' . $points->description . '   日期:' . $points->datetime . '
'; + $k[] = '
用户ID:'.$point->user_id.'  金币:'.$points->points.'   描述:'.$points->description.'   日期:'.$points->datetime.'
'; } - $alert = implode(" ", $k); + $alert = implode(' ', $k); } - if (isset($_POST['save']) && isset($_POST['action'])) { - if ($_POST['action'] == "edit") { + if (isset($_POST['save'], $_POST['action'])) { + if ('edit' == $_POST['action']) { $point_id = isset($_POST['point_id']) ? intval($_POST['point_id']) : null; - $points = GDK_Points::get_point($point_id); - $data = array(); + $points = GDK_Points::get_point($point_id); + $data = []; if (isset($_POST['user_mail'])) { $data['user_mail'] = $_POST['user_mail']; } @@ -265,83 +267,87 @@ class GDK_Points_Admin // 增加金币 if (isset($_POST['user_mail'])) { //如果输入邮箱的话 $usermail = $data['user_mail']; - $user = get_user_by('email', $usermail); - $userid = $user->ID; + $user = get_user_by('email', $usermail); + $userid = $user->ID; $username = $user->display_name; } if (isset($_POST['user_id'])) { //如果输入用户ID的话 - $user = get_user_by('id', $data['user_id']); + $user = get_user_by('id', $data['user_id']); $usermail = $user->user_email; - $userid = $data['user_id']; + $userid = $data['user_id']; $username = $user->display_name; } GDK_Points::set_points($_POST['points'], $userid, $data); - $mail_title = $username . '您好,金币增加通知'; + $mail_title = $username.'您好,金币增加通知'; $mail_cotent = '

您的金币金额被管理员调整,请查收!

-

如果您的金币金额有异常,请您在第一时间和我们取得联系哦,联系邮箱:' . get_bloginfo('admin_email') . '

'; - $message = mail_temp($mail_title, $mail_cotent, home_url(), get_bloginfo('name')); +

如果您的金币金额有异常,请您在第一时间和我们取得联系哦,联系邮箱:'.get_bloginfo('admin_email').'

'; + $message = gdk_mail_temp($mail_title, $mail_cotent, home_url(), get_bloginfo('name')); $headers = "Content-Type:text/html;charset=UTF-8\n"; - wp_mail($usermail, 'Hi,' . $username . ',金币账户金额变动通知!', $message, $headers); + wp_mail($usermail, 'Hi,'.$username.',金币账户金额变动通知!', $message, $headers); } } - $alert = "金币已更新"; + $alert = '金币已更新'; } - if (isset($_GET["action"])) { - $action = $_GET["action"]; - if ($action !== null) { + if (isset($_GET['action'])) { + $action = $_GET['action']; + if (null !== $action) { switch ($action) { case 'edit': - if (isset($_GET['point_id']) && ($_GET['point_id'] !== null)) { + if (isset($_GET['point_id']) && (null !== $_GET['point_id'])) { return self::points_admin_points_edit(intval($_GET['point_id'])); - } else { - return self::points_admin_points_edit(); } + + return self::points_admin_points_edit(); + break; + case 'delete': - if ($_GET['point_id'] !== null) { + if (null !== $_GET['point_id']) { if (current_user_can('administrator')) { GDK_Points::remove_points($_GET['point_id']); global $wpdb; - $wcu_sql = "DELETE FROM " . GDK_Points_Database::points_get_table("users") . " WHERE status = 'removed'"; + $wcu_sql = 'DELETE FROM '.GDK_Points_Database::points_get_table('users')." WHERE status = 'removed'"; $wpdb->query($wcu_sql); - $alert = "金币已删除"; + $alert = '金币已删除'; } } + break; } } } - if ($alert != "") { - echo '
' . $alert . '
'; + if ('' != $alert) { + echo '
'.$alert.'
'; } - $current_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; - $cancel_url = remove_query_arg('point_id', remove_query_arg('action', $current_url)); - $current_url = remove_query_arg('point_id', $current_url); - $current_url = remove_query_arg('action', $current_url); + $current_url = (is_ssl() ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; + $cancel_url = remove_query_arg('point_id', remove_query_arg('action', $current_url)); + $current_url = remove_query_arg('point_id', $current_url); + $current_url = remove_query_arg('action', $current_url); $exampleListTable = new GDK_Points_List_Table(); - $exampleListTable->prepare_items(); - ?> -
-

金币管理

- - 添加金币 - -
- -
- tbody#the-list tr:hover{background:rgba(132,219,162,.61)}'; + $exampleListTable->prepare_items(); ?> +
+

金币管理

+ + 添加金币 + +
+ +
+ tbody#the-list tr:hover{background:rgba(132,219,162,.61)}'; $exampleListTable->display(); ?> -
- +user_id; - $num_points = $points->points; + if (null !== $points) { + $user_id = $points->user_id; + $num_points = $points->points; $description = $points->description; - $datetime = $points->datetime; - $status = $points->status; + $datetime = $points->datetime; + $status = $points->status; } } else { - $user_id = ""; - $num_points = 0; - $description = "ADD"; - $datetime = ""; - $status = 'accepted'; + $user_id = ''; + $num_points = 0; + $description = 'ADD'; + $datetime = ''; + $status = 'accepted'; } if (empty($point_id)) { @@ -382,7 +388,7 @@ class GDK_Points_Admin } else { $pointsclass = 'editpoint'; } - $output .= '
'; + $output .= '
'; $output .= '

'; if (empty($point_id)) { $output .= '新金币'; @@ -390,7 +396,7 @@ class GDK_Points_Admin $output .= '编辑金币'; } $output .= '

'; - $output .= '
'; + $output .= ''; $output .= '
'; if ($point_id) { @@ -441,11 +447,11 @@ class GDK_Points_Admin $output .= sprintf('', esc_attr($num_points)); $output .= ''; $output .= '

'; - $status_descriptions = array( + $status_descriptions = [ 'accepted' => '正常', - 'pending' => '待审', + 'pending' => '待审', 'rejected' => '驳回', - ); + ]; $output .= '

'; $output .= ''; @@ -467,4 +473,4 @@ class GDK_Points_Admin $output .= '

'; echo $output; } -} \ No newline at end of file +} diff --git a/class/points/class-points-shortcodes.php b/class/points/class-points-shortcodes.php index 81e244c..556f84a 100644 --- a/class/points/class-points-shortcodes.php +++ b/class/points/class-points-shortcodes.php @@ -1,6 +1,6 @@ 10, + 'limit' => 10, 'order_by' => 'points', - 'order' => 'DESC', + 'order' => 'DESC', ], $atts ); extract($options); - $output = ""; + $output = ''; $pointsusers = GDK_Points::get_users(); if (sizeof($pointsusers) > 0) { foreach ($pointsusers as $pointsuser) { @@ -36,42 +36,46 @@ class GDK_Points_Shortcodes $output .= get_user_meta($pointsuser, 'nickname', true); $output .= ':'; $output .= ''; - $output .= " " . $total . " 金币"; + $output .= ' '.$total.' 金币'; $output .= ''; $output .= '
'; } } else { $output .= '

No users

'; } + return $output; } + public static function points_user_points($atts, $content = null) { - $output = ""; - $options = shortcode_atts(['id' => ""], + $output = ''; + $options = shortcode_atts( + ['id' => ''], $atts ); extract($options); - if ($id == "") { + if ('' == $id) { $id = get_current_user_id(); } - if ($id !== 0) { + if (0 !== $id) { $points = GDK_Points::get_user_total_points($id, 'accepted'); $output .= $points; } + return $output; } - /*付费可见短代码开始*/ + // 付费可见短代码开始 public static function pay($atts, $content = null) { - $content = do_shortcode($content); + $content = do_shortcode($content); global $wpdb; $user_id = get_current_user_id(); - $pid = get_the_ID(); - $result = $wpdb->get_row("SELECT description FROM " . GDK_Points_Database::points_get_table("users") . " WHERE user_id=" . $user_id . " AND description=" . $pid . " AND status='accepted' LIMIT 0, 3;", ARRAY_A)['description']; //验证是否支付 - extract(shortcode_atts(['point' => "10"], $atts)); + $pid = get_the_ID(); + $result = $wpdb->get_row('SELECT description FROM '.GDK_Points_Database::points_get_table('users').' WHERE user_id='.$user_id.' AND description='.$pid." AND status='accepted' LIMIT 0, 3;", ARRAY_A)['description']; //验证是否支付 + extract(shortcode_atts(['point' => '10'], $atts)); $notice = ''; add_post_meta($pid, '_point_content', $content, true) or update_post_meta($pid, '_point_content', $content); //没有新建,有就更新 if (is_user_logged_in()) { @@ -82,45 +86,50 @@ class GDK_Points_Shortcodes } else { if (GDK_Points::get_user_total_points($user_id, 'accepted') < $point) { $notice .= '
付费内容'; - $notice .= '

当前隐藏内容需要支付

' . $point . '金币'; - $notice .= '

您当前拥有' . GDK_Points::get_user_total_points($user_id, 'accepted') . '金币,金币不足,请充值

'; + $notice .= '

当前隐藏内容需要支付

'.$point.'金币'; + $notice .= '

您当前拥有'.GDK_Points::get_user_total_points($user_id, 'accepted').'金币,金币不足,请充值

'; $notice .= buy_points(); $notice .= '
'; } else { $notice .= '
付费内容'; - $notice .= '

当前隐藏内容需要支付

' . $point . '金币'; - $notice .= '

您当前拥有' . GDK_Points::get_user_total_points($user_id, 'accepted') . '金币

'; - $notice .= '

'; + $notice .= '

当前隐藏内容需要支付

'.$point.'金币'; + $notice .= '

您当前拥有'.GDK_Points::get_user_total_points($user_id, 'accepted').'金币

'; + $notice .= '

'; $notice .= '
'; } } } else { $notice .= '
付费内容'; - $notice .= '

当前隐藏内容需要支付

' . $point . '金币'; + $notice .= '

当前隐藏内容需要支付

'.$point.'金币'; $notice .= '

您当前尚未登陆,请登陆后查看

'; $notice .= weixin_login_btn(); $notice .= '
'; } + return $notice; } - /*付费可见短代码结束*/ + + // 付费可见短代码结束 /** * Shortcode. 显示用户的金币细节 + * + * @param mixed $atts + * @param null|mixed $content */ public static function points_user_points_details($atts, $content = null) { $options = shortcode_atts( [ - 'user_id' => '', - 'order_by' => 'point_id', - 'order' => 'DESC', + 'user_id' => '', + 'order_by' => 'point_id', + 'order' => 'DESC', 'description' => true, ], $atts ); extract($options); date_default_timezone_set('Asia/Shanghai'); - if (is_string($description) && (($description == '0') || (strtolower($description) == 'false'))) { + if (is_string($description) && (('0' == $description) || ('false' == strtolower($description)))) { $description = false; } @@ -131,29 +140,33 @@ class GDK_Points_Shortcodes global $wp_query; $curauth = $wp_query->get_queried_object(); $user_id = $curauth->ID; - $points = GDK_Points::get_points_by_user($user_id); - $output = '' . - '' . - '' . - '' . - '' . - $desc_th . + $points = GDK_Points::get_points_by_user($user_id); + $output = '
日期时间' . - '金币类别状态
'. + ''. + ''. + ''. + ''. + $desc_th. ''; - if ($user_id !== 0) { + if (0 !== $user_id) { if (sizeof($points) > 0) { foreach ($points as $point) { $desc_td = ''; if ($description) { - $desc_td = ''; + $desc_td = ''; } - if ($point->points > 0) {$leibie = '充值';} elseif ($point->points < 0) {$leibie = '消费';} - $output .= '' . - '' . - '' . - '' . - '' . - $desc_td . + if ($point->points > 0) { + $leibie = '充值'; + } elseif ($point->points < 0) { + $leibie = '消费'; + } + $output .= ''. + ''. + ''. + ''. + ''. + $desc_td. ''; } } diff --git a/class/points/class-points.php b/class/points/class-points.php index 529e535..def0b8b 100644 --- a/class/points/class-points.php +++ b/class/points/class-points.php @@ -1,48 +1,51 @@ prefix . self::$prefix . "users"; + case 'users': + $result = $wpdb->prefix.self::$prefix.'users'; + break; } + return $result; } } /** - * GDK_Points class + * GDK_Points class. */ class GDK_Points { - public static function get_points_by_user($user_id, $limit = null, $order_by = null, $order = null, $output = OBJECT, $offset = 0) { global $wpdb; $limit_str = ''; - if (isset($limit) && ($limit !== null)) { - $limit_str = ' LIMIT ' . $offset . ' ,' . $limit; + if (isset($limit) && (null !== $limit)) { + $limit_str = ' LIMIT '.$offset.' ,'.$limit; } - $order_by_str = ""; - if (isset($order_by) && ($order_by !== null)) { - $order_by_str = " ORDER BY " . $order_by; + $order_by_str = ''; + if (isset($order_by) && (null !== $order_by)) { + $order_by_str = ' ORDER BY '.$order_by; } - $order_str = ""; - if (isset($order) && ($order !== null)) { - $order_str = " " . $order; + $order_str = ''; + if (isset($order) && (null !== $order)) { + $order_str = ' '.$order; } - $result = $wpdb->get_results('SELECT * FROM ' . GDK_Points_Database::points_get_table('users') . " WHERE user_id = '$user_id'" . $order_by_str . $order_str . $limit_str, $output); + $result = $wpdb->get_results('SELECT * FROM '.GDK_Points_Database::points_get_table('users')." WHERE user_id = '{$user_id}'".$order_by_str.$order_str.$limit_str, $output); return $result; } @@ -54,14 +57,15 @@ class GDK_Points $result = 0; $where_status = ''; - if ($status !== null) { - $where_status = " AND status = '" . $status . "'"; + if (null !== $status) { + $where_status = " AND status = '".$status."'"; } - $points = $wpdb->get_row("SELECT SUM(points) as total FROM " . GDK_Points_Database::points_get_table("users") . " WHERE user_id = '$user_id' " . $where_status); + $points = $wpdb->get_row('SELECT SUM(points) as total FROM '.GDK_Points_Database::points_get_table('users')." WHERE user_id = '{$user_id}' ".$where_status); - if ($points && ($points->total !== null)) { + if ($points && (null !== $points->total)) { $result = $points->total; } + return $result; } @@ -70,41 +74,44 @@ class GDK_Points global $wpdb; $where_status = ''; - if ($status !== null) { - $where_status = " WHERE status = '" . $status . "'"; + if (null !== $status) { + $where_status = " WHERE status = '".$status."'"; } - $points = $wpdb->get_results("SELECT SUM(points) as total, user_id FROM " . GDK_Points_Database::points_get_table("users") . $where_status . " GROUP BY user_id"); + $points = $wpdb->get_results('SELECT SUM(points) as total, user_id FROM '.GDK_Points_Database::points_get_table('users').$where_status.' GROUP BY user_id'); return $points; } /** - * Get users id who have some points - * @param $user_id + * Get users id who have some points. + * + * @param $user_id + * * @return array */ public static function get_users() { global $wpdb; - $users_id = $wpdb->get_results("SELECT user_id FROM " . GDK_Points_Database::points_get_table("users") . " GROUP BY user_id"); + $users_id = $wpdb->get_results('SELECT user_id FROM '.GDK_Points_Database::points_get_table('users').' GROUP BY user_id'); - $result = array(); + $result = []; if (sizeof($users_id) > 0) { foreach ($users_id as $user_id) { $result[] = $user_id->user_id; } } + return $result; } - public static function set_points($points, $user_id, $info = array()) + public static function set_points($points, $user_id, $info = []) { global $wpdb; - $values = array('points' => $points); + $values = ['points' => $points]; - if (isset($info['datetime']) && ($info['datetime'] !== "")) { + if (isset($info['datetime']) && ('' !== $info['datetime'])) { $values['datetime'] = $info['datetime']; } else { $values['datetime'] = date('Y-m-d H:i:s', time()); @@ -129,16 +136,19 @@ class GDK_Points } $values['user_id'] = $user_id; - $rows_affected = $wpdb->insert(GDK_Points_Database::points_get_table("users"), $values); + $rows_affected = $wpdb->insert(GDK_Points_Database::points_get_table('users'), $values); return $rows_affected; } /** * Get a points list. - * @param int $limit + * + * @param int $limit * @param string $order_by * @param string $order + * @param mixed $output + * * @return Ambigous > */ public static function get_points($limit = null, $order_by = null, $order = null, $output = OBJECT) @@ -147,20 +157,20 @@ class GDK_Points $where_str = " WHERE status != 'removed'"; - $limit_str = ""; - if (isset($limit) && ($limit !== null)) { - $limit_str = " LIMIT 0 ," . $limit; + $limit_str = ''; + if (isset($limit) && (null !== $limit)) { + $limit_str = ' LIMIT 0 ,'.$limit; } - $order_by_str = ""; - if (isset($order_by) && ($order_by !== null)) { - $order_by_str = " ORDER BY " . $order_by; + $order_by_str = ''; + if (isset($order_by) && (null !== $order_by)) { + $order_by_str = ' ORDER BY '.$order_by; } - $order_str = ""; - if (isset($order) && ($order !== null)) { - $order_str = " " . $order; + $order_str = ''; + if (isset($order) && (null !== $order)) { + $order_str = ' '.$order; } - $result = $wpdb->get_results("SELECT * FROM " . GDK_Points_Database::points_get_table("users") . $where_str . $order_by_str . $order_str . $limit_str, $output); + $result = $wpdb->get_results('SELECT * FROM '.GDK_Points_Database::points_get_table('users').$where_str.$order_by_str.$order_str.$limit_str, $output); return $result; } @@ -171,10 +181,9 @@ class GDK_Points $result = null; - if (isset($point_id) && ($point_id !== null)) { - - $points_id_str = " WHERE point_id = " . (int)$point_id; - $result = $wpdb->get_row("SELECT * FROM " . GDK_Points_Database::points_get_table("users") . $points_id_str); + if (isset($point_id) && (null !== $point_id)) { + $points_id_str = ' WHERE point_id = '.(int) $point_id; + $result = $wpdb->get_row('SELECT * FROM '.GDK_Points_Database::points_get_table('users').$points_id_str); } return $result; @@ -184,22 +193,23 @@ class GDK_Points { global $wpdb; - $values = array(); + $values = []; $values['status'] = 'removed'; - $rows_affected = $wpdb->update(GDK_Points_Database::points_get_table("users"), $values, array('point_id' => $point_id)); + $rows_affected = $wpdb->update(GDK_Points_Database::points_get_table('users'), $values, ['point_id' => $point_id]); if (!$rows_affected) { $rows_affected = null; } + return $rows_affected; } - public static function update_points($point_id, $info = array()) + public static function update_points($point_id, $info = []) { global $wpdb; - $values = array(); + $values = []; if (isset($info['user_id'])) { $values['user_id'] = $info['user_id']; @@ -229,11 +239,12 @@ class GDK_Points $values['ipv6'] = $info['ipv6']; } - $rows_affected = $wpdb->update(GDK_Points_Database::points_get_table("users"), $values, array('point_id' => $point_id)); + $rows_affected = $wpdb->update(GDK_Points_Database::points_get_table('users'), $values, ['point_id' => $point_id]); if (!$rows_affected) { // insert $rows_affected = null; } + return $rows_affected; } } diff --git a/class/points/points.php b/class/points/points.php index 058becc..b73d628 100644 --- a/class/points/points.php +++ b/class/points/points.php @@ -1,12 +1,15 @@ charset)) { - $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; + $charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset}"; } if (!empty($wpdb->collate)) { - $charset_collate .= " COLLATE $wpdb->collate"; + $charset_collate .= " COLLATE {$wpdb->collate}"; } // create tables - $points_users_table = GDK_Points_Database::points_get_table("users"); - if ($wpdb->get_var("SHOW TABLES LIKE '$points_users_table'") != $points_users_table) { - $queries[] = "CREATE TABLE $points_users_table ( + $points_users_table = GDK_Points_Database::points_get_table('users'); + if ($wpdb->get_var("SHOW TABLES LIKE '{$points_users_table}'") != $points_users_table) { + $queries[] = "CREATE TABLE {$points_users_table} ( point_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, user_id BIGINT(20) UNSIGNED NOT NULL, points BIGINT(20) DEFAULT 0, @@ -50,10 +52,10 @@ class GDK_Points_Class status varchar(10) NOT NULL DEFAULT 'accepted', type varchar(32) NULL, PRIMARY KEY (point_id) - ) $charset_collate;"; + ) {$charset_collate};"; } if (!empty($queries)) { - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + require_once ABSPATH.'wp-admin/includes/upgrade.php'; dbDelta($queries); } } diff --git a/class/qrcode.class.php b/class/qrcode.class.php index 860a033..a0d8c9f 100644 --- a/class/qrcode.class.php +++ b/class/qrcode.class.php @@ -32,22 +32,14 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - /* * Version: 1.1.4 * Build: 2010100721 */ - - //---- qrconst.php ----------------------------- - - - - /* * PHP QR Code encoder * @@ -73,64 +65,55 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - // Encoding modes - - define('QR_MODE_NUL', -1); - define('QR_MODE_NUM', 0); - define('QR_MODE_AN', 1); - define('QR_MODE_8', 2); - define('QR_MODE_KANJI', 3); - define('QR_MODE_STRUCTURE', 4); + // Encoding modes - // Levels of error correction. + define('QR_MODE_NUL', -1); + define('QR_MODE_NUM', 0); + define('QR_MODE_AN', 1); + define('QR_MODE_8', 2); + define('QR_MODE_KANJI', 3); + define('QR_MODE_STRUCTURE', 4); - define('QR_ECLEVEL_L', 0); - define('QR_ECLEVEL_M', 1); - define('QR_ECLEVEL_Q', 2); - define('QR_ECLEVEL_H', 3); - - // Supported output formats - - define('QR_FORMAT_TEXT', 0); - define('QR_FORMAT_PNG', 1); - - class qrstr { - public static function set(&$srctab, $x, $y, $repl, $replLen = false) { - $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); - } - } + // Levels of error correction. + define('QR_ECLEVEL_L', 0); + define('QR_ECLEVEL_M', 1); + define('QR_ECLEVEL_Q', 2); + define('QR_ECLEVEL_H', 3); + // Supported output formats + + define('QR_FORMAT_TEXT', 0); + define('QR_FORMAT_PNG', 1); + + class qrstr + { + public static function set(&$srctab, $x, $y, $repl, $replLen = false) + { + $srctab[$y] = substr_replace($srctab[$y], (false !== $replLen) ? substr($repl, 0, $replLen) : $repl, $x, (false !== $replLen) ? $replLen : strlen($repl)); + } + } //---- merged_config.php ----------------------------- - - - /* * PHP QR Code encoder * * Config file, tuned-up for merged verion */ - + define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true - define('QR_LOG_DIR', false); // default error logs dir - + define('QR_LOG_DIR', false); // default error logs dir + define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false - - define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images - - + define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images //---- qrtools.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -154,123 +137,126 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - class QRtools { - + class QRtools + { //---------------------------------------------------------------------- public static function binarize($frame) { $len = count($frame); foreach ($frame as &$frameLine) { - - for($i=0; $i<$len; $i++) { - $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0'; + for ($i = 0; $i < $len; ++$i) { + $frameLine[$i] = (ord($frameLine[$i]) & 1) ? '1' : '0'; } } - + return $frame; } - + //---------------------------------------------------------------------- public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') { - $barcode_array = array(); - - if (!is_array($mode)) + $barcode_array = []; + + if (!is_array($mode)) { $mode = explode(',', $mode); - + } + $eccLevel = 'L'; - + if (count($mode) > 1) { $eccLevel = $mode[1]; } - + $qrTab = QRcode::text($code, false, $eccLevel); $size = count($qrTab); - + $barcode_array['num_rows'] = $size; $barcode_array['num_cols'] = $size; - $barcode_array['bcode'] = array(); - + $barcode_array['bcode'] = []; + foreach ($qrTab as $line) { - $arrAdd = array(); - foreach(str_split($line) as $char) - $arrAdd[] = ($char=='1')?1:0; + $arrAdd = []; + foreach (str_split($line) as $char) { + $arrAdd[] = ('1' == $char) ? 1 : 0; + } $barcode_array['bcode'][] = $arrAdd; } - + return $barcode_array; } - + //---------------------------------------------------------------------- public static function clearCache() { - self::$frames = array(); + self::$frames = []; } - + //---------------------------------------------------------------------- public static function buildCache() { - QRtools::markTime('before_build_cache'); - - $mask = new QRmask(); - for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) { + QRtools::markTime('before_build_cache'); + + $mask = new QRmask(); + for ($a = 1; $a <= QRSPEC_VERSION_MAX; ++$a) { $frame = QRspec::newFrame($a); if (QR_IMAGE) { $fileName = QR_CACHE_DIR.'frame_'.$a.'.png'; QRimage::png(self::binarize($frame), $fileName, 1, 0); } - - $width = count($frame); - $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - for ($maskNo=0; $maskNo<8; $maskNo++) - $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + + $width = count($frame); + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + for ($maskNo = 0; $maskNo < 8; ++$maskNo) { + $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + } } - - QRtools::markTime('after_build_cache'); + + QRtools::markTime('after_build_cache'); } //---------------------------------------------------------------------- public static function log($outfile, $err) { if (QR_LOG_DIR !== false) { - if ($err != '') { - if ($outfile !== false) { + if ('' != $err) { + if (false !== $outfile) { file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); } else { file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); } - } + } } } - + //---------------------------------------------------------------------- - public static function dumpMask($frame) + public static function dumpMask($frame) { $width = count($frame); - for($y=0;$y<$width;$y++) { - for($x=0;$x<$width;$x++) { + for ($y = 0; $y < $width; ++$y) { + for ($x = 0; $x < $width; ++$x) { echo ord($frame[$y][$x]).','; } } } - + //---------------------------------------------------------------------- public static function markTime($markerId) { - list($usec, $sec) = explode(" ", microtime()); - $time = ((float)$usec + (float)$sec); - - if (!isset($GLOBALS['qr_time_bench'])) - $GLOBALS['qr_time_bench'] = array(); - + list($usec, $sec) = explode(' ', microtime()); + $time = ((float) $usec + (float) $sec); + + if (!isset($GLOBALS['qr_time_bench'])) { + $GLOBALS['qr_time_bench'] = []; + } + $GLOBALS['qr_time_bench'][$markerId] = $time; } - + //---------------------------------------------------------------------- public static function timeBenchmark() { self::markTime('finish'); - + $lastTime = 0; $startTime = 0; $p = 0; @@ -279,37 +265,30 @@ '; - foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { + foreach ($GLOBALS['qr_time_bench'] as $markerId => $thisTime) { if ($p > 0) { - echo ''; + echo ''; } else { $startTime = $thisTime; } - - $p++; + + ++$p; $lastTime = $thisTime; } - + echo ' - +
日期时间'. + '金币类别状态
' . $point->description . ''.$point->description.'
' . $point->datetime . '' . $point->points . '' . $leibie . '' . $point->status . '
'.$point->datetime.''.$point->points.''.$leibie.''.$point->status.'
BENCHMARK
till '.$markerId.': '.number_format($thisTime-$lastTime, 6).'s
till '.$markerId.': '.number_format($thisTime - $lastTime, 6).'s
TOTAL: '.number_format($lastTime-$startTime, 6).'s
TOTAL: '.number_format($lastTime - $startTime, 6).'s
'; } - } - + //########################################################################## - + QRtools::markTime('start'); - - - //---- qrspec.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -324,7 +303,7 @@ * The following data / specifications are taken from * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) * or - * "Automatic identification and data capture techniques -- + * "Automatic identification and data capture techniques -- * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) * * This library is free software; you can redistribute it and/or @@ -341,116 +320,216 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - + define('QRSPEC_VERSION_MAX', 40); - define('QRSPEC_WIDTH_MAX', 177); + define('QRSPEC_WIDTH_MAX', 177); - define('QRCAP_WIDTH', 0); - define('QRCAP_WORDS', 1); - define('QRCAP_REMINDER', 2); - define('QRCAP_EC', 3); + define('QRCAP_WIDTH', 0); + define('QRCAP_WORDS', 1); + define('QRCAP_REMINDER', 2); + define('QRCAP_EC', 3); + + class QRspec + { + public static $capacity = [ + [0, 0, 0, [0, 0, 0, 0]], + [21, 26, 0, [7, 10, 13, 17]], // 1 + [25, 44, 7, [10, 16, 22, 28]], + [29, 70, 7, [15, 26, 36, 44]], + [33, 100, 7, [20, 36, 52, 64]], + [37, 134, 7, [26, 48, 72, 88]], // 5 + [41, 172, 7, [36, 64, 96, 112]], + [45, 196, 0, [40, 72, 108, 130]], + [49, 242, 0, [48, 88, 132, 156]], + [53, 292, 0, [60, 110, 160, 192]], + [57, 346, 0, [72, 130, 192, 224]], //10 + [61, 404, 0, [80, 150, 224, 264]], + [65, 466, 0, [96, 176, 260, 308]], + [69, 532, 0, [104, 198, 288, 352]], + [73, 581, 3, [120, 216, 320, 384]], + [77, 655, 3, [132, 240, 360, 432]], //15 + [81, 733, 3, [144, 280, 408, 480]], + [85, 815, 3, [168, 308, 448, 532]], + [89, 901, 3, [180, 338, 504, 588]], + [93, 991, 3, [196, 364, 546, 650]], + [97, 1085, 3, [224, 416, 600, 700]], //20 + [101, 1156, 4, [224, 442, 644, 750]], + [105, 1258, 4, [252, 476, 690, 816]], + [109, 1364, 4, [270, 504, 750, 900]], + [113, 1474, 4, [300, 560, 810, 960]], + [117, 1588, 4, [312, 588, 870, 1050]], //25 + [121, 1706, 4, [336, 644, 952, 1110]], + [125, 1828, 4, [360, 700, 1020, 1200]], + [129, 1921, 3, [390, 728, 1050, 1260]], + [133, 2051, 3, [420, 784, 1140, 1350]], + [137, 2185, 3, [450, 812, 1200, 1440]], //30 + [141, 2323, 3, [480, 868, 1290, 1530]], + [145, 2465, 3, [510, 924, 1350, 1620]], + [149, 2611, 3, [540, 980, 1440, 1710]], + [153, 2761, 3, [570, 1036, 1530, 1800]], + [157, 2876, 0, [570, 1064, 1590, 1890]], //35 + [161, 3034, 0, [600, 1120, 1680, 1980]], + [165, 3196, 0, [630, 1204, 1770, 2100]], + [169, 3362, 0, [660, 1260, 1860, 2220]], + [173, 3532, 0, [720, 1316, 1950, 2310]], + [177, 3706, 0, [750, 1372, 2040, 2430]], //40 + ]; + + //###################################################################### + + public static $lengthTableBits = [ + [10, 12, 14], + [9, 11, 13], + [8, 16, 16], + [8, 10, 12], + ]; + + // Error correction code ----------------------------------------------- + // Table of the error correction code (Reed-Solomon block) + // See Table 12-16 (pp.30-36), JIS X0510:2004. + + public static $eccTable = [ + [[0, 0], [0, 0], [0, 0], [0, 0]], + [[1, 0], [1, 0], [1, 0], [1, 0]], // 1 + [[1, 0], [1, 0], [1, 0], [1, 0]], + [[1, 0], [1, 0], [2, 0], [2, 0]], + [[1, 0], [2, 0], [2, 0], [4, 0]], + [[1, 0], [2, 0], [2, 2], [2, 2]], // 5 + [[2, 0], [4, 0], [4, 0], [4, 0]], + [[2, 0], [4, 0], [2, 4], [4, 1]], + [[2, 0], [2, 2], [4, 2], [4, 2]], + [[2, 0], [3, 2], [4, 4], [4, 4]], + [[2, 2], [4, 1], [6, 2], [6, 2]], //10 + [[4, 0], [1, 4], [4, 4], [3, 8]], + [[2, 2], [6, 2], [4, 6], [7, 4]], + [[4, 0], [8, 1], [8, 4], [12, 4]], + [[3, 1], [4, 5], [11, 5], [11, 5]], + [[5, 1], [5, 5], [5, 7], [11, 7]], //15 + [[5, 1], [7, 3], [15, 2], [3, 13]], + [[1, 5], [10, 1], [1, 15], [2, 17]], + [[5, 1], [9, 4], [17, 1], [2, 19]], + [[3, 4], [3, 11], [17, 4], [9, 16]], + [[3, 5], [3, 13], [15, 5], [15, 10]], //20 + [[4, 4], [17, 0], [17, 6], [19, 6]], + [[2, 7], [17, 0], [7, 16], [34, 0]], + [[4, 5], [4, 14], [11, 14], [16, 14]], + [[6, 4], [6, 14], [11, 16], [30, 2]], + [[8, 4], [8, 13], [7, 22], [22, 13]], //25 + [[10, 2], [19, 4], [28, 6], [33, 4]], + [[8, 4], [22, 3], [8, 26], [12, 28]], + [[3, 10], [3, 23], [4, 31], [11, 31]], + [[7, 7], [21, 7], [1, 37], [19, 26]], + [[5, 10], [19, 10], [15, 25], [23, 25]], //30 + [[13, 3], [2, 29], [42, 1], [23, 28]], + [[17, 0], [10, 23], [10, 35], [19, 35]], + [[17, 1], [14, 21], [29, 19], [11, 46]], + [[13, 6], [14, 23], [44, 7], [59, 1]], + [[12, 7], [12, 26], [39, 14], [22, 41]], //35 + [[6, 14], [6, 34], [46, 10], [2, 64]], + [[17, 4], [29, 14], [49, 10], [24, 46]], + [[4, 18], [13, 32], [48, 14], [42, 32]], + [[20, 4], [40, 7], [43, 22], [10, 67]], + [[19, 6], [18, 31], [34, 34], [20, 61]], //40 + ]; + + // Alignment pattern --------------------------------------------------- + + // Positions of alignment patterns. + // This array includes only the second and the third position of the + // alignment patterns. Rest of them can be calculated from the distance + // between them. + + // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. + + public static $alignmentPattern = [ + [0, 0], + [0, 0], [18, 0], [22, 0], [26, 0], [30, 0], // 1- 5 + [34, 0], [22, 38], [24, 42], [26, 46], [28, 50], // 6-10 + [30, 54], [32, 58], [34, 62], [26, 46], [26, 48], //11-15 + [26, 50], [30, 54], [30, 56], [30, 58], [34, 62], //16-20 + [28, 50], [26, 50], [30, 54], [28, 54], [32, 58], //21-25 + [30, 58], [34, 62], [26, 50], [30, 54], [26, 52], //26-30 + [30, 56], [34, 60], [30, 58], [34, 62], [30, 54], //31-35 + [24, 50], [28, 54], [32, 58], [26, 54], [30, 58], //35-40 + ]; + + // Version information pattern ----------------------------------------- + + // Version information pattern (BCH coded). + // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. + + // size: [QRSPEC_VERSION_MAX - 6] + + public static $versionPattern = [ + 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, + 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, + 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, + 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, + 0x27541, 0x28C69, + ]; + + // Format information -------------------------------------------------- + // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) + + public static $formatInfo = [ + [0x77C4, 0x72F3, 0x7DAA, 0x789D, 0x662F, 0x6318, 0x6C41, 0x6976], + [0x5412, 0x5125, 0x5E7C, 0x5B4B, 0x45F9, 0x40CE, 0x4F97, 0x4AA0], + [0x355F, 0x3068, 0x3F31, 0x3A06, 0x24B4, 0x2183, 0x2EDA, 0x2BED], + [0x1689, 0x13BE, 0x1CE7, 0x19D0, 0x0762, 0x0255, 0x0D0C, 0x083B], + ]; + + // Frame --------------------------------------------------------------- + // Cache of initial frames. + + public static $frames = []; - class QRspec { - - public static $capacity = array( - array( 0, 0, 0, array( 0, 0, 0, 0)), - array( 21, 26, 0, array( 7, 10, 13, 17)), // 1 - array( 25, 44, 7, array( 10, 16, 22, 28)), - array( 29, 70, 7, array( 15, 26, 36, 44)), - array( 33, 100, 7, array( 20, 36, 52, 64)), - array( 37, 134, 7, array( 26, 48, 72, 88)), // 5 - array( 41, 172, 7, array( 36, 64, 96, 112)), - array( 45, 196, 0, array( 40, 72, 108, 130)), - array( 49, 242, 0, array( 48, 88, 132, 156)), - array( 53, 292, 0, array( 60, 110, 160, 192)), - array( 57, 346, 0, array( 72, 130, 192, 224)), //10 - array( 61, 404, 0, array( 80, 150, 224, 264)), - array( 65, 466, 0, array( 96, 176, 260, 308)), - array( 69, 532, 0, array( 104, 198, 288, 352)), - array( 73, 581, 3, array( 120, 216, 320, 384)), - array( 77, 655, 3, array( 132, 240, 360, 432)), //15 - array( 81, 733, 3, array( 144, 280, 408, 480)), - array( 85, 815, 3, array( 168, 308, 448, 532)), - array( 89, 901, 3, array( 180, 338, 504, 588)), - array( 93, 991, 3, array( 196, 364, 546, 650)), - array( 97, 1085, 3, array( 224, 416, 600, 700)), //20 - array(101, 1156, 4, array( 224, 442, 644, 750)), - array(105, 1258, 4, array( 252, 476, 690, 816)), - array(109, 1364, 4, array( 270, 504, 750, 900)), - array(113, 1474, 4, array( 300, 560, 810, 960)), - array(117, 1588, 4, array( 312, 588, 870, 1050)), //25 - array(121, 1706, 4, array( 336, 644, 952, 1110)), - array(125, 1828, 4, array( 360, 700, 1020, 1200)), - array(129, 1921, 3, array( 390, 728, 1050, 1260)), - array(133, 2051, 3, array( 420, 784, 1140, 1350)), - array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30 - array(141, 2323, 3, array( 480, 868, 1290, 1530)), - array(145, 2465, 3, array( 510, 924, 1350, 1620)), - array(149, 2611, 3, array( 540, 980, 1440, 1710)), - array(153, 2761, 3, array( 570, 1036, 1530, 1800)), - array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35 - array(161, 3034, 0, array( 600, 1120, 1680, 1980)), - array(165, 3196, 0, array( 630, 1204, 1770, 2100)), - array(169, 3362, 0, array( 660, 1260, 1860, 2220)), - array(173, 3532, 0, array( 720, 1316, 1950, 2310)), - array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40 - ); - //---------------------------------------------------------------------- public static function getDataLength($version, $level) { return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; } - + //---------------------------------------------------------------------- public static function getECCLength($version, $level) { return self::$capacity[$version][QRCAP_EC][$level]; } - + //---------------------------------------------------------------------- public static function getWidth($version) { return self::$capacity[$version][QRCAP_WIDTH]; } - + //---------------------------------------------------------------------- public static function getRemainder($version) { return self::$capacity[$version][QRCAP_REMINDER]; } - + //---------------------------------------------------------------------- public static function getMinimumVersion($size, $level) { - - for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) { - $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; - if($words >= $size) + for ($i = 1; $i <= QRSPEC_VERSION_MAX; ++$i) { + $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; + if ($words >= $size) { return $i; + } } return -1; } - - //###################################################################### - - public static $lengthTableBits = array( - array(10, 12, 14), - array( 9, 11, 13), - array( 8, 16, 16), - array( 8, 10, 12) - ); - + //---------------------------------------------------------------------- public static function lengthIndicator($mode, $version) { - if ($mode == QR_MODE_STRUCTURE) + if (QR_MODE_STRUCTURE == $mode) { return 0; - + } + if ($version <= 9) { $l = 0; - } else if ($version <= 26) { + } elseif ($version <= 26) { $l = 1; } else { $l = 2; @@ -458,16 +537,17 @@ return self::$lengthTableBits[$mode][$l]; } - + //---------------------------------------------------------------------- public static function maximumWords($mode, $version) { - if($mode == QR_MODE_STRUCTURE) + if (QR_MODE_STRUCTURE == $mode) { return 3; - - if($version <= 9) { + } + + if ($version <= 9) { $l = 0; - } else if($version <= 26) { + } elseif ($version <= 26) { $l = 1; } else { $l = 2; @@ -475,168 +555,103 @@ $bits = self::$lengthTableBits[$mode][$l]; $words = (1 << $bits) - 1; - - if($mode == QR_MODE_KANJI) { + + if (QR_MODE_KANJI == $mode) { $words *= 2; // the number of bytes is required } return $words; } - // Error correction code ----------------------------------------------- - // Table of the error correction code (Reed-Solomon block) - // See Table 12-16 (pp.30-36), JIS X0510:2004. - - public static $eccTable = array( - array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), - array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1 - array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), - array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), - array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), - array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5 - array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), - array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), - array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), - array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), - array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10 - array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), - array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), - array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), - array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), - array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15 - array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), - array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), - array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), - array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), - array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20 - array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), - array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), - array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), - array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), - array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25 - array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), - array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), - array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), - array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), - array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 - array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), - array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), - array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), - array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), - array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 - array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), - array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), - array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), - array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), - array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 - ); - //---------------------------------------------------------------------- // CACHEABLE!!! - + public static function getEccSpec($version, $level, array &$spec) { if (count($spec) < 5) { - $spec = array(0,0,0,0,0); + $spec = [0, 0, 0, 0, 0]; } - $b1 = self::$eccTable[$version][$level][0]; - $b2 = self::$eccTable[$version][$level][1]; + $b1 = self::$eccTable[$version][$level][0]; + $b2 = self::$eccTable[$version][$level][1]; $data = self::getDataLength($version, $level); - $ecc = self::getECCLength($version, $level); + $ecc = self::getECCLength($version, $level); - if($b2 == 0) { + if (0 == $b2) { $spec[0] = $b1; - $spec[1] = (int)($data / $b1); - $spec[2] = (int)($ecc / $b1); - $spec[3] = 0; + $spec[1] = (int) ($data / $b1); + $spec[2] = (int) ($ecc / $b1); + $spec[3] = 0; $spec[4] = 0; } else { $spec[0] = $b1; - $spec[1] = (int)($data / ($b1 + $b2)); - $spec[2] = (int)($ecc / ($b1 + $b2)); + $spec[1] = (int) ($data / ($b1 + $b2)); + $spec[2] = (int) ($ecc / ($b1 + $b2)); $spec[3] = $b2; $spec[4] = $spec[1] + 1; } } - // Alignment pattern --------------------------------------------------- - - // Positions of alignment patterns. - // This array includes only the second and the third position of the - // alignment patterns. Rest of them can be calculated from the distance - // between them. - - // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. - - public static $alignmentPattern = array( - array( 0, 0), - array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 - array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 - array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 - array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 - array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 - array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 - array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 - array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 - ); - - /** -------------------------------------------------------------------- * Put an alignment marker. + * * @param frame * @param width * @param ox,oy center coordinate of the pattern + * @param mixed $ox + * @param mixed $oy */ public static function putAlignmentMarker(array &$frame, $ox, $oy) { - $finder = array( + $finder = [ "\xa1\xa1\xa1\xa1\xa1", "\xa1\xa0\xa0\xa0\xa1", "\xa1\xa0\xa1\xa0\xa1", "\xa1\xa0\xa0\xa0\xa1", - "\xa1\xa1\xa1\xa1\xa1" - ); - - $yStart = $oy-2; - $xStart = $ox-2; - - for($y=0; $y<5; $y++) { - QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]); + "\xa1\xa1\xa1\xa1\xa1", + ]; + + $yStart = $oy - 2; + $xStart = $ox - 2; + + for ($y = 0; $y < 5; ++$y) { + QRstr::set($frame, $xStart, $yStart + $y, $finder[$y]); } } //---------------------------------------------------------------------- public static function putAlignmentPattern($version, &$frame, $width) { - if($version < 2) + if ($version < 2) { return; - - $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; - if($d < 0) { - $w = 2; - } else { - $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); } - if($w * $w - 3 == 1) { + $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; + if ($d < 0) { + $w = 2; + } else { + $w = (int) (($width - self::$alignmentPattern[$version][0]) / $d + 2); + } + + if (1 == $w * $w - 3) { $x = self::$alignmentPattern[$version][0]; $y = self::$alignmentPattern[$version][0]; self::putAlignmentMarker($frame, $x, $y); + return; } $cx = self::$alignmentPattern[$version][0]; - for($x=1; $x<$w - 1; $x++) { + for ($x = 1; $x < $w - 1; ++$x) { self::putAlignmentMarker($frame, 6, $cx); - self::putAlignmentMarker($frame, $cx, 6); + self::putAlignmentMarker($frame, $cx, 6); $cx += $d; } $cy = self::$alignmentPattern[$version][0]; - for($y=0; $y<$w-1; $y++) { + for ($y = 0; $y < $w - 1; ++$y) { $cx = self::$alignmentPattern[$version][0]; - for($x=0; $x<$w-1; $x++) { + for ($x = 0; $x < $w - 1; ++$x) { self::putAlignmentMarker($frame, $cx, $cy); $cx += $d; } @@ -644,76 +659,53 @@ } } - // Version information pattern ----------------------------------------- - - // Version information pattern (BCH coded). - // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. - - // size: [QRSPEC_VERSION_MAX - 6] - - public static $versionPattern = array( - 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, - 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, - 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, - 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, - 0x27541, 0x28c69 - ); - //---------------------------------------------------------------------- public static function getVersionPattern($version) { - if($version < 7 || $version > QRSPEC_VERSION_MAX) + if ($version < 7 || $version > QRSPEC_VERSION_MAX) { return 0; + } - return self::$versionPattern[$version -7]; + return self::$versionPattern[$version - 7]; } - // Format information -------------------------------------------------- - // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) - - public static $formatInfo = array( - array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), - array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), - array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), - array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) - ); - public static function getFormatInfo($mask, $level) { - if($mask < 0 || $mask > 7) + if ($mask < 0 || $mask > 7) { return 0; - - if($level < 0 || $level > 3) - return 0; + } + + if ($level < 0 || $level > 3) { + return 0; + } return self::$formatInfo[$level][$mask]; } - // Frame --------------------------------------------------------------- - // Cache of initial frames. - - public static $frames = array(); - /** -------------------------------------------------------------------- * Put a finder pattern. + * * @param frame * @param width * @param ox,oy upper-left coordinate of the pattern + * @param mixed $frame + * @param mixed $ox + * @param mixed $oy */ public static function putFinderPattern(&$frame, $ox, $oy) { - $finder = array( + $finder = [ "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", - "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" - ); - - for($y=0; $y<7; $y++) { - QRstr::set($frame, $ox, $oy+$y, $finder[$y]); + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", + ]; + + for ($y = 0; $y < 7; ++$y) { + QRstr::set($frame, $ox, $oy + $y, $finder[$y]); } } @@ -721,77 +713,77 @@ public static function createFrame($version) { $width = self::$capacity[$version][QRCAP_WIDTH]; - $frameLine = str_repeat ("\0", $width); + $frameLine = str_repeat("\0", $width); $frame = array_fill(0, $width, $frameLine); // Finder pattern self::putFinderPattern($frame, 0, 0); self::putFinderPattern($frame, $width - 7, 0); self::putFinderPattern($frame, 0, $width - 7); - + // Separator $yOffset = $width - 7; - - for($y=0; $y<7; $y++) { + + for ($y = 0; $y < 7; ++$y) { $frame[$y][7] = "\xc0"; $frame[$y][$width - 8] = "\xc0"; $frame[$yOffset][7] = "\xc0"; - $yOffset++; + ++$yOffset; } - + $setPattern = str_repeat("\xc0", 8); - + QRstr::set($frame, 0, 7, $setPattern); - QRstr::set($frame, $width-8, 7, $setPattern); + QRstr::set($frame, $width - 8, 7, $setPattern); QRstr::set($frame, 0, $width - 8, $setPattern); - + // Format info $setPattern = str_repeat("\x84", 9); QRstr::set($frame, 0, 8, $setPattern); QRstr::set($frame, $width - 8, 8, $setPattern, 8); - + $yOffset = $width - 8; - for($y=0; $y<8; $y++,$yOffset++) { + for ($y = 0; $y < 8; $y++,$yOffset++) { $frame[$y][8] = "\x84"; $frame[$yOffset][8] = "\x84"; } - // Timing pattern - - for($i=1; $i<$width-15; $i++) { - $frame[6][7+$i] = chr(0x90 | ($i & 1)); - $frame[7+$i][6] = chr(0x90 | ($i & 1)); + // Timing pattern + + for ($i = 1; $i < $width - 15; ++$i) { + $frame[6][7 + $i] = chr(0x90 | ($i & 1)); + $frame[7 + $i][6] = chr(0x90 | ($i & 1)); } - - // Alignment pattern + + // Alignment pattern self::putAlignmentPattern($version, $frame, $width); - - // Version information - if($version >= 7) { + + // Version information + if ($version >= 7) { $vinf = self::getVersionPattern($version); $v = $vinf; - - for($x=0; $x<6; $x++) { - for($y=0; $y<3; $y++) { - $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1)); + + for ($x = 0; $x < 6; ++$x) { + for ($y = 0; $y < 3; ++$y) { + $frame[($width - 11) + $y][$x] = chr(0x88 | ($v & 1)); $v = $v >> 1; } } $v = $vinf; - for($y=0; $y<6; $y++) { - for($x=0; $x<3; $x++) { - $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1)); + for ($y = 0; $y < 6; ++$y) { + for ($x = 0; $x < 3; ++$x) { + $frame[$y][$x + ($width - 11)] = chr(0x88 | ($v & 1)); $v = $v >> 1; } } } - - // and a little bit... + + // and a little bit... $frame[$width - 8][8] = "\x81"; - + return $frame; } @@ -799,53 +791,64 @@ public static function debug($frame, $binary_mode = false) { if ($binary_mode) { - - foreach ($frame as &$frameLine) { - $frameLine = join('  ', explode('0', $frameLine)); - $frameLine = join('██', explode('1', $frameLine)); - } - - ?> - -


        '; - echo join("
        ", $frame); - echo '






'; - - } else { - foreach ($frame as &$frameLine) { - $frameLine = join(' ', explode("\xc0", $frameLine)); + $frameLine = join('  ', explode('0', $frameLine)); + $frameLine = join('██', explode('1', $frameLine)); + } ?> + +


        '; + echo join('
        ', $frame); + echo '






'; + } else { + foreach ($frame as &$frameLine) { + $frameLine = join(' ', explode("\xc0", $frameLine)); $frameLine = join('', explode("\xc1", $frameLine)); - $frameLine = join(' ', explode("\xa0", $frameLine)); + $frameLine = join(' ', explode("\xa0", $frameLine)); $frameLine = join('', explode("\xa1", $frameLine)); $frameLine = join('', explode("\x84", $frameLine)); //format 0 $frameLine = join('', explode("\x85", $frameLine)); //format 1 $frameLine = join('', explode("\x81", $frameLine)); //special bit - $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 $frameLine = join('', explode("\x91", $frameLine)); //clock 1 - $frameLine = join(' ', explode("\x88", $frameLine)); //version + $frameLine = join(' ', explode("\x88", $frameLine)); //version $frameLine = join('', explode("\x89", $frameLine)); //version $frameLine = join('♦', explode("\x01", $frameLine)); $frameLine = join('⋅', explode("\0", $frameLine)); - } - - ?> - - "; - echo join("
", $frame); - echo "
"; - + } ?> + +'; + echo join('
', $frame); + echo '
'; } } @@ -854,23 +857,23 @@ { return gzcompress(join("\n", $frame), 9); } - + //---------------------------------------------------------------------- public static function unserial($code) { return explode("\n", gzuncompress($code)); } - + //---------------------------------------------------------------------- public static function newFrame($version) { - if($version < 1 || $version > QRSPEC_VERSION_MAX) + if ($version < 1 || $version > QRSPEC_VERSION_MAX) { return null; + } - if(!isset(self::$frames[$version])) { - + if (!isset(self::$frames[$version])) { $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat'; - + if (QR_CACHEABLE) { if (file_exists($fileName)) { self::$frames[$version] = self::unserial(file_get_contents($fileName)); @@ -882,33 +885,63 @@ self::$frames[$version] = self::createFrame($version); } } - - if(is_null(self::$frames[$version])) + + if (is_null(self::$frames[$version])) { return null; + } return self::$frames[$version]; } //---------------------------------------------------------------------- - public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; } - public static function rsBlockNum1($spec) { return $spec[0]; } - public static function rsDataCodes1($spec) { return $spec[1]; } - public static function rsEccCodes1($spec) { return $spec[2]; } - public static function rsBlockNum2($spec) { return $spec[3]; } - public static function rsDataCodes2($spec) { return $spec[4]; } - public static function rsEccCodes2($spec) { return $spec[2]; } - public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); } - public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; } - + public static function rsBlockNum($spec) + { + return $spec[0] + $spec[3]; + } + + public static function rsBlockNum1($spec) + { + return $spec[0]; + } + + public static function rsDataCodes1($spec) + { + return $spec[1]; + } + + public static function rsEccCodes1($spec) + { + return $spec[2]; + } + + public static function rsBlockNum2($spec) + { + return $spec[3]; + } + + public static function rsDataCodes2($spec) + { + return $spec[4]; + } + + public static function rsEccCodes2($spec) + { + return $spec[2]; + } + + public static function rsDataLength($spec) + { + return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); + } + + public static function rsEccLength($spec) + { + return ($spec[0] + $spec[3]) * $spec[2]; + } } - - //---- qrimage.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -931,86 +964,81 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - + define('QR_IMAGE', true); - class QRimage { - + class QRimage + { //---------------------------------------------------------------------- - public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) + public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4, $saveandprint = false) { $image = self::image($frame, $pixelPerPoint, $outerFrame); - - if ($filename === false) { - Header("Content-type: image/png"); - ImagePng($image); + + if (false === $filename) { + header('Content-type: image/png'); + imagepng($image); } else { - if($saveandprint===TRUE){ - ImagePng($image, $filename); - header("Content-type: image/png"); - ImagePng($image); - }else{ - ImagePng($image, $filename); + if (true === $saveandprint) { + imagepng($image, $filename); + header('Content-type: image/png'); + imagepng($image); + } else { + imagepng($image, $filename); } } - - ImageDestroy($image); + + imagedestroy($image); } - + //---------------------------------------------------------------------- - public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) + public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) { $image = self::image($frame, $pixelPerPoint, $outerFrame); - - if ($filename === false) { - Header("Content-type: image/jpeg"); - ImageJpeg($image, null, $q); + + if (false === $filename) { + header('Content-type: image/jpeg'); + imagejpeg($image, null, $q); } else { - ImageJpeg($image, $filename, $q); + imagejpeg($image, $filename, $q); } - - ImageDestroy($image); + + imagedestroy($image); } - + //---------------------------------------------------------------------- - private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) + private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) { $h = count($frame); $w = strlen($frame[0]); - - $imgW = $w + 2*$outerFrame; - $imgH = $h + 2*$outerFrame; - - $base_image =ImageCreate($imgW, $imgH); - - $col[0] = ImageColorAllocate($base_image,255,255,255); - $col[1] = ImageColorAllocate($base_image,0,0,0); + + $imgW = $w + 2 * $outerFrame; + $imgH = $h + 2 * $outerFrame; + + $base_image = imagecreate($imgW, $imgH); + + $col[0] = imagecolorallocate($base_image, 255, 255, 255); + $col[1] = imagecolorallocate($base_image, 0, 0, 0); imagefill($base_image, 0, 0, $col[0]); - for($y=0; $y<$h; $y++) { - for($x=0; $x<$w; $x++) { - if ($frame[$y][$x] == '1') { - ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); + for ($y = 0; $y < $h; ++$y) { + for ($x = 0; $x < $w; ++$x) { + if ('1' == $frame[$y][$x]) { + imagesetpixel($base_image, $x + $outerFrame, $y + $outerFrame, $col[1]); } } } - - $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); - ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); - ImageDestroy($base_image); - + + $target_image = imagecreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); + imagecopyresized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); + imagedestroy($base_image); + return $target_image; } } - - //---- qrinput.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -1036,102 +1064,102 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('STRUCTURE_HEADER_BITS', 20); + + define('STRUCTURE_HEADER_BITS', 20); define('MAX_STRUCTURED_SYMBOLS', 16); - class QRinputItem { - + class QRinputItem + { public $mode; public $size; public $data; public $bstream; - public function __construct($mode, $size, $data, $bstream = null) + public function __construct($mode, $size, $data, $bstream = null) { $setData = array_slice($data, 0, $size); - + if (count($setData) < $size) { - $setData = array_merge($setData, array_fill(0,$size-count($setData),0)); + $setData = array_merge($setData, array_fill(0, $size - count($setData), 0)); } - - if(!QRinput::check($mode, $size, $setData)) { - throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData)); + + if (!QRinput::check($mode, $size, $setData)) { + throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',', $setData)); + return null; } - + $this->mode = $mode; $this->size = $size; $this->data = $setData; $this->bstream = $bstream; } - + //---------------------------------------------------------------------- public function encodeModeNum($version) { try { - - $words = (int)($this->size / 3); + $words = (int) ($this->size / 3); $bs = new QRbitstream(); - + $val = 0x1; $bs->appendNum(4, $val); $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); - for($i=0; $i<$words; $i++) { - $val = (ord($this->data[$i*3 ]) - ord('0')) * 100; - $val += (ord($this->data[$i*3+1]) - ord('0')) * 10; - $val += (ord($this->data[$i*3+2]) - ord('0')); + for ($i = 0; $i < $words; ++$i) { + $val = (ord($this->data[$i * 3]) - ord('0')) * 100; + $val += (ord($this->data[$i * 3 + 1]) - ord('0')) * 10; + $val += (ord($this->data[$i * 3 + 2]) - ord('0')); $bs->appendNum(10, $val); } - if($this->size - $words * 3 == 1) { - $val = ord($this->data[$words*3]) - ord('0'); + if (1 == $this->size - $words * 3) { + $val = ord($this->data[$words * 3]) - ord('0'); $bs->appendNum(4, $val); - } else if($this->size - $words * 3 == 2) { - $val = (ord($this->data[$words*3 ]) - ord('0')) * 10; - $val += (ord($this->data[$words*3+1]) - ord('0')); + } elseif (2 == $this->size - $words * 3) { + $val = (ord($this->data[$words * 3]) - ord('0')) * 10; + $val += (ord($this->data[$words * 3 + 1]) - ord('0')); $bs->appendNum(7, $val); } $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- public function encodeModeAn($version) { try { - $words = (int)($this->size / 2); + $words = (int) ($this->size / 2); $bs = new QRbitstream(); - + $bs->appendNum(4, 0x02); $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); - for($i=0; $i<$words; $i++) { - $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45; - $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1])); + for ($i = 0; $i < $words; ++$i) { + $val = (int) QRinput::lookAnTable(ord($this->data[$i * 2])) * 45; + $val += (int) QRinput::lookAnTable(ord($this->data[$i * 2 + 1])); $bs->appendNum(11, $val); } - if($this->size & 1) { + if ($this->size & 1) { $val = QRinput::lookAnTable(ord($this->data[$words * 2])); $bs->appendNum(6, $val); } - + $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- public function encodeMode8($version) { @@ -1141,45 +1169,44 @@ $bs->appendNum(4, 0x4); $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); - for($i=0; $i<$this->size; $i++) { + for ($i = 0; $i < $this->size; ++$i) { $bs->appendNum(8, ord($this->data[$i])); } $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- public function encodeModeKanji($version) { try { - $bs = new QRbitrtream(); - - $bs->appendNum(4, 0x8); - $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2)); - for($i=0; $i<$this->size; $i+=2) { - $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]); - if($val <= 0x9ffc) { + $bs->appendNum(4, 0x8); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int) ($this->size / 2)); + + for ($i = 0; $i < $this->size; $i += 2) { + $val = (ord($this->data[$i]) << 8) | ord($this->data[$i + 1]); + if ($val <= 0x9FFC) { $val -= 0x8140; } else { - $val -= 0xc140; + $val -= 0xC140; } - - $h = ($val >> 8) * 0xc0; - $val = ($val & 0xff) + $h; + + $h = ($val >> 8) * 0xC0; + $val = ($val & 0xFF) + $h; $bs->appendNum(13, $val); } $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } @@ -1189,130 +1216,167 @@ public function encodeModeStructure() { try { - $bs = new QRbitstream(); - + $bs = new QRbitstream(); + $bs->appendNum(4, 0x03); $bs->appendNum(4, ord($this->data[1]) - 1); $bs->appendNum(4, ord($this->data[0]) - 1); $bs->appendNum(8, ord($this->data[2])); $this->bstream = $bs; + return 0; - } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- public function estimateBitStreamSizeOfEntry($version) { $bits = 0; - if($version == 0) + if (0 == $version) { $version = 1; + } + + switch ($this->mode) { + case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); + +break; + + case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); + +break; + + case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); + +break; + + case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size); + +break; + + case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; - switch($this->mode) { - case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; - case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; - case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; - case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break; - case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; default: return 0; } $l = QRspec::lengthIndicator($this->mode, $version); $m = 1 << $l; - $num = (int)(($this->size + $m - 1) / $m); + $num = (int) (($this->size + $m - 1) / $m); $bits += $num * (4 + $l); return $bits; } - + //---------------------------------------------------------------------- public function encodeBitStream($version) { try { - unset($this->bstream); $words = QRspec::maximumWords($this->mode, $version); - - if($this->size > $words) { - + + if ($this->size > $words) { $st1 = new QRinputItem($this->mode, $words, $this->data); $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); $st1->encodeBitStream($version); $st2->encodeBitStream($version); - + $this->bstream = new QRbitstream(); $this->bstream->append($st1->bstream); $this->bstream->append($st2->bstream); - - unset($st1); - unset($st2); - + + unset($st1, $st2); } else { - $ret = 0; - - switch($this->mode) { - case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; - case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; - case QR_MODE_8: $ret = $this->encodeMode8($version); break; - case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break; - case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; - + + switch ($this->mode) { + case QR_MODE_NUM: $ret = $this->encodeModeNum($version); + +break; + + case QR_MODE_AN: $ret = $this->encodeModeAn($version); + +break; + + case QR_MODE_8: $ret = $this->encodeMode8($version); + +break; + + case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version); + +break; + + case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); + +break; + default: break; } - - if($ret < 0) + + if ($ret < 0) { return -1; + } } return $this->bstream->size(); - } catch (Exception $e) { return -1; } } - }; - + } + //########################################################################## - class QRinput { - + class QRinput + { public $items; - + + //---------------------------------------------------------------------- + public static $anTable = [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, + -1, 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, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + ]; + private $version; private $level; - + //---------------------------------------------------------------------- public function __construct($version = 0, $level = QR_ECLEVEL_L) { if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { throw new Exception('Invalid version no'); - return NULL; + + return null; } - + $this->version = $version; $this->level = $level; } - + //---------------------------------------------------------------------- public function getVersion() { return $this->version; } - + //---------------------------------------------------------------------- public function setVersion($version) { - if($version < 0 || $version > QRSPEC_VERSION_MAX) { + if ($version < 0 || $version > QRSPEC_VERSION_MAX) { throw new Exception('Invalid version no'); + return -1; } @@ -1320,7 +1384,7 @@ return 0; } - + //---------------------------------------------------------------------- public function getErrorCorrectionLevel() { @@ -1330,8 +1394,9 @@ //---------------------------------------------------------------------- public function setErrorCorrectionLevel($level) { - if($level > QR_ECLEVEL_H) { + if ($level > QR_ECLEVEL_H) { throw new Exception('Invalid ECLEVEL'); + return -1; } @@ -1339,42 +1404,44 @@ return 0; } - + //---------------------------------------------------------------------- public function appendEntry(QRinputItem $entry) { $this->items[] = $entry; } - + //---------------------------------------------------------------------- public function append($mode, $size, $data) { try { $entry = new QRinputItem($mode, $size, $data); $this->items[] = $entry; + return 0; } catch (Exception $e) { return -1; } } - + //---------------------------------------------------------------------- - + public function insertStructuredAppendHeader($size, $index, $parity) { - if( $size > MAX_STRUCTURED_SYMBOLS ) { + if ($size > MAX_STRUCTURED_SYMBOLS) { throw new Exception('insertStructuredAppendHeader wrong size'); } - - if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) { + + if ($index <= 0 || $index > MAX_STRUCTURED_SYMBOLS) { throw new Exception('insertStructuredAppendHeader wrong index'); } - $buf = array($size, $index, $parity); - + $buf = [$size, $index, $parity]; + try { $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); array_unshift($this->items, $entry); + return 0; } catch (Exception $e) { return -1; @@ -1385,10 +1452,10 @@ public function calcParity() { $parity = 0; - - foreach($this->items as $item) { - if($item->mode != QR_MODE_STRUCTURE) { - for($i=$item->size-1; $i>=0; $i--) { + + foreach ($this->items as $item) { + if (QR_MODE_STRUCTURE != $item->mode) { + for ($i = $item->size - 1; $i >= 0; --$i) { $parity ^= $item->data[$i]; } } @@ -1396,12 +1463,12 @@ return $parity; } - + //---------------------------------------------------------------------- public static function checkModeNum($size, $data) { - for($i=0; $i<$size; $i++) { - if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){ + for ($i = 0; $i < $size; ++$i) { + if ((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))) { return false; } } @@ -1412,89 +1479,82 @@ //---------------------------------------------------------------------- public static function estimateBitsModeNum($size) { - $w = (int)$size / 3; + $w = (int) $size / 3; $bits = $w * 10; - - switch($size - $w * 3) { + + switch ($size - $w * 3) { case 1: $bits += 4; + break; + case 2: $bits += 7; + break; + default: break; } return $bits; } - - //---------------------------------------------------------------------- - public static $anTable = array( - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, - -1, 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, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - ); - + //---------------------------------------------------------------------- public static function lookAnTable($c) { - return (($c > 127)?-1:self::$anTable[$c]); + return ($c > 127) ? -1 : self::$anTable[$c]; } - + //---------------------------------------------------------------------- public static function checkModeAn($size, $data) { - for($i=0; $i<$size; $i++) { - if (self::lookAnTable(ord($data[$i])) == -1) { + for ($i = 0; $i < $size; ++$i) { + if (-1 == self::lookAnTable(ord($data[$i]))) { return false; } } return true; } - + //---------------------------------------------------------------------- public static function estimateBitsModeAn($size) { - $w = (int)($size / 2); + $w = (int) ($size / 2); $bits = $w * 11; - - if($size & 1) { + + if ($size & 1) { $bits += 6; } return $bits; } - + //---------------------------------------------------------------------- public static function estimateBitsMode8($size) { return $size * 8; } - + //---------------------------------------------------------------------- public function estimateBitsModeKanji($size) { - return (int)(($size / 2) * 13); + return (int) (($size / 2) * 13); } - + //---------------------------------------------------------------------- public static function checkModeKanji($size, $data) { - if($size & 1) + if ($size & 1) { return false; + } - for($i=0; $i<$size; $i+=2) { - $val = (ord($data[$i]) << 8) | ord($data[$i+1]); - if( $val < 0x8140 - || ($val > 0x9ffc && $val < 0xe040) - || $val > 0xebbf) { + for ($i = 0; $i < $size; $i += 2) { + $val = (ord($data[$i]) << 8) | ord($data[$i + 1]); + if ($val < 0x8140 + || ($val > 0x9FFC && $val < 0xE040) + || $val > 0xEBBF) { return false; } } @@ -1502,42 +1562,54 @@ return true; } - /*********************************************************************** - * Validation - **********************************************************************/ + // Validation public static function check($mode, $size, $data) { - if($size <= 0) + if ($size <= 0) { return false; + } + + switch ($mode) { + case QR_MODE_NUM: return self::checkModeNum($size, $data); + +break; + + case QR_MODE_AN: return self::checkModeAn($size, $data); + +break; + + case QR_MODE_KANJI: return self::checkModeKanji($size, $data); + +break; + + case QR_MODE_8: return true; + +break; + + case QR_MODE_STRUCTURE: return true; + +break; - switch($mode) { - case QR_MODE_NUM: return self::checkModeNum($size, $data); break; - case QR_MODE_AN: return self::checkModeAn($size, $data); break; - case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break; - case QR_MODE_8: return true; break; - case QR_MODE_STRUCTURE: return true; break; - default: break; } return false; } - - + //---------------------------------------------------------------------- public function estimateBitStreamSize($version) { $bits = 0; - foreach($this->items as $item) { + foreach ($this->items as $item) { $bits += $item->estimateBitStreamSizeOfEntry($version); } return $bits; } - + //---------------------------------------------------------------------- public function estimateVersion() { @@ -1546,7 +1618,7 @@ do { $prev = $version; $bits = $this->estimateBitStreamSize($prev); - $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + $version = QRspec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); if ($version < 0) { return -1; } @@ -1554,86 +1626,107 @@ return $version; } - + //---------------------------------------------------------------------- public static function lengthOfCode($mode, $version, $bits) { $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); - switch($mode) { + + switch ($mode) { case QR_MODE_NUM: - $chunks = (int)($payload / 10); + $chunks = (int) ($payload / 10); $remain = $payload - $chunks * 10; $size = $chunks * 3; - if($remain >= 7) { + if ($remain >= 7) { $size += 2; - } else if($remain >= 4) { - $size += 1; + } elseif ($remain >= 4) { + ++$size; } + break; + case QR_MODE_AN: - $chunks = (int)($payload / 11); + $chunks = (int) ($payload / 11); $remain = $payload - $chunks * 11; $size = $chunks * 2; - if($remain >= 6) - $size++; + if ($remain >= 6) { + ++$size; + } + break; + case QR_MODE_8: - $size = (int)($payload / 8); + $size = (int) ($payload / 8); + break; + case QR_MODE_KANJI: - $size = (int)(($payload / 13) * 2); + $size = (int) (($payload / 13) * 2); + break; + case QR_MODE_STRUCTURE: - $size = (int)($payload / 8); + $size = (int) ($payload / 8); + break; + default: $size = 0; + break; } - + $maxsize = QRspec::maximumWords($mode, $version); - if($size < 0) $size = 0; - if($size > $maxsize) $size = $maxsize; + if ($size < 0) { + $size = 0; + } + if ($size > $maxsize) { + $size = $maxsize; + } return $size; } - + //---------------------------------------------------------------------- public function createBitStream() { $total = 0; - foreach($this->items as $item) { + foreach ($this->items as $item) { $bits = $item->encodeBitStream($this->version); - - if($bits < 0) + + if ($bits < 0) { return -1; - + } + $total += $bits; } return $total; } - + //---------------------------------------------------------------------- public function convertData() { $ver = $this->estimateVersion(); - if($ver > $this->getVersion()) { + if ($ver > $this->getVersion()) { $this->setVersion($ver); } - for(;;) { + while (true) { $bits = $this->createBitStream(); - - if($bits < 0) + + if ($bits < 0) { return -1; - - $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); - if($ver < 0) { + } + + $ver = QRspec::getMinimumVersion((int) (($bits + 7) / 8), $this->level); + if ($ver < 0) { throw new Exception('WRONG VERSION'); + return -1; - } else if($ver > $this->getVersion()) { + } + if ($ver > $this->getVersion()) { $this->setVersion($ver); } else { break; @@ -1642,7 +1735,7 @@ return 0; } - + //---------------------------------------------------------------------- public function appendPaddingBit(&$bstream) { @@ -1659,47 +1752,47 @@ } $bits += 4; - $words = (int)(($bits + 7) / 8); + $words = (int) (($bits + 7) / 8); $padding = new QRbitstream(); $ret = $padding->appendNum($words * 8 - $bits + 4, 0); - - if($ret < 0) + + if ($ret < 0) { return $ret; + } $padlen = $maxwords - $words; - - if($padlen > 0) { - - $padbuf = array(); - for($i=0; $i<$padlen; $i++) { - $padbuf[$i] = ($i&1)?0x11:0xec; + + if ($padlen > 0) { + $padbuf = []; + for ($i = 0; $i < $padlen; ++$i) { + $padbuf[$i] = ($i & 1) ? 0x11 : 0xEC; } - + $ret = $padding->appendBytes($padlen, $padbuf); - - if($ret < 0) + + if ($ret < 0) { return $ret; - + } } $ret = $bstream->append($padding); - + return $ret; } //---------------------------------------------------------------------- public function mergeBitStream() { - if($this->convertData() < 0) { + if ($this->convertData() < 0) { return null; } $bstream = new QRbitstream(); - - foreach($this->items as $item) { + + foreach ($this->items as $item) { $ret = $bstream->append($item->bstream); - if($ret < 0) { + if ($ret < 0) { return null; } } @@ -1710,43 +1803,34 @@ //---------------------------------------------------------------------- public function getBitStream() { - $bstream = $this->mergeBitStream(); - - if($bstream == null) { + + if (null == $bstream) { return null; } - + $ret = $this->appendPaddingBit($bstream); - if($ret < 0) { + if ($ret < 0) { return null; } return $bstream; } - + //---------------------------------------------------------------------- public function getByteStream() { $bstream = $this->getBitStream(); - if($bstream == null) { + if (null == $bstream) { return null; } - + return $bstream->toByte(); } } - - - - - //---- qrbitstream.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -1772,33 +1856,34 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRbitstream { - - public $data = array(); - + + class QRbitstream + { + public $data = []; + //---------------------------------------------------------------------- public function size() { return count($this->data); } - + //---------------------------------------------------------------------- public function allocate($setLength) { $this->data = array_fill(0, $setLength, 0); + return 0; } - + //---------------------------------------------------------------------- public static function newFromNum($bits, $num) { $bstream = new QRbitstream(); $bstream->allocate($bits); - + $mask = 1 << ($bits - 1); - for($i=0; $i<$bits; $i++) { - if($num & $mask) { + for ($i = 0; $i < $bits; ++$i) { + if ($num & $mask) { $bstream->data[$i] = 1; } else { $bstream->data[$i] = 0; @@ -1808,61 +1893,64 @@ return $bstream; } - + //---------------------------------------------------------------------- public static function newFromBytes($size, $data) { $bstream = new QRbitstream(); $bstream->allocate($size * 8); - $p=0; + $p = 0; - for($i=0; $i<$size; $i++) { + for ($i = 0; $i < $size; ++$i) { $mask = 0x80; - for($j=0; $j<8; $j++) { - if($data[$i] & $mask) { + for ($j = 0; $j < 8; ++$j) { + if ($data[$i] & $mask) { $bstream->data[$p] = 1; } else { $bstream->data[$p] = 0; } - $p++; + ++$p; $mask = $mask >> 1; } } return $bstream; } - + //---------------------------------------------------------------------- public function append(QRbitstream $arg) { if (is_null($arg)) { return -1; } - - if($arg->size() == 0) { + + if (0 == $arg->size()) { return 0; } - - if($this->size() == 0) { + + if (0 == $this->size()) { $this->data = $arg->data; + return 0; } - + $this->data = array_values(array_merge($this->data, $arg->data)); return 0; } - + //---------------------------------------------------------------------- public function appendNum($bits, $num) { - if ($bits == 0) + if (0 == $bits) { return 0; + } $b = QRbitstream::newFromNum($bits, $num); - - if(is_null($b)) + + if (is_null($b)) { return -1; + } $ret = $this->append($b); unset($b); @@ -1873,68 +1961,62 @@ //---------------------------------------------------------------------- public function appendBytes($size, $data) { - if ($size == 0) + if (0 == $size) { return 0; + } $b = QRbitstream::newFromBytes($size, $data); - - if(is_null($b)) + + if (is_null($b)) { return -1; + } $ret = $this->append($b); unset($b); return $ret; } - + //---------------------------------------------------------------------- public function toByte() { - $size = $this->size(); - if($size == 0) { - return array(); + if (0 == $size) { + return []; } - - $data = array_fill(0, (int)(($size + 7) / 8), 0); - $bytes = (int)($size / 8); + + $data = array_fill(0, (int) (($size + 7) / 8), 0); + $bytes = (int) ($size / 8); $p = 0; - - for($i=0; $i<$bytes; $i++) { + + for ($i = 0; $i < $bytes; ++$i) { $v = 0; - for($j=0; $j<8; $j++) { + for ($j = 0; $j < 8; ++$j) { $v = $v << 1; $v |= $this->data[$p]; - $p++; + ++$p; } $data[$i] = $v; } - - if($size & 7) { + + if ($size & 7) { $v = 0; - for($j=0; $j<($size & 7); $j++) { + for ($j = 0; $j < ($size & 7); ++$j) { $v = $v << 1; $v |= $this->data[$p]; - $p++; + ++$p; } $data[$bytes] = $v; } return $data; } - } - - - //---- qrsplit.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -1949,7 +2031,7 @@ * The following data / specifications are taken from * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) * or - * "Automatic identification and data capture techniques -- + * "Automatic identification and data capture techniques -- * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) * * This library is free software; you can redistribute it and/or @@ -1966,161 +2048,166 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - class QRsplit { - + class QRsplit + { public $dataStr = ''; public $input; public $modeHint; //---------------------------------------------------------------------- - public function __construct($dataStr, $input, $modeHint) + public function __construct($dataStr, $input, $modeHint) { - $this->dataStr = $dataStr; - $this->input = $input; + $this->dataStr = $dataStr; + $this->input = $input; $this->modeHint = $modeHint; } - + //---------------------------------------------------------------------- public static function isdigitat($str, $pos) - { - if ($pos >= strlen($str)) + { + if ($pos >= strlen($str)) { return false; - - return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9'))); + } + + return (ord($str[$pos]) >= ord('0')) && (ord($str[$pos]) <= ord('9')); } - + //---------------------------------------------------------------------- public static function isalnumat($str, $pos) { - if ($pos >= strlen($str)) + if ($pos >= strlen($str)) { return false; - - return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + } + + return QRinput::lookAnTable(ord($str[$pos])) >= 0; } //---------------------------------------------------------------------- public function identifyMode($pos) { - if ($pos >= strlen($this->dataStr)) + if ($pos >= strlen($this->dataStr)) { return QR_MODE_NUL; - + } + $c = $this->dataStr[$pos]; - - if(self::isdigitat($this->dataStr, $pos)) { + + if (self::isdigitat($this->dataStr, $pos)) { return QR_MODE_NUM; - } else if(self::isalnumat($this->dataStr, $pos)) { + } + if (self::isalnumat($this->dataStr, $pos)) { return QR_MODE_AN; - } else if($this->modeHint == QR_MODE_KANJI) { - - if ($pos+1 < strlen($this->dataStr)) - { - $d = $this->dataStr[$pos+1]; + } + if (QR_MODE_KANJI == $this->modeHint) { + if ($pos + 1 < strlen($this->dataStr)) { + $d = $this->dataStr[$pos + 1]; $word = (ord($c) << 8) | ord($d); - if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { + if (($word >= 0x8140 && $word <= 0x9FFC) || ($word >= 0xE040 && $word <= 0xEBBF)) { return QR_MODE_KANJI; } } } return QR_MODE_8; - } - + } + //---------------------------------------------------------------------- public function eatNum() { $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); $p = 0; - while(self::isdigitat($this->dataStr, $p)) { - $p++; + while (self::isdigitat($this->dataStr, $p)) { + ++$p; } - + $run = $p; $mode = $this->identifyMode($p); - - if($mode == QR_MODE_8) { + + if (QR_MODE_8 == $mode) { $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + QRinput::estimateBitsMode8(1) // + 4 + l8 - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 - if($dif > 0) { + if ($dif > 0) { return $this->eat8(); } } - if($mode == QR_MODE_AN) { + if (QR_MODE_AN == $mode) { $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + QRinput::estimateBitsModeAn(1) // + 4 + la - - QRinput::estimateBitsModeAn($run + 1);// - 4 - la - if($dif > 0) { + - QRinput::estimateBitsModeAn($run + 1); // - 4 - la + if ($dif > 0) { return $this->eatAn(); } } - + $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); - if($ret < 0) + if ($ret < 0) { return -1; + } return $run; } - + //---------------------------------------------------------------------- public function eatAn() { - $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); $p = 0; - - while(self::isalnumat($this->dataStr, $p)) { - if(self::isdigitat($this->dataStr, $p)) { + + while (self::isalnumat($this->dataStr, $p)) { + if (self::isdigitat($this->dataStr, $p)) { $q = $p; - while(self::isdigitat($this->dataStr, $q)) { - $q++; + while (self::isdigitat($this->dataStr, $q)) { + ++$q; } - + $dif = QRinput::estimateBitsModeAn($p) // + 4 + la + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln - QRinput::estimateBitsModeAn($q); // - 4 - la - - if($dif < 0) { + + if ($dif < 0) { break; - } else { - $p = $q; } + $p = $q; } else { - $p++; + ++$p; } } $run = $p; - if(!self::isalnumat($this->dataStr, $p)) { + if (!self::isalnumat($this->dataStr, $p)) { $dif = QRinput::estimateBitsModeAn($run) + 4 + $la + QRinput::estimateBitsMode8(1) // + 4 + l8 - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 - if($dif > 0) { + if ($dif > 0) { return $this->eat8(); } } $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); - if($ret < 0) + if ($ret < 0) { return -1; + } return $run; } - + //---------------------------------------------------------------------- public function eatKanji() { $p = 0; - - while($this->identifyMode($p) == QR_MODE_KANJI) { + + while (QR_MODE_KANJI == $this->identifyMode($p)) { $p += 2; } - + $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); - if($ret < 0) + if ($ret < 0) { return -1; + } return $run; } @@ -2133,49 +2220,47 @@ $p = 1; $dataStrLen = strlen($this->dataStr); - - while($p < $dataStrLen) { - + + while ($p < $dataStrLen) { $mode = $this->identifyMode($p); - if($mode == QR_MODE_KANJI) { + if (QR_MODE_KANJI == $mode) { break; } - if($mode == QR_MODE_NUM) { + if (QR_MODE_NUM == $mode) { $q = $p; - while(self::isdigitat($this->dataStr, $q)) { - $q++; + while (self::isdigitat($this->dataStr, $q)) { + ++$q; } $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln - QRinput::estimateBitsMode8($q); // - 4 - l8 - if($dif < 0) { + if ($dif < 0) { break; - } else { - $p = $q; } - } else if($mode == QR_MODE_AN) { + $p = $q; + } elseif (QR_MODE_AN == $mode) { $q = $p; - while(self::isalnumat($this->dataStr, $q)) { - $q++; + while (self::isalnumat($this->dataStr, $q)) { + ++$q; } $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + QRinput::estimateBitsModeAn($q - $p) + 4 + $la - QRinput::estimateBitsMode8($q); // - 4 - l8 - if($dif < 0) { + if ($dif < 0) { break; - } else { - $p = $q; } + $p = $q; } else { - $p++; + ++$p; } } $run = $p; $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); - - if($ret < 0) + + if ($ret < 0) { return -1; + } return $run; } @@ -2183,28 +2268,43 @@ //---------------------------------------------------------------------- public function splitString() { - while (strlen($this->dataStr) > 0) - { - if($this->dataStr == '') + while (strlen($this->dataStr) > 0) { + if ('' == $this->dataStr) { return 0; - - $mode = $this->identifyMode(0); - - switch ($mode) { - case QR_MODE_NUM: $length = $this->eatNum(); break; - case QR_MODE_AN: $length = $this->eatAn(); break; - case QR_MODE_KANJI: - if ($hint == QR_MODE_KANJI) - $length = $this->eatKanji(); - else $length = $this->eat8(); - break; - default: $length = $this->eat8(); break; - } - if($length == 0) return 0; - if($length < 0) return -1; - + $mode = $this->identifyMode(0); + + switch ($mode) { + case QR_MODE_NUM: $length = $this->eatNum(); + +break; + + case QR_MODE_AN: $length = $this->eatAn(); + +break; + + case QR_MODE_KANJI: + if (QR_MODE_KANJI == $hint) { + $length = $this->eatKanji(); + } else { + $length = $this->eat8(); + } + + break; + + default: $length = $this->eat8(); + +break; + } + + if (0 == $length) { + return 0; + } + if ($length < 0) { + return -1; + } + $this->dataStr = substr($this->dataStr, $length); } } @@ -2214,16 +2314,16 @@ { $stringLen = strlen($this->dataStr); $p = 0; - - while ($p<$stringLen) { + + while ($p < $stringLen) { $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); - if($mode == QR_MODE_KANJI) { + if (QR_MODE_KANJI == $mode) { $p += 2; } else { if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); } - $p++; + ++$p; } } @@ -2233,31 +2333,27 @@ //---------------------------------------------------------------------- public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) { - if(is_null($string) || $string == '\0' || $string == '') { + if (is_null($string) || '\0' == $string || '' == $string) { throw new Exception('empty string!!!'); } $split = new QRsplit($string, $input, $modeHint); - - if(!$casesensitive) + + if (!$casesensitive) { $split->toUpper(); - + } + return $split->splitString(); } } - - //---- qrrscode.php ----------------------------- - - - /* * PHP QR Code encoder * * Reed-Solomon error correction support - * + * * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q * (libfec is released under the GNU Lesser General Public License.) * @@ -2281,21 +2377,21 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRrsItem { - - public $mm; // Bits per symbol - public $nn; // Symbols per block (= (1<nn; $x = ($x >> $this->mm) + ($x & $this->nn); } - + return $x; } - + //---------------------------------------------------------------------- public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) { @@ -2315,119 +2411,130 @@ // May be used under the terms of the GNU Lesser General Public License (LGPL) $rs = null; - + // Check parameter ranges - if($symsize < 0 || $symsize > 8) return $rs; - if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs; - if($prim <= 0 || $prim >= (1<<$symsize)) return $rs; - if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values! - if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding + if ($symsize < 0 || $symsize > 8) { + return $rs; + } + if ($fcr < 0 || $fcr >= (1 << $symsize)) { + return $rs; + } + if ($prim <= 0 || $prim >= (1 << $symsize)) { + return $rs; + } + if ($nroots < 0 || $nroots >= (1 << $symsize)) { + return $rs; + } // Can't have more roots than symbol values! + if ($pad < 0 || $pad >= ((1 << $symsize) - 1 - $nroots)) { + return $rs; + } // Too much padding $rs = new QRrsItem(); $rs->mm = $symsize; - $rs->nn = (1<<$symsize)-1; + $rs->nn = (1 << $symsize) - 1; $rs->pad = $pad; - $rs->alpha_to = array_fill(0, $rs->nn+1, 0); - $rs->index_of = array_fill(0, $rs->nn+1, 0); - + $rs->alpha_to = array_fill(0, $rs->nn + 1, 0); + $rs->index_of = array_fill(0, $rs->nn + 1, 0); + // PHP style macro replacement ;) - $NN =& $rs->nn; - $A0 =& $NN; - + $NN = &$rs->nn; + $A0 = &$NN; + // Generate Galois field lookup tables $rs->index_of[0] = $A0; // log(zero) = -inf $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 $sr = 1; - - for($i=0; $i<$rs->nn; $i++) { + + for ($i = 0; $i < $rs->nn; ++$i) { $rs->index_of[$sr] = $i; $rs->alpha_to[$i] = $sr; $sr <<= 1; - if($sr & (1<<$symsize)) { + if ($sr & (1 << $symsize)) { $sr ^= $gfpoly; } $sr &= $rs->nn; } - - if($sr != 1){ + + if (1 != $sr) { // field generator polynomial is not primitive! - $rs = NULL; + $rs = null; + return $rs; } - /* Form RS code generator polynomial from its roots */ - $rs->genpoly = array_fill(0, $nroots+1, 0); - + // Form RS code generator polynomial from its roots + $rs->genpoly = array_fill(0, $nroots + 1, 0); + $rs->fcr = $fcr; $rs->prim = $prim; $rs->nroots = $nroots; $rs->gfpoly = $gfpoly; - /* Find prim-th root of 1, used in decoding */ - for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn) + // Find prim-th root of 1, used in decoding + for ($iprim = 1; ($iprim % $prim) != 0; $iprim += $rs->nn) ; // intentional empty-body loop! - - $rs->iprim = (int)($iprim / $prim); + + $rs->iprim = (int) ($iprim / $prim); $rs->genpoly[0] = 1; - - for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) { - $rs->genpoly[$i+1] = 1; + + for ($i = 0,$root = $fcr * $prim; $i < $nroots; $i++, $root += $prim) { + $rs->genpoly[$i + 1] = 1; // Multiply rs->genpoly[] by @**(root + x) - for ($j = $i; $j > 0; $j--) { - if ($rs->genpoly[$j] != 0) { - $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; + for ($j = $i; $j > 0; --$j) { + if (0 != $rs->genpoly[$j]) { + $rs->genpoly[$j] = $rs->genpoly[$j - 1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; } else { - $rs->genpoly[$j] = $rs->genpoly[$j-1]; + $rs->genpoly[$j] = $rs->genpoly[$j - 1]; } } // rs->genpoly[0] can never be zero $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; } - + // convert rs->genpoly[] to index form for quicker encoding - for ($i = 0; $i <= $nroots; $i++) + for ($i = 0; $i <= $nroots; ++$i) { $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + } return $rs; } - + //---------------------------------------------------------------------- public function encode_rs_char($data, &$parity) { - $MM =& $this->mm; - $NN =& $this->nn; - $ALPHA_TO =& $this->alpha_to; - $INDEX_OF =& $this->index_of; - $GENPOLY =& $this->genpoly; - $NROOTS =& $this->nroots; - $FCR =& $this->fcr; - $PRIM =& $this->prim; - $IPRIM =& $this->iprim; - $PAD =& $this->pad; - $A0 =& $NN; + $MM = &$this->mm; + $NN = &$this->nn; + $ALPHA_TO = &$this->alpha_to; + $INDEX_OF = &$this->index_of; + $GENPOLY = &$this->genpoly; + $NROOTS = &$this->nroots; + $FCR = &$this->fcr; + $PRIM = &$this->prim; + $IPRIM = &$this->iprim; + $PAD = &$this->pad; + $A0 = &$NN; $parity = array_fill(0, $NROOTS, 0); - for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) { - + for ($i = 0; $i < ($NN - $NROOTS - $PAD); ++$i) { $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; - if($feedback != $A0) { + if ($feedback != $A0) { // feedback term is non-zero - + // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must // always be for the polynomials constructed by init_rs() $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); - - for($j=1;$j<$NROOTS;$j++) { - $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])]; + + for ($j = 1; $j < $NROOTS; ++$j) { + $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS - $j])]; } } - - // Shift + + // Shift array_shift($parity); - if($feedback != $A0) { + if ($feedback != $A0) { array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); } else { array_push($parity, 0); @@ -2435,23 +2542,35 @@ } } } - + //########################################################################## - - class QRrs { - - public static $items = array(); - + + class QRrs + { + public static $items = []; + //---------------------------------------------------------------------- public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) { - foreach(self::$items as $rs) { - if($rs->pad != $pad) continue; - if($rs->nroots != $nroots) continue; - if($rs->mm != $symsize) continue; - if($rs->gfpoly != $gfpoly) continue; - if($rs->fcr != $fcr) continue; - if($rs->prim != $prim) continue; + foreach (self::$items as $rs) { + if ($rs->pad != $pad) { + continue; + } + if ($rs->nroots != $nroots) { + continue; + } + if ($rs->mm != $symsize) { + continue; + } + if ($rs->gfpoly != $gfpoly) { + continue; + } + if ($rs->fcr != $fcr) { + continue; + } + if ($rs->prim != $prim) { + continue; + } return $rs; } @@ -2463,13 +2582,8 @@ } } - - //---- qrmask.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -2495,125 +2609,138 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - define('N1', 3); - define('N2', 3); - define('N3', 40); - define('N4', 10); - class QRmask { - - public $runLength = array(); - - //---------------------------------------------------------------------- - public function __construct() + define('N1', 3); + define('N2', 3); + define('N3', 40); + define('N4', 10); + + class QRmask + { + public $runLength = []; + + //---------------------------------------------------------------------- + public function __construct() { $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); } - + //---------------------------------------------------------------------- public function writeFormatInformation($width, &$frame, $mask, $level) { $blacks = 0; - $format = QRspec::getFormatInfo($mask, $level); + $format = QRspec::getFormatInfo($mask, $level); - for($i=0; $i<8; $i++) { - if($format & 1) { + for ($i = 0; $i < 8; ++$i) { + if ($format & 1) { $blacks += 2; $v = 0x85; } else { $v = 0x84; } - + $frame[8][$width - 1 - $i] = chr($v); - if($i < 6) { + if ($i < 6) { $frame[$i][8] = chr($v); } else { $frame[$i + 1][8] = chr($v); } $format = $format >> 1; } - - for($i=0; $i<7; $i++) { - if($format & 1) { + + for ($i = 0; $i < 7; ++$i) { + if ($format & 1) { $blacks += 2; $v = 0x85; } else { $v = 0x84; } - + $frame[$width - 7 + $i][8] = chr($v); - if($i == 0) { + if (0 == $i) { $frame[8][7] = chr($v); } else { $frame[8][6 - $i] = chr($v); } - + $format = $format >> 1; } return $blacks; } - + //---------------------------------------------------------------------- - public function mask0($x, $y) { return ($x+$y)&1; } - public function mask1($x, $y) { return ($y&1); } - public function mask2($x, $y) { return ($x%3); } - public function mask3($x, $y) { return ($x+$y)%3; } - public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; } - public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; } - public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; } - public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; } - - //---------------------------------------------------------------------- - private function generateMaskNo($maskNo, $width, $frame) + public function mask0($x, $y) { - $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); - - for($y=0; $y<$width; $y++) { - for($x=0; $x<$width; $x++) { - if(ord($frame[$y][$x]) & 0x80) { - $bitMask[$y][$x] = 0; - } else { - $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y); - $bitMask[$y][$x] = ($maskFunc == 0)?1:0; - } - - } - } - - return $bitMask; + return ($x + $y) & 1; } - + + public function mask1($x, $y) + { + return $y & 1; + } + + public function mask2($x, $y) + { + return $x % 3; + } + + public function mask3($x, $y) + { + return ($x + $y) % 3; + } + + public function mask4($x, $y) + { + return (((int) ($y / 2)) + ((int) ($x / 3))) & 1; + } + + public function mask5($x, $y) + { + return (($x * $y) & 1) + ($x * $y) % 3; + } + + public function mask6($x, $y) + { + return ((($x * $y) & 1) + ($x * $y) % 3) & 1; + } + + public function mask7($x, $y) + { + return ((($x * $y) % 3) + (($x + $y) & 1)) & 1; + } + //---------------------------------------------------------------------- public static function serial($bitFrame) { - $codeArr = array(); - - foreach ($bitFrame as $line) + $codeArr = []; + + foreach ($bitFrame as $line) { $codeArr[] = join('', $line); - + } + return gzcompress(join("\n", $codeArr), 9); } - + //---------------------------------------------------------------------- public static function unserial($code) { - $codeArr = array(); - + $codeArr = []; + $codeLines = explode("\n", gzuncompress($code)); - foreach ($codeLines as $line) + foreach ($codeLines as $line) { $codeArr[] = str_split($line); - + } + return $codeArr; } - + //---------------------------------------------------------------------- - public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) + public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) { $b = 0; - $bitMask = array(); - + $bitMask = []; + $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat'; if (QR_CACHEABLE) { @@ -2621,191 +2748,204 @@ $bitMask = self::unserial(file_get_contents($fileName)); } else { $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); - if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) + if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) { mkdir(QR_CACHE_DIR.'mask_'.$maskNo); + } file_put_contents($fileName, self::serial($bitMask)); } } else { $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); } - if ($maskGenOnly) + if ($maskGenOnly) { return; - + } + $d = $s; - for($y=0; $y<$width; $y++) { - for($x=0; $x<$width; $x++) { - if($bitMask[$y][$x] == 1) { - $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); + for ($y = 0; $y < $width; ++$y) { + for ($x = 0; $x < $width; ++$x) { + if (1 == $bitMask[$y][$x]) { + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int) $bitMask[$y][$x]); } - $b += (int)(ord($d[$y][$x]) & 1); + $b += (int) (ord($d[$y][$x]) & 1); } } return $b; } - + //---------------------------------------------------------------------- public function makeMask($width, $frame, $maskNo, $level) { $masked = array_fill(0, $width, str_repeat("\0", $width)); $this->makeMaskNo($maskNo, $width, $frame, $masked); $this->writeFormatInformation($width, $masked, $maskNo, $level); - + return $masked; } - + //---------------------------------------------------------------------- public function calcN1N3($length) { $demerit = 0; - for($i=0; $i<$length; $i++) { - - if($this->runLength[$i] >= 5) { + for ($i = 0; $i < $length; ++$i) { + if ($this->runLength[$i] >= 5) { $demerit += (N1 + ($this->runLength[$i] - 5)); } - if($i & 1) { - if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) { - $fact = (int)($this->runLength[$i] / 3); - if(($this->runLength[$i-2] == $fact) && - ($this->runLength[$i-1] == $fact) && - ($this->runLength[$i+1] == $fact) && - ($this->runLength[$i+2] == $fact)) { - if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) { + if ($i & 1) { + if (($i >= 3) && ($i < ($length - 2)) && ($this->runLength[$i] % 3 == 0)) { + $fact = (int) ($this->runLength[$i] / 3); + if (($this->runLength[$i - 2] == $fact) + && ($this->runLength[$i - 1] == $fact) + && ($this->runLength[$i + 1] == $fact) + && ($this->runLength[$i + 2] == $fact)) { + if (($this->runLength[$i - 3] < 0) || ($this->runLength[$i - 3] >= (4 * $fact))) { $demerit += N3; - } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) { + } elseif ((($i + 3) >= $length) || ($this->runLength[$i + 3] >= (4 * $fact))) { $demerit += N3; } } } } } + return $demerit; } - + //---------------------------------------------------------------------- public function evaluateSymbol($width, $frame) { $head = 0; $demerit = 0; - for($y=0; $y<$width; $y++) { + for ($y = 0; $y < $width; ++$y) { $head = 0; $this->runLength[0] = 1; - + $frameY = $frame[$y]; - - if ($y>0) - $frameYM = $frame[$y-1]; - - for($x=0; $x<$width; $x++) { - if(($x > 0) && ($y > 0)) { - $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]); - $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]); - - if(($b22 | ($w22 ^ 1))&1) { + + if ($y > 0) { + $frameYM = $frame[$y - 1]; + } + + for ($x = 0; $x < $width; ++$x) { + if (($x > 0) && ($y > 0)) { + $b22 = ord($frameY[$x]) & ord($frameY[$x - 1]) & ord($frameYM[$x]) & ord($frameYM[$x - 1]); + $w22 = ord($frameY[$x]) | ord($frameY[$x - 1]) | ord($frameYM[$x]) | ord($frameYM[$x - 1]); + + if (($b22 | ($w22 ^ 1)) & 1) { $demerit += N2; } } - if(($x == 0) && (ord($frameY[$x]) & 1)) { + if ((0 == $x) && (ord($frameY[$x]) & 1)) { $this->runLength[0] = -1; $head = 1; $this->runLength[$head] = 1; - } else if($x > 0) { - if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) { - $head++; + } elseif ($x > 0) { + if ((ord($frameY[$x]) ^ ord($frameY[$x - 1])) & 1) { + ++$head; $this->runLength[$head] = 1; } else { - $this->runLength[$head]++; + ++$this->runLength[$head]; } } } - - $demerit += $this->calcN1N3($head+1); + + $demerit += $this->calcN1N3($head + 1); } - for($x=0; $x<$width; $x++) { + for ($x = 0; $x < $width; ++$x) { $head = 0; $this->runLength[0] = 1; - - for($y=0; $y<$width; $y++) { - if($y == 0 && (ord($frame[$y][$x]) & 1)) { + + for ($y = 0; $y < $width; ++$y) { + if (0 == $y && (ord($frame[$y][$x]) & 1)) { $this->runLength[0] = -1; $head = 1; $this->runLength[$head] = 1; - } else if($y > 0) { - if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) { - $head++; + } elseif ($y > 0) { + if ((ord($frame[$y][$x]) ^ ord($frame[$y - 1][$x])) & 1) { + ++$head; $this->runLength[$head] = 1; } else { - $this->runLength[$head]++; + ++$this->runLength[$head]; } } } - - $demerit += $this->calcN1N3($head+1); + + $demerit += $this->calcN1N3($head + 1); } return $demerit; } - - + //---------------------------------------------------------------------- public function mask($width, $frame, $level) { $minDemerit = PHP_INT_MAX; $bestMaskNum = 0; - $bestMask = array(); - - $checked_masks = array(0,1,2,3,4,5,6,7); - + $bestMask = []; + + $checked_masks = [0, 1, 2, 3, 4, 5, 6, 7]; + if (QR_FIND_FROM_RANDOM !== false) { - - $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9); - for ($i = 0; $i < $howManuOut; $i++) { - $remPos = rand (0, count($checked_masks)-1); + $howManuOut = 8 - (QR_FIND_FROM_RANDOM % 9); + for ($i = 0; $i < $howManuOut; ++$i) { + $remPos = rand(0, count($checked_masks) - 1); unset($checked_masks[$remPos]); $checked_masks = array_values($checked_masks); } - } - + $bestMask = $frame; - - foreach($checked_masks as $i) { + + foreach ($checked_masks as $i) { $mask = array_fill(0, $width, str_repeat("\0", $width)); $demerit = 0; $blacks = 0; - $blacks = $this->makeMaskNo($i, $width, $frame, $mask); + $blacks = $this->makeMaskNo($i, $width, $frame, $mask); $blacks += $this->writeFormatInformation($width, $mask, $i, $level); - $blacks = (int)(100 * $blacks / ($width * $width)); - $demerit = (int)((int)(abs($blacks - 50) / 5) * N4); + $blacks = (int) (100 * $blacks / ($width * $width)); + $demerit = (int) ((int) (abs($blacks - 50) / 5) * N4); $demerit += $this->evaluateSymbol($width, $mask); - - if($demerit < $minDemerit) { + + if ($demerit < $minDemerit) { $minDemerit = $demerit; $bestMask = $mask; $bestMaskNum = $i; } } - + return $bestMask; } - + + //---------------------------------------------------------------------- + private function generateMaskNo($maskNo, $width, $frame) + { + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + + for ($y = 0; $y < $width; ++$y) { + for ($x = 0; $x < $width; ++$x) { + if (ord($frame[$y][$x]) & 0x80) { + $bitMask[$y][$x] = 0; + } else { + $maskFunc = call_user_func([$this, 'mask'.$maskNo], $x, $y); + $bitMask[$y][$x] = (0 == $maskFunc) ? 1 : 0; + } + } + } + + return $bitMask; + } + //---------------------------------------------------------------------- } - - - //---- qrencode.php ----------------------------- - - - /* * PHP QR Code encoder * @@ -2831,44 +2971,46 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ - - class QRrsblock { + + class QRrsblock + { public $dataLength; - public $data = array(); + public $data = []; public $eccLength; - public $ecc = array(); - + public $ecc = []; + public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) { $rs->encode_rs_char($data, $ecc); - + $this->dataLength = $dl; $this->data = $data; $this->eccLength = $el; $this->ecc = $ecc; } - }; - + } + //########################################################################## - class QRrawcode { + class QRrawcode + { public $version; - public $datacode = array(); - public $ecccode = array(); + public $datacode = []; + public $ecccode = []; public $blocks; - public $rsblocks = array(); //of RSblock + public $rsblocks = []; //of RSblock public $count; public $dataLength; public $eccLength; public $b1; - + //---------------------------------------------------------------------- public function __construct(QRinput $input) { - $spec = array(0,0,0,0,0); - + $spec = [0, 0, 0, 0, 0]; + $this->datacode = $input->getByteStream(); - if(is_null($this->datacode)) { + if (is_null($this->datacode)) { throw new Exception('null imput string'); } @@ -2880,145 +3022,144 @@ $this->eccLength = QRspec::rsEccLength($spec); $this->ecccode = array_fill(0, $this->eccLength, 0); $this->blocks = QRspec::rsBlockNum($spec); - + $ret = $this->init($spec); - if($ret < 0) { + if ($ret < 0) { throw new Exception('block alloc error'); + return null; } $this->count = 0; } - + //---------------------------------------------------------------------- public function init(array $spec) { $dl = QRspec::rsDataCodes1($spec); $el = QRspec::rsEccCodes1($spec); - $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); - + $rs = QRrs::init_rs(8, 0x11D, 0, 1, $el, 255 - $dl - $el); $blockNo = 0; $dataPos = 0; $eccPos = 0; - for($i=0; $iecccode,$eccPos); - $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); - $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); - + for ($i = 0; $i < QRspec::rsBlockNum1($spec); ++$i) { + $ecc = array_slice($this->ecccode, $eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc); + $dataPos += $dl; $eccPos += $el; - $blockNo++; + ++$blockNo; } - if(QRspec::rsBlockNum2($spec) == 0) + if (0 == QRspec::rsBlockNum2($spec)) { return 0; + } $dl = QRspec::rsDataCodes2($spec); $el = QRspec::rsEccCodes2($spec); - $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); - - if($rs == NULL) return -1; - - for($i=0; $iecccode,$eccPos); + $rs = QRrs::init_rs(8, 0x11D, 0, 1, $el, 255 - $dl - $el); + + if (null == $rs) { + return -1; + } + + for ($i = 0; $i < QRspec::rsBlockNum2($spec); ++$i) { + $ecc = array_slice($this->ecccode, $eccPos); $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); - $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); - + $this->ecccode = array_merge(array_slice($this->ecccode, 0, $eccPos), $ecc); + $dataPos += $dl; $eccPos += $el; - $blockNo++; + ++$blockNo; } return 0; } - + //---------------------------------------------------------------------- public function getCode() { - $ret; - - if($this->count < $this->dataLength) { + if ($this->count < $this->dataLength) { $row = $this->count % $this->blocks; $col = $this->count / $this->blocks; - if($col >= $this->rsblocks[0]->dataLength) { + if ($col >= $this->rsblocks[0]->dataLength) { $row += $this->b1; } $ret = $this->rsblocks[$row]->data[$col]; - } else if($this->count < $this->dataLength + $this->eccLength) { + } elseif ($this->count < $this->dataLength + $this->eccLength) { $row = ($this->count - $this->dataLength) % $this->blocks; $col = ($this->count - $this->dataLength) / $this->blocks; $ret = $this->rsblocks[$row]->ecc[$col]; } else { return 0; } - $this->count++; - + ++$this->count; + return $ret; } } //########################################################################## - - class QRcode { - + + class QRcode + { public $version; public $width; - public $data; - + public $data; + //---------------------------------------------------------------------- public function encodeMask(QRinput $input, $mask) { - if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { + if ($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { throw new Exception('wrong version'); } - if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { + if ($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { throw new Exception('wrong level'); } $raw = new QRrawcode($input); - + QRtools::markTime('after_raw'); - + $version = $raw->version; $width = QRspec::getWidth($version); $frame = QRspec::newFrame($version); - + $filler = new FrameFiller($width, $frame); - if(is_null($filler)) { - return NULL; + if (is_null($filler)) { + return null; } // inteleaved data and ecc codes - for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) { + for ($i = 0; $i < $raw->dataLength + $raw->eccLength; ++$i) { $code = $raw->getCode(); $bit = 0x80; - for($j=0; $j<8; $j++) { + for ($j = 0; $j < 8; ++$j) { $addr = $filler->next(); $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); $bit = $bit >> 1; } } - + QRtools::markTime('after_filler'); - + unset($raw); - + // remainder bits $j = QRspec::getRemainder($version); - for($i=0; $i<$j; $i++) { + for ($i = 0; $i < $j; ++$i) { $addr = $filler->next(); $filler->setFrameAt($addr, 0x02); } - + $frame = $filler->frame; unset($filler); - - + // masking $maskObj = new QRmask(); - if($mask < 0) { - + if ($mask < 0) { if (QR_FIND_BEST_MASK) { $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); } else { @@ -3027,98 +3168,108 @@ } else { $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); } - - if($masked == NULL) { - return NULL; + + if (null == $masked) { + return null; } - + QRtools::markTime('after_mask'); - + $this->version = $version; $this->width = $width; $this->data = $masked; - + return $this; } - + //---------------------------------------------------------------------- public function encodeInput(QRinput $input) { return $this->encodeMask($input, -1); } - + //---------------------------------------------------------------------- public function encodeString8bit($string, $version, $level) { - if(string == NULL) { + if (string == null) { throw new Exception('empty string!'); - return NULL; + + return null; } $input = new QRinput($version, $level); - if($input == NULL) return NULL; + if (null == $input) { + return null; + } $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); - if($ret < 0) { + if ($ret < 0) { unset($input); - return NULL; + + return null; } + return $this->encodeInput($input); } //---------------------------------------------------------------------- public function encodeString($string, $version, $level, $hint, $casesensitive) { - - if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { + if (QR_MODE_8 != $hint && QR_MODE_KANJI != $hint) { throw new Exception('bad hint'); - return NULL; + + return null; } $input = new QRinput($version, $level); - if($input == NULL) return NULL; + if (null == $input) { + return null; + } $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); - if($ret < 0) { - return NULL; + if ($ret < 0) { + return null; } return $this->encodeInput($input); } - + //---------------------------------------------------------------------- - public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false) + public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint = false) { $enc = QRencode::factory($level, $size, $margin); - return $enc->encodePNG($text, $outfile, $saveandprint=false); + + return $enc->encodePNG($text, $outfile, $saveandprint = false); } //---------------------------------------------------------------------- - public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) { $enc = QRencode::factory($level, $size, $margin); + return $enc->encode($text, $outfile); } //---------------------------------------------------------------------- - public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) { $enc = QRencode::factory($level, $size, $margin); + return $enc->encodeRAW($text, $outfile); } } - + //########################################################################## - - class FrameFiller { - + + class FrameFiller + { public $width; public $frame; public $x; public $y; public $dir; public $bit; - + //---------------------------------------------------------------------- public function __construct($width, &$frame) { @@ -3129,183 +3280,187 @@ $this->dir = -1; $this->bit = -1; } - + //---------------------------------------------------------------------- public function setFrameAt($at, $val) { $this->frame[$at['y']][$at['x']] = chr($val); } - + //---------------------------------------------------------------------- public function getFrameAt($at) { return ord($this->frame[$at['y']][$at['x']]); } - + //---------------------------------------------------------------------- public function next() { do { - - if($this->bit == -1) { + if (-1 == $this->bit) { $this->bit = 0; - return array('x'=>$this->x, 'y'=>$this->y); + + return ['x' => $this->x, 'y' => $this->y]; } $x = $this->x; $y = $this->y; $w = $this->width; - if($this->bit == 0) { - $x--; - $this->bit++; + if (0 == $this->bit) { + --$x; + ++$this->bit; } else { - $x++; + ++$x; $y += $this->dir; - $this->bit--; + --$this->bit; } - if($this->dir < 0) { - if($y < 0) { + if ($this->dir < 0) { + if ($y < 0) { $y = 0; $x -= 2; $this->dir = 1; - if($x == 6) { - $x--; + if (6 == $x) { + --$x; $y = 9; } } } else { - if($y == $w) { + if ($y == $w) { $y = $w - 1; $x -= 2; $this->dir = -1; - if($x == 6) { - $x--; + if (6 == $x) { + --$x; $y -= 8; } } } - if($x < 0 || $y < 0) return null; + if ($x < 0 || $y < 0) { + return null; + } $this->x = $x; $this->y = $y; + } while (ord($this->frame[$y][$x]) & 0x80); - } while(ord($this->frame[$y][$x]) & 0x80); - - return array('x'=>$x, 'y'=>$y); + return ['x' => $x, 'y' => $y]; } - - } ; - - //########################################################################## - - class QRencode { - + } + + //########################################################################## + + class QRencode + { public $casesensitive = true; public $eightbit = false; - + public $version = 0; public $size = 3; public $margin = 4; - + public $structured = 0; // not supported yet - + public $level = QR_ECLEVEL_L; public $hint = QR_MODE_8; - + //---------------------------------------------------------------------- public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) { $enc = new QRencode(); $enc->size = $size; $enc->margin = $margin; - + switch ($level.'') { case '0': case '1': case '2': case '3': $enc->level = $level; + break; + case 'l': case 'L': $enc->level = QR_ECLEVEL_L; + break; + case 'm': case 'M': $enc->level = QR_ECLEVEL_M; + break; + case 'q': case 'Q': $enc->level = QR_ECLEVEL_Q; + break; + case 'h': case 'H': $enc->level = QR_ECLEVEL_H; + break; } - + return $enc; } - + //---------------------------------------------------------------------- - public function encodeRAW($intext, $outfile = false) + public function encodeRAW($intext, $outfile = false) { $code = new QRcode(); - if($this->eightbit) { + if ($this->eightbit) { $code->encodeString8bit($intext, $this->version, $this->level); } else { $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); } - + return $code->data; } //---------------------------------------------------------------------- - public function encode($intext, $outfile = false) + public function encode($intext, $outfile = false) { $code = new QRcode(); - if($this->eightbit) { + if ($this->eightbit) { $code->encodeString8bit($intext, $this->version, $this->level); } else { $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); } - + QRtools::markTime('after_encode'); - - if ($outfile!== false) { + + if (false !== $outfile) { file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); } else { return QRtools::binarize($code->data); } } - + //---------------------------------------------------------------------- - public function encodePNG($intext, $outfile = false,$saveandprint=false) + public function encodePNG($intext, $outfile = false, $saveandprint = false) { try { - ob_start(); $tab = $this->encode($intext); $err = ob_get_contents(); ob_end_clean(); - - if ($err != '') + + if ('' != $err) { QRtools::log($outfile, $err); - - $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin)); - - QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint); - + } + + $maxSize = (int) (QR_PNG_MAXIMUM_SIZE / (count($tab) + 2 * $this->margin)); + + QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin, $saveandprint); } catch (Exception $e) { - QRtools::log($outfile, $e->getMessage()); - } } } - - diff --git a/class/updates.php b/class/updates.php index 9d0c50d..5bbd0f1 100644 --- a/class/updates.php +++ b/class/updates.php @@ -1,7 +1,7 @@ metadataUrl = $metadataUrl; + { + $this->metadataUrl = $metadataUrl; $this->enableAutomaticChecking = $enableAutomaticChecking; - $this->theme = $theme; - $this->optionName = 'external_theme_updates-' . $this->theme; + $this->theme = $theme; + $this->optionName = 'external_theme_updates-'.$this->theme; $this->installHooks(); } public function installHooks() - { - + { if ($this->enableAutomaticChecking) { - add_filter('pre_set_site_transient_update_themes', array($this, 'onTransientUpdate')); + add_filter('pre_set_site_transient_update_themes', [$this, 'onTransientUpdate']); } //Insert our update info into the update list maintained by WP. - add_filter('site_transient_update_themes', array($this, 'injectUpdate')); + add_filter('site_transient_update_themes', [$this, 'injectUpdate']); //Delete our update info when WP deletes its own. //This usually happens when a theme is installed, removed or upgraded. - add_action('delete_site_transient_update_themes', array($this, 'deleteStoredData')); + add_action('delete_site_transient_update_themes', [$this, 'deleteStoredData']); } - public function requestUpdate($queryArgs = array()) - { + public function requestUpdate($queryArgs = []) + { //Query args to append to the URL. Themes can add their own by using a filter callback (see addQueryArgFilter()). $queryArgs['installed_version'] = $this->getInstalledVersion(); - $queryArgs = apply_filters(self::$filterPrefix . 'query_args-' . $this->theme, $queryArgs); + $queryArgs = apply_filters(self::$filterPrefix.'query_args-'.$this->theme, $queryArgs); //Various options for the wp_remote_get() call. Themes can filter these, too. - $options = array( + $options = [ 'timeout' => 20, //seconds - ); - $options = apply_filters(self::$filterPrefix . 'options-' . $this->theme, $options); + ]; + $options = apply_filters(self::$filterPrefix.'options-'.$this->theme, $options); $url = $this->metadataUrl; if (!empty($queryArgs)) { @@ -69,24 +67,24 @@ if (!class_exists('ThemeUpdateChecker')): //Try to parse the response $themeUpdate = null; - $code = wp_remote_retrieve_response_code($result); - $body = wp_remote_retrieve_body($result); - if (($code == 200) && !empty($body)) { + $code = wp_remote_retrieve_response_code($result); + $body = wp_remote_retrieve_body($result); + if ((200 == $code) && !empty($body)) { $themeUpdate = ThemeUpdate::fromJson($body); //The update should be newer than the currently installed version. - if (($themeUpdate != null) && version_compare($themeUpdate->version, $this->getInstalledVersion(), '<=')) { + if ((null != $themeUpdate) && version_compare($themeUpdate->version, $this->getInstalledVersion(), '<=')) { $themeUpdate = null; } } - $themeUpdate = apply_filters(self::$filterPrefix . 'result-' . $this->theme, $themeUpdate, $result); - return $themeUpdate; + return apply_filters(self::$filterPrefix.'result-'.$this->theme, $themeUpdate, $result); } public function getInstalledVersion() - { + { if (function_exists('wp_get_theme')) { $theme = wp_get_theme($this->theme); + return $theme->get('Version'); } @@ -95,20 +93,21 @@ if (!class_exists('ThemeUpdateChecker')): return $theme['Version']; } } + return ''; } public function checkForUpdates() - { + { $state = get_option($this->optionName); if (empty($state)) { - $state = new StdClass; - $state->lastCheck = 0; + $state = new StdClass(); + $state->lastCheck = 0; $state->checkedVersion = ''; - $state->update = null; + $state->update = null; } - $state->lastCheck = time(); + $state->lastCheck = time(); $state->checkedVersion = $this->getInstalledVersion(); update_option($this->optionName, $state); //Save before checking in case something goes wrong @@ -117,16 +116,17 @@ if (!class_exists('ThemeUpdateChecker')): } public function onTransientUpdate($value) - { + { if (!$this->automaticCheckDone) { $this->checkForUpdates(); $this->automaticCheckDone = true; } + return $value; } public function injectUpdate($updates) - { + { $state = get_option($this->optionName); //Is there an update to insert? @@ -138,38 +138,36 @@ if (!class_exists('ThemeUpdateChecker')): } public function deleteStoredData() - { + { delete_option($this->optionName); } public function addQueryArgFilter($callback) - { - add_filter(self::$filterPrefix . 'query_args-' . $this->theme, $callback); + { + add_filter(self::$filterPrefix.'query_args-'.$this->theme, $callback); } public function addHttpRequestArgFilter($callback) - { - add_filter(self::$filterPrefix . 'options-' . $this->theme, $callback); + { + add_filter(self::$filterPrefix.'options-'.$this->theme, $callback); } public function addResultFilter($callback) - { - add_filter(self::$filterPrefix . 'result-' . $this->theme, $callback, 10, 2); + { + add_filter(self::$filterPrefix.'result-'.$this->theme, $callback, 10, 2); } } +} -endif; - -if (!class_exists('ThemeUpdate')): - +if (!class_exists('ThemeUpdate')) { class ThemeUpdate -{ + { public $version; //Version number. public $details_url; //The URL where the user can learn more about this version. public $download_url; //The download URL for this version of the theme. Optional. public static function fromJson($json) - { + { $apiResponse = json_decode($json); if (empty($apiResponse) || !is_object($apiResponse)) { return null; @@ -183,18 +181,18 @@ if (!class_exists('ThemeUpdate')): $update = new self(); foreach (get_object_vars($apiResponse) as $key => $value) { - $update->$key = $value; + $update->{$key} = $value; } return $update; } public function toWpFormat() - { - $update = array( + { + $update = [ 'new_version' => $this->version, - 'url' => $this->details_url, - ); + 'url' => $this->details_url, + ]; if (!empty($this->download_url)) { $update['package'] = $this->download_url; @@ -203,5 +201,4 @@ if (!class_exists('ThemeUpdate')): return $update; } } - -endif; +} diff --git a/class/wechat.php b/class/wechat.php index c2a824a..b63bf6c 100644 --- a/class/wechat.php +++ b/class/wechat.php @@ -1,47 +1,41 @@ token = $wx_token; + $this->token = $wx_token; $this->captcha = $wx_captcha; } + private function __checkSignature() { - $signature = $_GET["signature"]; - $timestamp = $_GET["timestamp"]; - $nonce = $_GET["nonce"]; - $token = $this->token; - $tmpArr = array($token, $timestamp, $nonce); + $signature = $_GET['signature']; + $timestamp = $_GET['timestamp']; + $nonce = $_GET['nonce']; + $token = $this->token; + $tmpArr = [$token, $timestamp, $nonce]; sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); + return $tmpStr == $signature ? true : false; } - protected function _valid() - { - $echoStr = $_GET["echostr"]; - //valid signature , option - if ($this->checkSignature()) { - echo $echoStr; - exit; - } else { - echo 'error signature'; - } - } + public function responseMsg() { //如果是验证请求,则执行签名验证并退出 - if (!empty($_GET["echostr"])) { + if (!empty($_GET['echostr'])) { $this->valid(); //验证签名是否有效 return; //返回退出 } - if ($_SERVER['REQUEST_METHOD'] != 'POST') { + if ('POST' != $_SERVER['REQUEST_METHOD']) { echo ''; + return; } //如果不是验证请求,则 @@ -50,45 +44,61 @@ class Wechat_Captcha $postData = file_get_contents('php://input'); if (empty($postData)) { echo ''; + return; } //如果没有POST数据,则退出 if (!empty($postData)) { //解析POST数据(XML格式) - $object = simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA); - $messgeType = trim($object->MsgType); //取得消息类型 + $object = simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA); + $messgeType = trim($object->MsgType); //取得消息类型 $this->fromUser = $object->FromUserName; - $this->toUser = $object->ToUserName; - $keyword = trim($object->Content); - if ($messgeType == 'text' && $keyword == '验证码') { - $response_content = '您的验证码为:【' . $this->captcha . '】,验证码有效期为2分钟,请抓紧使用,过期需重新申请'; - $xmlTemplate = " + $this->toUser = $object->ToUserName; + $keyword = trim($object->Content); + if ('text' == $messgeType && '验证码' == $keyword) { + $response_content = '您的验证码为:【'.$this->captcha.'】,验证码有效期为2分钟,请抓紧使用,过期需重新申请'; + $xmlTemplate = ' %s %d - "; + '; $xmlText = sprintf($xmlTemplate, $this->fromUser, $this->toUser, time(), $response_content, 0); echo $xmlText; } } else { - echo ""; + echo ''; + + exit; + } + } + + protected function _valid() + { + $echoStr = $_GET['echostr']; + //valid signature , option + if ($this->checkSignature()) { + echo $echoStr; + + exit; + } + echo 'error signature'; + } +} + +function wx_process() +{ + if (isset($_GET['signature'])) { + global $wx_captchas; + if (!isset($wx_captchas)) { + $wx_token = gdk_option('gdk_wxmp_token'); + $wx_captchas = new Wechat_Captcha($wx_token, wx_captcha()); + $wx_captchas->responseMsg(); + exit; } } } - -function wx_process() { - if(isset($_GET["signature"])) { - global $wx_captchas; - if(!isset($wx_captchas)) { - $wx_token = trim(gdk_option('gdk_wxmp_token')); - $wx_captchas = new Wechat_Captcha($wx_token, wx_captcha()); - $wx_captchas->responseMsg(); - exit; - } - } -} add_action('parse_request', 'wx_process', 4); diff --git a/class/widget_cache.php b/class/widget_cache.php index 83027be..82d8b6b 100644 --- a/class/widget_cache.php +++ b/class/widget_cache.php @@ -3,6 +3,7 @@ class Auto_Widget_cache { public $cache_time = 18000; + /* MINUTE_IN_SECONDS = 60 seconds HOUR_IN_SECONDS = 3600 seconds @@ -12,25 +13,27 @@ class Auto_Widget_cache */ public function __construct() { - add_filter('widget_display_callback', array($this, '_cache_widget_output'), 10, 3); - add_action('in_widget_form', array($this, 'in_widget_form'), 5, 3); - add_filter('widget_update_callback', array($this, 'widget_update_callback'), 5, 3); + add_filter('widget_display_callback', [$this, '_cache_widget_output'], 10, 3); + add_action('in_widget_form', [$this, 'in_widget_form'], 5, 3); + add_filter('widget_update_callback', [$this, 'widget_update_callback'], 5, 3); } + public function get_widget_key($i, $a) { - return 'WC-' . md5(serialize(array($i, $a))); + return 'WC-'.md5(serialize([$i, $a])); } + public function cache_widget_output($instance, $widget, $args) { if (false === $instance) { return $instance; } - if (isset($instance['wc_cache']) && $instance['wc_cache'] == true) { + if (isset($instance['wc_cache']) && true == $instance['wc_cache']) { return $instance; } - $timer_start = microtime(true); + $timer_start = microtime(true); $transient_name = $this->get_widget_key($instance, $args); if (false === ($cached_widget = get_transient($transient_name))) { ob_start(); @@ -39,32 +42,34 @@ class Auto_Widget_cache set_transient($transient_name, $cached_widget, $this->cache_time); } echo $cached_widget; - echo ''; + echo ''; + return false; } + public function in_widget_form($t, $return, $instance) { - $instance = wp_parse_args((array)$instance, array('title' => '', 'text' => '', 'wc_cache' => null)); + $instance = wp_parse_args((array) $instance, ['title' => '', 'text' => '', 'wc_cache' => null]); if (!isset($instance['wc_cache'])) { $instance['wc_cache'] = null; - } - - ?> -

- get_field_id('wc_cache'); ?>" name="get_field_name('wc_cache'); ?>" type="checkbox" /> - -

- + "thumb", - "title" => "自定义缩略图", - "description" => "这里可以输入您的自定义缩略图链接", - "type" => "text", - "scope" => ['post'], - "capability" => "edit_posts", - ), - array( - "name" => "download_name", - "title" => "单页下载文件名字", - "description" => "这里可以输入您的下载文件的名字", - "type" => "text", - "scope" => ['post'], - "capability" => "edit_posts", - ), - array( - "name" => "download_size", - "title" => "单页下载文件大小", - "description" => "这里可以输入您的下载文件的大小,可以加上单位,比如:233KB或者233MB", - "type" => "text", - "scope" => ['post'], - "capability" => "edit_posts", - ), - array( - "name" => "download_link", - "title" => "单页下载下载链接", - "description" => "按照链接,名字,备注的格式,注意中间是用英文逗号,换行可添加多个,举个栗子:https://www.baidu.com,百度官网,中国最大的搜索引擎网站", - "type" => "textarea", - "scope" => ['post'], - "capability" => "edit_posts", - ), - ); + public $customFields = [ + [ + 'name' => 'thumb', + 'title' => '自定义缩略图', + 'description' => '这里可以输入您的自定义缩略图链接', + 'type' => 'text', + 'scope' => ['post'], + 'capability' => 'edit_posts', + ], + [ + 'name' => 'download_name', + 'title' => '单页下载文件名字', + 'description' => '这里可以输入您的下载文件的名字', + 'type' => 'text', + 'scope' => ['post'], + 'capability' => 'edit_posts', + ], + [ + 'name' => 'download_size', + 'title' => '单页下载文件大小', + 'description' => '这里可以输入您的下载文件的大小,可以加上单位,比如:233KB或者233MB', + 'type' => 'text', + 'scope' => ['post'], + 'capability' => 'edit_posts', + ], + [ + 'name' => 'download_link', + 'title' => '单页下载下载链接', + 'description' => '按照链接,名字,备注的格式,注意中间是用英文逗号,换行可添加多个,举个栗子:https://www.baidu.com,百度官网,中国最大的搜索引擎网站', + 'type' => 'textarea', + 'scope' => ['post'], + 'capability' => 'edit_posts', + ], + ]; + /** - * PHP 5 Constructor + * PHP 5 Constructor. */ public function __construct() { - add_action('admin_menu', array($this, 'createCustomFields')); - add_action('save_post', array($this, 'saveCustomFields'), 1, 2); + add_action('admin_menu', [$this, 'createCustomFields']); + add_action('save_post', [$this, 'saveCustomFields'], 1, 2); } + /** - * 创建一组你自己的自定义栏目 + * 创建一组你自己的自定义栏目. */ public function createCustomFields() { if (function_exists('add_meta_box')) { foreach ($this->postTypes as $postType) { - add_meta_box('my-custom-fields', '文章选项', array($this, 'displayCustomFields'), $postType, 'normal', 'high'); + add_meta_box('my-custom-fields', '文章选项', [$this, 'displayCustomFields'], $postType, 'normal', 'high'); } } } + /** * 在文章发布页显示出来面板 */ public function displayCustomFields() { - global $post; - ?> -
- +
+ customFields as $customField) { // Check scope - $scope = $customField['scope']; + $scope = $customField['scope']; $output = false; foreach ($scope as $scopeItem) { switch ($scopeItem) { - default:{ + default: if ($post->post_type == $scopeItem) { $output = true; } break; - } } if ($output) { break; } - } // 检查权限 if (!current_user_can($customField['capability'], $post->ID)) { @@ -104,57 +103,67 @@ if (!class_exists('myCustomFields')) { // 通过则输出 if ($output) { ?> -
- "> + prefix . $customField['name'] . '" style="display:inline;">' . $customField['title'] . ' '; - echo 'ID, $this->prefix . $customField['name'], true) == "1") { + echo ' '; + echo 'ID, $this->prefix.$customField['name'], true)) { echo ' checked="checked"'; } echo '" style="width: auto;" />'; + break; - } - case "textarea": - case "wysiwyg":{ + + case 'textarea': + case 'wysiwyg': // Text area - echo ''; - echo ''; + echo ''; + echo ''; // WYSIWYG - if ($customField['type'] == "wysiwyg") { ?> - - + + prefix . $customField['name'] . '">' . $customField['title'] . ''; - echo ''; + echo ''; + echo ''; + break; - } - } - ?> - ' . $customField['description'] . '

'; - } - ?> -
- + '.$customField['description'].'

'; + } ?> +
+ -
- +customFields as $customField) { if (current_user_can($customField['capability'], $post_id)) { - if (isset($_POST[$this->prefix . $customField['name']]) && trim($_POST[$this->prefix . $customField['name']])) { - $value = $_POST[$this->prefix . $customField['name']]; + if (isset($_POST[$this->prefix.$customField['name']]) && trim($_POST[$this->prefix.$customField['name']])) { + $value = $_POST[$this->prefix.$customField['name']]; // Auto-paragraphs for any WYSIWYG - if ($customField['type'] == "wysiwyg") { + if ('wysiwyg' == $customField['type']) { $value = wpautop($value); } - update_post_meta($post_id, $this->prefix . $customField['name'], $value); + update_post_meta($post_id, $this->prefix.$customField['name'], $value); } else { - delete_post_meta($post_id, $this->prefix . $customField['name']); + delete_post_meta($post_id, $this->prefix.$customField['name']); } } } } - } // End Class - } // End if class exists statement // Instantiate the class if (class_exists('myCustomFields')) { $myCustomFields_var = new myCustomFields(); } -?> \ No newline at end of file diff --git a/framework/options-config.php b/framework/options-config.php index 3bd0c1b..9c729f6 100644 --- a/framework/options-config.php +++ b/framework/options-config.php @@ -1,385 +1,384 @@ [ + '优化' => [ [ - 'name' => '古腾堡编辑器', - 'desc' => '新版编辑器尚不成熟,很多主题不兼容,建议禁用', - 'id' => 'gdk_diasble_gutenberg', - 'type' => 'select', + 'name' => '古腾堡编辑器', + 'desc' => '新版编辑器尚不成熟,很多主题不兼容,建议禁用', + 'id' => 'gdk_diasble_gutenberg', + 'type' => 'select', 'options' => [ '0' => '启用', '1' => '禁用', ], - 'std' => '1', + 'std' => '1', ], [ - 'name' => '新版小工具块编辑器', - 'desc' => '5.8版本小工具使用块编辑器,很多主题不兼容,建议禁用', - 'id' => 'gdk_diasble_widgets_block', - 'type' => 'select', + 'name' => '新版小工具块编辑器', + 'desc' => '5.8版本小工具使用块编辑器,很多主题不兼容,建议禁用', + 'id' => 'gdk_diasble_widgets_block', + 'type' => 'select', 'options' => [ '0' => '启用', '1' => '禁用', ], - 'std' => '1', + 'std' => '1', ], [ - 'name' => '头部冗余代码', - 'desc' => '禁用
WordPress头部自带很多无用代码,不安全且浪费,建议禁用', - 'id' => 'gdk_diasble_head_useless', - 'type' => 'checkbox', + 'name' => '头部冗余代码', + 'desc' => '禁用
WordPress头部自带很多无用代码,不安全且浪费,建议禁用', + 'id' => 'gdk_diasble_head_useless', + 'type' => 'checkbox', ], [ - 'name' => 'Emojis表情功能', - 'desc' => '禁用
WordPress自带的Emojis功能会加载国外资源,那是网站速度,建议禁用', - 'id' => 'gdk_disable_emojis', - 'type' => 'checkbox', + 'name' => 'Emojis表情功能', + 'desc' => '禁用
WordPress自带的Emojis功能会加载国外资源,那是网站速度,建议禁用', + 'id' => 'gdk_disable_emojis', + 'type' => 'checkbox', ], [ - 'name' => '前台Dashicons字体资源', - 'desc' => '禁用
一般前台不需要加载dashicons字体,建议禁用', - 'id' => 'gdk_disable_dashicons', - 'type' => 'checkbox', + 'name' => '前台Dashicons字体资源', + 'desc' => '禁用
一般前台不需要加载dashicons字体,建议禁用', + 'id' => 'gdk_disable_dashicons', + 'type' => 'checkbox', ], [ 'name' => '中英文自动空格', 'desc' => '启用
【开启后,中文和英文之前将自动增加一个空格,比如:WordPress插件=>WordPress 插件】', - 'id' => 'gdk_auto_space', + 'id' => 'gdk_auto_space', 'type' => 'checkbox', ], [ - 'name' => 'XML-RPC发布功能', - 'desc' => '禁用
该功能有安全风险,如果不使用WordPress的手机客户端或者第三方编辑器软件,那么建议禁用', - 'id' => 'gdk_disable_xmlrpc', - 'type' => 'checkbox', + 'name' => 'XML-RPC发布功能', + 'desc' => '禁用
该功能有安全风险,如果不使用WordPress的手机客户端或者第三方编辑器软件,那么建议禁用', + 'id' => 'gdk_disable_xmlrpc', + 'type' => 'checkbox', ], [ - 'name' => '文章版本功能', - 'desc' => '禁用
该功能有会造成数据库体量暴增为了你的数据库考虑,建议禁用', - 'id' => 'gdk_disable_revision', - 'type' => 'checkbox', + 'name' => '文章版本功能', + 'desc' => '禁用
该功能有会造成数据库体量暴增为了你的数据库考虑,建议禁用', + 'id' => 'gdk_disable_revision', + 'type' => 'checkbox', ], [ - 'name' => 'Pingback功能', - 'desc' => '禁用
该功能会增加垃圾评论的几率,建议禁用', - 'id' => 'gdk_disable_trackbacks', - 'type' => 'checkbox', + 'name' => 'Pingback功能', + 'desc' => '禁用
该功能会增加垃圾评论的几率,建议禁用', + 'id' => 'gdk_disable_trackbacks', + 'type' => 'checkbox', ], [ - 'name' => '文件上传重命名', - 'desc' => '该功能会将上传的文件图片等按照数字格式重命名,服务器文件不建议使用中文,默认开启', - 'id' => 'gdk_upload_rename', - 'type' => 'select', + 'name' => '文件上传重命名', + 'desc' => '该功能会将上传的文件图片等按照数字格式重命名,服务器文件不建议使用中文,默认开启', + 'id' => 'gdk_upload_rename', + 'type' => 'select', 'options' => [ '0' => '禁用', '1' => '开启', ], - 'std' => '1', + 'std' => '1', ], [ - 'name' => 'WordPress更新', - 'desc' => '禁用
WordPress更新会不时发送请求数据,所以可以关闭WordPress更新,包括主题,插件和内核更新,建议禁用', - 'id' => 'gdk_diasble_wp_update', - 'type' => 'checkbox', + 'name' => 'WordPress更新', + 'desc' => '禁用
WordPress更新会不时发送请求数据,所以可以关闭WordPress更新,包括主题,插件和内核更新,建议禁用', + 'id' => 'gdk_diasble_wp_update', + 'type' => 'checkbox', ], [ - 'name' => 'WordPress更新中国加速', - 'desc' => '启用
该功能会帮助更顺利更新WordPress,注意:如果上面的WordPress禁用更新了,此处设置无效,由Litepress提供镜像,建议开启', - 'id' => 'gdk_porxy_update', - 'type' => 'checkbox', + 'name' => 'WordPress更新中国加速', + 'desc' => '启用
该功能会帮助更顺利更新WordPress,注意:如果上面的WordPress禁用更新了,此处设置无效,由Litepress提供镜像,建议开启', + 'id' => 'gdk_porxy_update', + 'type' => 'checkbox', ], [ - 'name' => '头像加速功能', - 'desc' => '该功能会增加头像加载速度,有随机头像,V2EX头像镜像和七牛头像镜像,默认选择随机头像,本地头像和微信头像不受影响', - 'id' => 'gdk_switch_get_avatar', - 'type' => 'select', + 'name' => '头像加速功能', + 'desc' => '该功能会增加头像加载速度,有随机头像,V2EX头像镜像和七牛头像镜像,默认选择随机头像,本地头像和微信头像不受影响', + 'id' => 'gdk_switch_get_avatar', + 'type' => 'select', 'options' => [ '1' => '随机头像', '2' => 'V2EX头像镜像', '3' => '七牛头像镜像', '4' => 'Cravatar', ], - 'std' => '1', + 'std' => '1', ], ], 'SEO' => [ [ 'name' => '网站关键字', //选项显示的文字,选填 - 'desc' => '各关键字间用半角逗号', '分割,数量在6个以内最佳。', //选项显示的一段描述文字,选填 - 'id' => 'gdk_keywords', //选项的id,必须是唯一,后面根据这个获取值,必填 - 'type' => 'text', //种类,这个是普通的文字输入,必填 - 'std' => '', //选项的默认值,选填 + 'desc' => '各关键字间用半角逗号', '分割,数量在6个以内最佳。', //选项显示的一段描述文字,选填 + 'id' => 'gdk_keywords', //选项的id,必须是唯一,后面根据这个获取值,必填 + 'type' => 'text', //种类,这个是普通的文字输入,必填 + 'std' => '', //选项的默认值,选填 ], [ 'name' => '网站描述', 'desc' => '用简洁的文字描述本站点,字数建议在120个字以内。', - 'id' => 'gdk_description', + 'id' => 'gdk_description', 'type' => 'text', ], [ 'name' => 'title分隔符', 'desc' => '显示在浏览器标题栏的一个用来分隔网站名字的', - 'id' => 'gdk_delimiter', + 'id' => 'gdk_delimiter', 'type' => 'text', - 'std' => '|', + 'std' => '|', ], [ - 'name' => '自动添加nofollow', - 'desc' => '该功能会给外链自动添加nofollow,推荐开启', - 'id' => 'gdk_nofollow', - 'type' => 'checkbox', + 'name' => '自动添加nofollow', + 'desc' => '该功能会给外链自动添加nofollow,推荐开启', + 'id' => 'gdk_nofollow', + 'type' => 'checkbox', ], [ 'name' => '分类去Category优化', 'desc' => '该功能会给外链自动添加nofollow,默认开启', - 'id' => 'gdk_no_category', + 'id' => 'gdk_no_category', 'type' => 'checkbox', ], [ - 'name' => '文章自动内链', - 'desc' => '启用
该功能会将文章中与标签匹配的文字自动添加标签链接,如果是纯文字的内容建议打开,注意该功能和一些短代码等功能有冲突', - 'id' => 'gdk_tag_link', - 'type' => 'checkbox', + 'name' => '文章自动内链', + 'desc' => '启用
该功能会将文章中与标签匹配的文字自动添加标签链接,如果是纯文字的内容建议打开,注意该功能和一些短代码等功能有冲突', + 'id' => 'gdk_tag_link', + 'type' => 'checkbox', ], [ 'name' => '关键词链接次数', 'desc' => '文章中最多链接的次数,默认是5', - 'id' => 'gdk_tag_num', + 'id' => 'gdk_tag_num', 'type' => 'number', - 'std' => 5, + 'std' => 5, ], [ - 'name' => 'Robots.txt 优化', - 'desc' => '启用
该功能会自动生成一个虚拟Robots.txt文件,和真实文件效果一样的,默认开启', - 'id' => 'gdk_robots', - 'type' => 'checkbox', + 'name' => 'Robots.txt 优化', + 'desc' => '启用
该功能会自动生成一个虚拟Robots.txt文件,和真实文件效果一样的,默认开启', + 'id' => 'gdk_robots', + 'type' => 'checkbox', ], [ - 'name' => '禁止蜘蛛爬取作者页面', - 'desc' => '启用
该功能会屏蔽蜘蛛访问作者页面,如果是单作者网站没必要展示作者页,根据自己网站实际情况选择是否开启,建议启用', - 'id' => 'gdk_no_author_page', - 'type' => 'checkbox', + 'name' => '禁止蜘蛛爬取作者页面', + 'desc' => '启用
该功能会屏蔽蜘蛛访问作者页面,如果是单作者网站没必要展示作者页,根据自己网站实际情况选择是否开启,建议启用', + 'id' => 'gdk_no_author_page', + 'type' => 'checkbox', ], [ - 'name' => '网站地图 sitemap', - 'desc' => '启用
该功能会自动生成网站地图[xml版和html版],链接:域名/sitemap.xml,域名/sitemap.html,开启后建议更新固定链接一次,建议启用开启', - 'id' => 'gdk_sitemap_xml', - 'type' => 'checkbox', + 'name' => '网站地图 sitemap', + 'desc' => '启用
该功能会自动生成网站地图[xml版和html版],链接:域名/sitemap.xml,域名/sitemap.html,开启后建议更新固定链接一次,建议启用开启', + 'id' => 'gdk_sitemap_xml', + 'type' => 'checkbox', ], [ - 'name' => '文章图片自动添加alt以及title', - 'desc' => '该功能会自动给文章中图片添加alt和title,并且是按照文章标题进行命名,默认开启', - 'id' => 'gdk_seo_img', - 'type' => 'checkbox', + 'name' => '文章图片自动添加alt以及title', + 'desc' => '该功能会自动给文章中图片添加alt和title,并且是按照文章标题进行命名,默认开启', + 'id' => 'gdk_seo_img', + 'type' => 'checkbox', ], [ 'name' => '外链GO跳转', 'desc' => '启用
启用后,文章外链会转化为/go?url=的类型', - 'id' => 'gdk_link_go', + 'id' => 'gdk_link_go', 'type' => 'checkbox', ], [ - 'name' => '百度自动&主动推送', - 'desc' => '启用
启用后可以采用自动推送和主动推送给百度', - 'id' => 'gdk_baidu_push', - 'type' => 'checkbox', + 'name' => '百度自动&主动推送', + 'desc' => '启用
启用后可以采用自动推送和主动推送给百度', + 'id' => 'gdk_baidu_push', + 'type' => 'checkbox', ], [ 'name' => '主动推送接口token', 'desc' => '在百度站长平台获取主动推送token,比如:http://data.zz.baidu.com/urls?site=xxoo&token=一组字符, 需要填写的是红色部分,主动推送接口地址', - 'id' => 'gdk_baidu_token', + 'id' => 'gdk_baidu_token', 'type' => 'text', ], ], - '安全' => [ + '安全' => [ [ - 'name' => '屏蔽各种不正常的请求', - 'desc' => '该功能会将各种不正常的请求比如破解,注入类的屏蔽掉,默认开启', - 'id' => 'gdk_block_requst', - 'type' => 'select', + 'name' => '屏蔽各种不正常的请求', + 'desc' => '该功能会将各种不正常的请求比如破解,注入类的屏蔽掉,默认开启', + 'id' => 'gdk_block_requst', + 'type' => 'select', 'options' => [ '0' => '禁用', '1' => '启用', ], - 'std' => '1', + 'std' => '1', ], [ 'name' => '网站维护模式', 'desc' => '启用
启用后,未登录用户将看到一个简陋的维护页面', - 'id' => 'gdk_maintenance_mode', + 'id' => 'gdk_maintenance_mode', 'type' => 'checkbox', ], [ 'name' => '禁用REST API功能', 'desc' => '禁用
启用后,REST API功能将关闭,如果没不使用该功能的话,建议关闭', - 'id' => 'gdk_disable_restapi', + 'id' => 'gdk_disable_restapi', 'type' => 'checkbox', ], [ 'name' => '保护用户暴露用户名', 'desc' => '开启
启用后,将隐藏掉用户的登录名,起到保护作用', - 'id' => 'gdk_hide_user_name', + 'id' => 'gdk_hide_user_name', 'type' => 'checkbox', ], [ 'title' => '登陆安全防御', - 'type' => 'title', + 'type' => 'title', ], [ - 'name' => '登陆安全保护', - 'desc' => '该功能会将连续多次登陆错误的用户暂时锁定,待解锁后方可重新登陆,默认开启', - 'id' => 'gdk_lock_login', - 'type' => 'select', + 'name' => '登陆安全保护', + 'desc' => '该功能会将连续多次登陆错误的用户暂时锁定,待解锁后方可重新登陆,默认开启', + 'id' => 'gdk_lock_login', + 'type' => 'select', 'options' => [ '1' => '启用', '0' => '禁用', ], - 'std' => '1', + 'std' => '1', ], [ 'name' => '登录失败最大次数', 'desc' => '默认:5', - 'id' => 'gdk_failed_login_limit', + 'id' => 'gdk_failed_login_limit', 'type' => 'number', - 'std' => 5, + 'std' => 5, ], [ 'name' => '登录失败锁定时间', 'desc' => '单位秒,默认:60', - 'id' => 'gdk_lockout_duration', + 'id' => 'gdk_lockout_duration', 'type' => 'number', - 'std' => 60, + 'std' => 60, ], [ 'name' => '登录失败邮件通知', 'desc' => '启用
开启后,将所有登陆失败信息发邮件通知管理员,预计会收到很多邮件,不建议启用', - 'id' => 'gdk_login_email', + 'id' => 'gdk_login_email', 'type' => 'checkbox', ], [ 'name' => '登陆数学验证', 'desc' => '启用
开启后,将会登陆页面增加数学验证码', - 'id' => 'gdk_login_verify', + 'id' => 'gdk_login_verify', 'type' => 'checkbox', ], [ 'title' => '垃圾评论屏蔽', - 'type' => 'title', + 'type' => 'title', ], [ - 'name' => '垃圾评论拦截', - 'desc' => '该功能会默认屏蔽垃圾评论,支持纯外语拦截,日语拦截[外贸站慎用],关键词黑名单拦截,请务必选择对应主题的评论方式,关键词黑名单如图设置点击查看如图设置', - 'id' => 'gdk_fuck_spam', - 'type' => 'select', + 'name' => '垃圾评论拦截', + 'desc' => '该功能会默认屏蔽垃圾评论,支持纯外语拦截,日语拦截[外贸站慎用],关键词黑名单拦截,请务必选择对应主题的评论方式,关键词黑名单如图设置点击查看如图设置', + 'id' => 'gdk_fuck_spam', + 'type' => 'select', 'options' => [ '0' => '禁用', '1' => '启用(推荐)', ], - 'std' => '1', + 'std' => '1', ], ], - '高级' => [ + '高级' => [ [ - 'name' => '图片懒加载', - 'desc' => '启用
该功能会降低因为图片而导致的打开速度慢问题,建议开启', - 'id' => 'gdk_lazyload', - 'type' => 'checkbox', + 'name' => '图片懒加载', + 'desc' => '启用
该功能会降低因为图片而导致的打开速度慢问题,建议开启', + 'id' => 'gdk_lazyload', + 'type' => 'checkbox', ], [ 'name' => 'HTML代码压缩', 'desc' => '启用
开启后,将压缩网页HTML代码,提高网页加载速度', - 'id' => 'gdk_compress', + 'id' => 'gdk_compress', 'type' => 'checkbox', ], [ 'name' => '侧边栏缓存', 'desc' => '启用
开启后,将会自动缓存小工具,如果想禁止缓存某个小工具,可以去小工具页面排除', - 'id' => 'gdk_sidebar_cache', + 'id' => 'gdk_sidebar_cache', 'type' => 'checkbox', ], [ 'name' => '链接新窗口打开', 'desc' => '启用
启用后,所有文章链接将在新标签页打开', - 'id' => 'gdk_target_blank', + 'id' => 'gdk_target_blank', 'type' => 'checkbox', ], [ 'title' => '统一支付设置', - 'type' => 'title', + 'type' => 'title', ], [ - 'name' => '网站Psyjs支付功能', - 'desc' => '启用
网站支付功能需要HTTPS支持,需要开通Payjs使用,点击注册Payjs', - 'id' => 'gdk_payjs', - 'type' => 'checkbox', + 'name' => '网站Psyjs支付功能', + 'desc' => '启用
网站支付功能需要HTTPS支持,需要开通Payjs使用,点击注册Payjs', + 'id' => 'gdk_payjs', + 'type' => 'checkbox', ], [ 'name' => '支付宝支付通道', 'desc' => '启用
开启后,将增加支付宝支付方式,支付宝通道需要到payjs申请开通,如果开通的话,建议使用支付宝,因为费率便宜', - 'id' => 'gdk_payjs_alipay', + 'id' => 'gdk_payjs_alipay', 'type' => 'checkbox', ], [ 'name' => '金币和RMB兑换关系', 'desc' => '请输入兑换关系,默认1RMB=10金币,请慎重选择,一旦设置好后面不能修改的,本选项仅对会员金币支付生效,游客免登陆支持不受影响', - 'id' => 'gdk_rate', + 'id' => 'gdk_rate', 'type' => 'number', - 'std' => 10, + 'std' => 10, ], [ 'name' => 'PayJs商户号', 'desc' => '', - 'id' => 'gdk_payjs_id', + 'id' => 'gdk_payjs_id', 'type' => 'text', - 'std' => 2333333333, + 'std' => 2333333333, ], [ 'name' => 'PayJs密钥', 'desc' => '', - 'id' => 'gdk_payjs_key', + 'id' => 'gdk_payjs_key', 'type' => 'text', - 'std' => 444444444, + 'std' => 444444444, ], [ 'title' => 'CDN镜像加速', - 'type' => 'title', + 'type' => 'title', ], [ - 'name' => 'CDN镜像加速', - 'desc' => '开启
本功能可以将本站静态资源同步到远程CDN服务器,减轻本站的流量压力,提高网站整体速度,国内主流CDN服务商[七牛,又拍,阿里OSS,腾讯COS,华为BOS等等]均支持,默认关闭,配置好服务器端后开启', - 'id' => 'gdk_cdn', - 'type' => 'checkbox', + 'name' => 'CDN镜像加速', + 'desc' => '开启
本功能可以将本站静态资源同步到远程CDN服务器,减轻本站的流量压力,提高网站整体速度,国内主流CDN服务商[七牛,又拍,阿里OSS,腾讯COS,华为BOS等等]均支持,默认关闭,配置好服务器端后开启', + 'id' => 'gdk_cdn', + 'type' => 'checkbox', ], [ 'name' => 'CDN域名', 'desc' => '输入您的CDN域名,一般需要到VDN后台获取,必须带 http(s):// ,且结尾不能带/ ', - 'id' => 'gdk_cdn_host', + 'id' => 'gdk_cdn_host', 'type' => 'text', - 'std' => '', + 'std' => '', ], [ 'name' => 'CDN镜像文件格式', 'desc' => '在输入框内添加准备镜像的文件格式,比如png|jpg|jpeg|gif|ico(使用|分隔)', - 'id' => 'gdk_cdn_ext', + 'id' => 'gdk_cdn_ext', 'type' => 'text', - 'std' => 'png|jpg|jpeg|gif|ico|html|7z|zip|rar|pdf|ppt|wmv|mp4|avi|mp3|txt', + 'std' => 'png|jpg|jpeg|gif|ico|html|7z|zip|rar|pdf|ppt|wmv|mp4|avi|mp3|txt', ], [ 'name' => 'CDN镜像目录', 'desc' => '在输入框内添加准备镜像的文件夹,默认为wp-content|wp-includes(使用|分隔)', - 'id' => 'gdk_cdn_dir', + 'id' => 'gdk_cdn_dir', 'type' => 'text', - 'std' => 'wp-content|wp-includes', + 'std' => 'wp-content|wp-includes', ], [ - 'name' => '静态CDN服务商', - 'desc' => '选择使用国内CDN服务商,此项主要影响CDN缩略图,请选择对应服务商', - 'id' => 'gdk_cdn_serves', - 'type' => 'select', + 'name' => '静态CDN服务商', + 'desc' => '选择使用国内CDN服务商,此项主要影响CDN缩略图,请选择对应服务商', + 'id' => 'gdk_cdn_serves', + 'type' => 'select', 'options' => [ '1' => '七牛云', '2' => '又拍云', @@ -388,219 +387,219 @@ $gdk_options = [ '5' => '华为云OBS', '6' => '百度云BOS', ], - 'std' => '4', + 'std' => '4', ], [ 'name' => 'CDN水印', 'desc' => '启用
启用后,请在七牛,又拍,OSS等CDN中设置自定义样式,名字为:water.jpg,分隔符为!', - 'id' => 'gdk_cdn_water', + 'id' => 'gdk_cdn_water', 'type' => 'checkbox', ], [ 'title' => '微信登录设置', - 'type' => 'title', + 'type' => 'title', ], [ 'name' => '是否启用微信扫码登录', 'desc' => '启用
开启后,可以使用微信扫码,另外需要HTTPS', - 'id' => 'gdk_weauth_oauth', + 'id' => 'gdk_weauth_oauth', 'type' => 'checkbox', ], [ 'name' => '强制微信登录', 'desc' => '启用
开启后,将禁用WordPress自带的登录,所有登录地址都跳转到微信的登录,如需临时使用自带登录,可以使用这个链接:你的域名/wp-login.php?loggedout=true', - 'id' => 'gdk_weauth_force', + 'id' => 'gdk_weauth_force', 'type' => 'checkbox', ], [ 'title' => '微信推送设置', - 'type' => 'title', + 'type' => 'title', ], [ 'name' => '评论微信推送提醒', 'desc' => '启用
开启后,如果网站有新的评论,可以给管理员的微信推送提醒', - 'id' => 'gdk_workpush', + 'id' => 'gdk_workpush', 'type' => 'checkbox', ], [ 'name' => '企业微信推送应用ID', 'desc' => '请输入您的企业微信推送应用ID', - 'id' => 'gdk_workpush_id', + 'id' => 'gdk_workpush_id', 'type' => 'text', ], [ 'name' => '企业微信推送应用Secret', 'desc' => '请输入您的企业微信推送应用Secret', - 'id' => 'gdk_workpush_secret', + 'id' => 'gdk_workpush_secret', 'type' => 'text', ], [ 'name' => '企业微信企业ID', 'desc' => '请输入您的企业微信ID', - 'id' => 'gdk_work_id', + 'id' => 'gdk_work_id', 'type' => 'text', ], [ 'title' => '微信群发设置', - 'type' => 'title', + 'type' => 'title', ], [ 'name' => '微信wxPushet应用Token', 'desc' => '请输入Wxpuers应用Token,从wxpusher后台获取', - 'id' => 'gdk_wxpusher_key', + 'id' => 'gdk_wxpusher_key', 'type' => 'text', ], [ 'name' => '微信Wxpusher主题ID', 'desc' => '请输入您的Wxpusher主题ID,可以从后台获取', - 'id' => 'gdk_wxpusher_id', + 'id' => 'gdk_wxpusher_id', 'type' => 'text', ], [ 'title' => '微信公众号设置', - 'type' => 'title', + 'type' => 'title', ], [ 'name' => '微信公众号TOKEN', 'desc' => '请输入您的微信公众号TOKEN,微信公众号后台获取', - 'id' => 'gdk_wxmp_token', + 'id' => 'gdk_wxmp_token', 'type' => 'text', ], [ 'name' => '微信公众号二维码', 'desc' => '请输入您的微信订阅号/公众号二维码图片链接', - 'id' => 'gdk_mp_qr', + 'id' => 'gdk_mp_qr', 'type' => 'text', - 'std' => '', + 'std' => '', ], [ 'title' => 'HTML5 桌面推送', - 'type' => 'title', + 'type' => 'title', ], [ - 'name' => 'HTML5 桌面推送', - 'desc' => '启用
该功能开启后会在浏览器右下角进行信息推送', - 'id' => 'gdk_h5notice', - 'type' => 'checkbox', + 'name' => 'HTML5 桌面推送', + 'desc' => '启用
该功能开启后会在浏览器右下角进行信息推送', + 'id' => 'gdk_h5notice', + 'type' => 'checkbox', ], [ 'name' => 'HTML5推送标题【必选】', 'desc' => '显示在弹窗顶部', - 'id' => 'gdk_notification_title', + 'id' => 'gdk_notification_title', 'type' => 'text', - 'std' => 'Hi,你好', + 'std' => 'Hi,你好', ], [ 'name' => 'HTML5推送间隔【必选】', 'desc' => '输入数字,当自动关闭或者用户关闭之后多久再次弹窗,默认10天', - 'id' => 'gdk_notification_days', + 'id' => 'gdk_notification_days', 'type' => 'number', - 'std' => 10, + 'std' => 10, ], [ 'name' => 'HTML5推送COOKIE【必选】', 'desc' => '修改COOKIE值可以强制向访客推送新的信息,无视时间间隔,不能使用中文,默认233', - 'id' => 'gdk_notification_cookie', + 'id' => 'gdk_notification_cookie', 'type' => 'text', - 'std' => '233', + 'std' => '233', ], [ 'name' => 'HTML5推送图片【必选】', 'desc' => '填写一个正方形的图片,显示在推送信息左侧,默认为默认头像', - 'id' => 'gdk_notification_icon', + 'id' => 'gdk_notification_icon', 'type' => 'text', - 'std' => '', + 'std' => '', ], [ 'name' => 'HTML5推送链接【可选】', 'desc' => '当用户点击弹窗的时候说点击的链接,默认为极客公园', - 'id' => 'gdk_notification_link', + 'id' => 'gdk_notification_link', 'type' => 'text', - 'std' => 'https://gitcafe.net', + 'std' => 'https://gitcafe.net', ], [ 'name' => 'HTML5推送内容', 'desc' => '在这里输入推送主体内容,字数合适就行,不能太多【必选】', - 'id' => 'gdk_notification_body', + 'id' => 'gdk_notification_body', 'type' => 'textarea', - 'std' => '极客公园,一个分享有趣的安卓APP和实用的WordPress技术以及Windows使用技巧的网站', + 'std' => '极客公园,一个分享有趣的安卓APP和实用的WordPress技术以及Windows使用技巧的网站', ], [ 'title' => 'SMTP邮箱设置', - 'type' => 'title', + 'type' => 'title', ], [ - 'name' => 'SMTP邮箱发送', - 'desc' => '启用
该功能利用第三方SMTP邮箱服务发送邮件,比如评论邮件,需要配置好再开启', - 'id' => 'gdk_smtp', - 'type' => 'checkbox', + 'name' => 'SMTP邮箱发送', + 'desc' => '启用
该功能利用第三方SMTP邮箱服务发送邮件,比如评论邮件,需要配置好再开启', + 'id' => 'gdk_smtp', + 'type' => 'checkbox', ], [ 'name' => '发件人昵称', 'desc' => '请输入您的网站名称,比如:云落', - 'id' => 'gdk_smtp_username', + 'id' => 'gdk_smtp_username', 'type' => 'text', ], [ 'name' => 'SMTP服务器地址', 'desc' => '请输入您的邮箱的SMTP服务器,点击查看常用SMTP地址', - 'id' => 'gdk_smtp_host', + 'id' => 'gdk_smtp_host', 'type' => 'text', - 'std' => 'smtp.qq.com', + 'std' => 'smtp.qq.com', ], [ 'name' => 'SMTP服务器端口', 'desc' => '请输入您的smtp端口,一般QQ邮箱推荐使用465端口', - 'id' => 'gdk_smtp_port', + 'id' => 'gdk_smtp_port', 'type' => 'number', - 'std' => 465, + 'std' => 465, ], [ 'name' => '邮箱账号', 'desc' => '请输入您的邮箱地址,比如云落的sp91@qq.com', - 'id' => 'gdk_smtp_mail', + 'id' => 'gdk_smtp_mail', 'type' => 'text', ], [ 'name' => '邮箱密码', 'desc' => '请输入您的邮箱授权码,注意不同邮箱服务器的密码不一样,有的是密码,有的比如QQ邮箱就是授权码', - 'id' => 'gdk_smtp_password', + 'id' => 'gdk_smtp_password', 'type' => 'password', ], [ 'title' => '自定义代码', - 'type' => 'title', + 'type' => 'title', ], [ 'name' => '网站头部自定义代码', 'desc' => '代码将插入到head区域', - 'id' => 'gdk_custom_head_code', + 'id' => 'gdk_custom_head_code', 'type' => 'textarea', ], [ 'name' => '网站底部自定义代码', 'desc' => '代码将插入到foot区域', - 'id' => 'gdk_custom_foot_code', + 'id' => 'gdk_custom_foot_code', 'type' => 'textarea', ], [ 'name' => '文章顶部自定义内容', 'desc' => '在文章顶部插入一个内容', - 'id' => 'gdk_artical_top', + 'id' => 'gdk_artical_top', 'type' => 'textarea', ], [ 'name' => '文章底部自定义内容', 'desc' => '在文章底部插入一个内容', - 'id' => 'gdk_artical_bottom', + 'id' => 'gdk_artical_bottom', 'type' => 'textarea', ], ], ]; //载入主题配置,默认路径在主题根目录options.php -if (file_exists(get_template_directory() . '/options.php')) { - include get_template_directory() . '/options.php'; +if (file_exists(get_template_directory().'/options.php')) { + include get_template_directory().'/options.php'; } if (!empty($gdk_theme_options)) { diff --git a/framework/plugin-options.php b/framework/plugin-options.php index a258516..ec9ffe5 100644 --- a/framework/plugin-options.php +++ b/framework/plugin-options.php @@ -1,14 +1,14 @@ + global $gdk_options; ?>
-

GDK选项

-
-GDK选项 +
+

设置已保存。

'; } if (isset($_GET['reset'])) { echo '

设置已重置。

'; - } - - ?> + } ?>
-
-
+
+
- - + '; + echo '
'; foreach ($panel as $option) { $type = $option['type']; - if ($type == 'title') { + if ('title' == $type) { ?> - - - - + + + - - - + + '; } echo '
-

- ' . $option['desc'] . '

'; - } - ?> -
+

+

+ '.$option['desc'].'

'; + } ?> +
- +
+ + - -

- + + +

+

+ - - + + + + -

-

- +

+

+

+ - - -

- + +

+

+ -
- $name): ?> - - -
-

- + $name) { ?> + + + +

+

+ - - + /> + + + -
- $name): ?> - - -
-

- + $name) { ?> + + + +

+

+ - -

- + + +

+

+
'; - $index++; - } - ?> -
- - - - - - - - + ++$index; + } ?> +
+

联系方式

-
    -
  • QQ:865113728(推荐)
  • -
  • 邮箱:sp91@qq.com
  • -
  • * 和主题无关的问题恕不回复

  • -
-

意见反馈

- -
+ + + + + + + + -
+

联系方式

+
+
    +
  • QQ:865113728(推荐)
  • +
  • 邮箱:sp91@qq.com
  • +
  • +

    * 和主题无关的问题恕不回复

    +
  • +
+
+

意见反馈

+
+ +
-
-
-

- - - -

- + + +
+

+ + + +

+ -
-

- - -

-
-
-

- -

-
+
+

+ + +

+
+
+

+ +

+
')) { - exit('插件有更新,已安装版本:' . GDK_PLUGIN_VER . ' 新版本:' . $version . ' '); - } else { - exit('你的插件目前已经是最新版了!'); + exit('插件有更新,已安装版本:'.GDK_PLUGIN_VER.' 新版本:'.$version.' '); } + + exit('你的插件目前已经是最新版了!'); } add_action('wp_ajax_nopriv_get_new_version', 'gdk_ajax_get_update'); add_action('wp_ajax_get_new_version', 'gdk_ajax_get_update'); @@ -45,9 +44,9 @@ add_action('wp_ajax_get_new_version', 'gdk_ajax_get_update'); function gdk_ajax_install_update() { $url = 'http://dl.gitcafe.net/gdk.zip'; - unzip_url($url, GDK_ROOT_PATH); - exit(1); + gdk_unzip_url($url, GDK_ROOT_PATH); + exit(1); } add_action('wp_ajax_nopriv_install_new_version', 'gdk_ajax_install_update'); add_action('wp_ajax_install_new_version', 'gdk_ajax_install_update'); @@ -61,29 +60,29 @@ function gdk_pasteup_imag() if ($_FILES) { global $post; - $post_ID = $post->ID; + $post_ID = $post->ID; $wp_upload_dir = wp_upload_dir(); - $file = $_FILES['imageFile']; - $result = array('success' => false, 'message' => 'Null'); - if (array_key_exists($file['type'], array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png'))) { + $file = $_FILES['imageFile']; + $result = ['success' => false, 'message' => 'Null']; + if (array_key_exists($file['type'], ['image/gif', 'image/jpeg', 'image/pjpeg', 'image/png'])) { if ($file['error'] > 0) { $result['message'] = 'error'; } else { - $file_name = md5_file($file['tmp_name']) . str_replace('image/', '.', $file['type']); //img name - $file_url = $wp_upload_dir['url'] . '/' . $file_name; - $file_path = $wp_upload_dir['path'] . '/' . $file_name; + $file_name = md5_file($file['tmp_name']).strtr($file['type'], ['image/' => '.']); //img name + $file_url = $wp_upload_dir['url'].'/'.$file_name; + $file_path = $wp_upload_dir['path'].'/'.$file_name; if (!file_exists($file_path)) { move_uploaded_file($file['tmp_name'], $file_path); $attachment = [ - 'guid' => $wp_upload_dir['url'] . '/' . basename($file_path), + 'guid' => $wp_upload_dir['url'].'/'.basename($file_path), 'post_mime_type' => $file['type'], - 'post_title' => $file_name, - 'post_content' => '', - 'post_status' => 'inherit', + 'post_title' => $file_name, + 'post_content' => '', + 'post_status' => 'inherit', ]; $attach_id = wp_insert_attachment($attachment, $file_name, $post_ID); //这是wp内置的上传附件的函数 - require_once ABSPATH . 'wp-admin/includes/image.php'; + require_once ABSPATH.'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $file_path); wp_update_attachment_metadata($attach_id, $attach_data); } @@ -93,7 +92,8 @@ function gdk_pasteup_imag() } else { $result['message'] = '400'; } - echo (json_encode($result)); + echo json_encode($result); + exit(); } } @@ -107,9 +107,9 @@ function gdk_pass_view() exit('400'); } - $action = $_POST['action']; - $post_id = $_POST['id']; - $pass = $_POST['pass']; + $action = esc_attr($_POST['action']); + $post_id = esc_attr($_POST['id']); + $pass = esc_attr($_POST['pass']); $wxcaptcha = wx_captcha(); if (!isset($action) || !isset($post_id) || !isset($pass)) { exit('400'); @@ -117,9 +117,8 @@ function gdk_pass_view() if ($pass == $wxcaptcha) { $pass_content = get_post_meta($post_id, '_pass_content')[0]; + exit($pass_content); - } else { - exit('400'); } } add_action('wp_ajax_nopriv_gdk_pass_view', 'gdk_pass_view'); @@ -130,7 +129,7 @@ add_action('wp_ajax_gdk_pass_view', 'gdk_pass_view'); //在线积分充值开始 function pay_points() { - if (!isset($_POST['action']) || $_POST['action'] !== 'pay_points') { + if (!isset($_POST['action']) || 'pay_points' !== $_POST['action']) { exit('400'); } @@ -154,12 +153,12 @@ function check_pay_points() if (!isset($_POST['id']) || !isset($_POST['orderid'])) { exit('400'); } //无脑输出400错误 - if ($_POST['action'] == 'check_pay_points') { - if (gdk_check($_POST['orderid'], $_POST['id'])) { + if ('check_pay_points' == $_POST['action']) { + if (gdk_order_check($_POST['orderid'], $_POST['id'])) { exit('200'); - } else { - exit('400'); } + + exit('400'); } } add_action('wp_ajax_check_pay_points', 'check_pay_points'); @@ -170,16 +169,16 @@ add_action('wp_ajax_nopriv_check_pay_points', 'check_pay_points'); //游客付费可见开始 function pay_view() { - if (!isset($_POST['action']) || $_POST['action'] !== 'pay_view') { + if (!isset($_POST['action']) || 'pay_view' !== $_POST['action']) { exit('400'); } if (!isset($_POST['money']) || !isset($_POST['way'])) { exit('400'); } -//无脑输出400错误 + //无脑输出400错误 if (isset($_POST['id'])) { - payjs_action('付费查看:' . get_the_title($_POST['id']), 'PP' . $_POST['id'], $_POST['money']); //标题,文章id + payjs_action('付费查看:'.get_the_title($_POST['id']), 'PP'.$_POST['id'], $_POST['money']); //标题,文章id } } add_action('wp_ajax_pay_view', 'pay_view'); @@ -188,23 +187,23 @@ add_action('wp_ajax_nopriv_pay_view', 'pay_view'); //添加提取码 function add_code() { - $id = $_POST['id']; + $id = $_POST['id']; $code = $_POST['code']; if (empty($id) || empty($code)) { exit('400'); } - if ($_POST['action'] == 'add_code') { - $code = trim($code); //清理一下 + if ('add_code' == $_POST['action']) { + $code = trim($code); //清理一下 $pay_log = get_post_meta($id, 'pay_log', true); //获取旧的购买记录数据 - add_post_meta($id, 'pay_log', $code, true) or update_post_meta($id, 'pay_log', $pay_log . ',' . $code); //没有新建,有就更新 + add_post_meta($id, 'pay_log', $code, true) or update_post_meta($id, 'pay_log', $pay_log.','.$code); //没有新建,有就更新 $pay_log = get_post_meta($id, 'pay_log', true); //获取新的购买记录数据 - $pay_arr = explode(",", $pay_log); + $pay_arr = explode(',', $pay_log); if (array_key_exists($code, $pay_arr)) { exit('200'); //OK - } else { - exit('400'); //NO } + + exit('400'); //NO } } add_action('wp_ajax_add_code', 'add_code'); @@ -214,9 +213,9 @@ add_action('wp_ajax_nopriv_add_code', 'add_code'); function check_code() { $check_code_nonce = $_POST['check_code']; - $code = $_POST['code']; - $action = $_POST['action']; - $id = $_POST['id']; + $code = $_POST['code']; + $action = $_POST['action']; + $id = $_POST['id']; if (!isset($check_code_nonce) || !wp_verify_nonce($check_code_nonce, 'check_code')) { exit('400'); } @@ -224,15 +223,15 @@ function check_code() if (empty($code) || !isset($action) || !isset($id)) { exit('400'); } //无脑输出400错误 - if ($action == 'check_code') { - $code = trim($code); //清理一下 + if ('check_code' == $action) { + $code = trim($code); //清理一下 $pay_log = get_post_meta($id, 'pay_log', true); //购买记录数据 - $pay_arr = explode(",", $pay_log); + $pay_arr = explode(',', $pay_log); if (array_key_exists($code, $pay_arr)) { exit('200'); - } else { - exit('400'); } + + exit('400'); } } add_action('wp_ajax_check_code', 'check_code'); @@ -241,11 +240,12 @@ add_action('wp_ajax_nopriv_check_code', 'check_code'); //获取加密内容 function get_content() { - if (!isset($_POST['action']) || $_POST['action'] !== 'get_content') { + if (!isset($_POST['action']) || 'get_content' !== $_POST['action']) { exit('400'); } //无脑输出400错误 if (isset($_POST['id'])) { $pay_content = get_post_meta($_POST['id'], '_pay_content', true); + exit($pay_content); } } @@ -262,30 +262,31 @@ function check_pay_view() if (!isset($_POST['id']) || !isset($_POST['orderid'])) { exit('400'); } //无脑输出400错误 - if ($_POST['action'] == 'check_pay_view') { - $sid = get_transient('PP' . $_POST['id']); + if ('check_pay_view' == $_POST['action']) { + $sid = get_transient('PP'.$_POST['id']); if (in_string($sid, 'E20') && $_POST['orderid'] == $sid) { exit('200'); //OK - } else { - exit('400'); //no } + + exit('400'); //no } } add_action('wp_ajax_check_pay_view', 'check_pay_view'); add_action('wp_ajax_nopriv_check_pay_view', 'check_pay_view'); -/**END */ +// END //开始微信登陆 //ajax生成登录二维码 function gdk_weauth_qr_gen() { - if (isset($_POST['action']) && $_POST['action'] == 'gdk_weauth_qr_gen') { + if (isset($_POST['action']) && 'gdk_weauth_qr_gen' == $_POST['action']) { $rest = implode('|', gdk_weauth_qr()); + exit($rest); - } else { - exit('400'); } + + exit('400'); } add_action('wp_ajax_gdk_weauth_qr_gen', 'gdk_weauth_qr_gen'); add_action('wp_ajax_nopriv_gdk_weauth_qr_gen', 'gdk_weauth_qr_gen'); @@ -297,12 +298,12 @@ function gdk_weauth_check() exit('400'); } - if (!in_string($_POST['key'], '@') || $_POST['action'] !== 'gdk_weauth_check') { + if (!in_string($_POST['key'], '@') || 'gdk_weauth_check' !== $_POST['action']) { exit('400'); } - $sk = substr(trim($_POST['key']), -12); //sk - $user_info = get_transient($sk . '-info'); //user_info + $sk = substr(trim($_POST['key']), -12); //sk + $user_info = get_transient($sk.'-info'); //user_info if (!empty($user_info)) { exit($user_info); //user_info } @@ -313,21 +314,22 @@ add_action('wp_ajax_nopriv_gdk_weauth_check', 'gdk_weauth_check'); //开始自动登陆 function gdk_auto_login() { - if (!isset($_POST['data']) || $_POST['action'] !== 'gdk_auto_login') { + if (!isset($_POST['data']) || 'gdk_auto_login' !== $_POST['action']) { exit('400'); } - $mail = $_POST['email'] ?? ''; + $mail = $_POST['email'] ?? ''; $userdata = gdk_str2arr($_POST['data'], '|'); - $user_id = create_user_id($userdata); + $user_id = create_user_id($userdata); if (is_numeric($user_id) && $user_id) { $user = get_user_by('id', $user_id); wp_set_current_user($user_id, $user->user_login); wp_set_auth_cookie($user_id, true); do_action('wp_login', $user->user_login); if ($mail && !empty($mail) && is_email($mail)) { - wp_update_user(array('ID' => $user_id, 'user_email' => $mail)); //绑定邮箱 + wp_update_user(['ID' => $user_id, 'user_email' => $mail]); //绑定邮箱 } + exit('200'); } } @@ -338,7 +340,7 @@ add_action('wp_ajax_nopriv_gdk_auto_login', 'gdk_auto_login'); function gdk_bind_email_check() { $mail = isset($_POST['email']) ? $_POST['email'] : false; - if ($mail && $_POST['action'] == 'bind_email_check') { + if ($mail && 'bind_email_check' == $_POST['action']) { $user_id = email_exists($email); if ($user_id) { exit('200'); @@ -351,21 +353,22 @@ add_action('wp_ajax_nopriv_bind_email_check', 'gdk_bind_email_check'); //积分支付 function point_buy() { - if (isset($_POST['point']) && isset($_POST['userid']) && isset($_POST['id']) && $_POST['action'] == 'gdk_pay_buy') { + if (isset($_POST['point'], $_POST['userid'], $_POST['id']) && 'gdk_pay_buy' == $_POST['action']) { $all = GDK_Points::get_user_total_points($_POST['userid'], 'accepted'); - if( $all < $_POST['point']){ + if ($all < $_POST['point']) { exit; - }else{ - GDK_Points::set_points(-$_POST['point'], + } + GDK_Points::set_points( + -$_POST['point'], $_POST['userid'], - array( + [ 'description' => $_POST['id'], - 'status' => 'accepted', - ) + 'status' => 'accepted', + ] ); //扣除金币 $pay_content = get_post_meta($_POST['id'], '_point_content', true); + exit($pay_content); - } } } add_action('wp_ajax_gdk_pay_buy', 'point_buy'); @@ -374,29 +377,28 @@ add_action('wp_ajax_nopriv_gdk_pay_buy', 'point_buy'); //ajax 表单 function msg_form() { - if (empty($_POST['mail']) || empty($_POST['msg_content']) || $_POST['action'] !== 'msg_submit' || !wp_verify_nonce($_POST['msg_nonce'], 'msg_nonce')) { + if (empty($_POST['mail']) || empty($_POST['msg_content']) || 'msg_submit' !== $_POST['action'] || !wp_verify_nonce($_POST['msg_nonce'], 'msg_nonce')) { exit('400'); } if (!is_email($_POST['mail'])) { exit('403'); } - - $msg = array( - 'post_title' => '【来自' . $_POST['mail'] . '留言】', - 'post_author' => 1, + $msg = [ + 'post_title' => '【来自'.$_POST['mail'].'留言】', + 'post_author' => 1, 'post_content' => $_POST['msg_content'].' - 回复邮件:' . $_POST['mail'], - ); + 回复邮件:'.$_POST['mail'], + ]; - wp_mail(get_bloginfo('admin_email'), $msg['post_title'], $msg['post_content']); + wp_mail(get_bloginfo('admin_email'), $msg['post_title'], $msg['post_content']); + + if ('1' !== $_POST['only_mail']) { + wp_insert_post($msg); + } - if($_POST['only_mail'] !== '1'){ - wp_insert_post($msg); - } exit('200'); - } add_action('wp_ajax_msg_submit', 'msg_form'); add_action('wp_ajax_nopriv_msg_submit', 'msg_form'); diff --git a/functions/Common.php b/functions/Common.php index 41c948a..5a64496 100644 --- a/functions/Common.php +++ b/functions/Common.php @@ -1,29 +1,49 @@ console.info('log:".$log."');"; } + +function gdk_rand_color() +{ + $arr = [ + 'red', + 'green', + 'blue', + 'yellow', + ]; + $rndKey = array_rand($arr); + echo $arr[$rndKey]; +} + //获取友情链接ID,默认是第一个创建的分类 -function gdk_link_id() { - $arr = get_terms( 'link_category', 'orderby=id&hide_empty=0' ); - return $arr[0]->term_id; +function gdk_link_id() +{ + $arr = get_terms('link_category', 'orderby=id&hide_empty=0'); + + return $arr[0]->term_id; } /** * 获取摘要 + * + * @param mixed $length + * @param null|mixed $post + * @param mixed $echo + * @param mixed $more */ function gdk_print_excerpt($length, $post = null, $echo = true, $more = '...') { - global $post; $text = $post->post_excerpt; if ('' == $text) { $text = get_the_content(); //获取文字 $text = apply_filters('the_content', $text); - $text = str_replace(']]>', ']]>', $text); + $text = strtr($text, [']]>' => ']]>']); } $text = strip_shortcodes($text); @@ -31,10 +51,10 @@ function gdk_print_excerpt($length, $post = null, $echo = true, $more = '...') $excerpt = wp_trim_words($text, $length, $more); - if ($excerpt) { + if (isset($excerpt)) { $result = apply_filters('the_excerpt', $excerpt); } - if ($echo == true) { + if (true == $echo) { echo $result; } else { return $result; @@ -44,8 +64,9 @@ function gdk_print_excerpt($length, $post = null, $echo = true, $more = '...') function nc_comment_add_at($comment_text, $comment = '') { if (!empty($comment) && $comment->comment_parent > 0) { - $comment_text = '@' . get_comment_author($comment->comment_parent) . ' ' . $comment_text; + $comment_text = '@'.get_comment_author($comment->comment_parent).' '.$comment_text; } + return $comment_text; } @@ -55,7 +76,7 @@ function gdk_record_visitors() global $post; $post_ID = $post->ID; if ($post_ID) { - $post_views = (int)get_post_meta($post_ID, 'views', true); + $post_views = (int) get_post_meta($post_ID, 'views', true); if (!update_post_meta($post_ID, 'views', ($post_views + 1))) { add_post_meta($post_ID, 'views', 1, true); } @@ -67,7 +88,7 @@ function nc_post_views($before = '(点击 ', $after = ' 次)', $echo = 1) { global $post; $post_ID = $post->ID; - $views = (int)get_post_meta($post_ID, 'views', true); + $views = (int) get_post_meta($post_ID, 'views', true); if ($echo) { echo $before, number_format($views), $after; } else { @@ -78,18 +99,20 @@ function nc_post_views($before = '(点击 ', $after = ' 次)', $echo = 1) /** * Load a component into a template while supplying data. * - * @param string $slug The slug name for the generic template. - * @param array $params An associated array of data that will be extracted into the templates scope - * @param bool $output Whether to output component or return as string. + * @param string $slug the slug name for the generic template + * @param array $params An associated array of data that will be extracted into the templates scope + * @param bool $output whether to output component or return as string + * * @return string */ -function nc_get_template_part_with_vars($slug, array $params = array(), $output = true) +function nc_get_template_part_with_vars($slug, array $params = [], $output = true) { if (!$output) { ob_start(); } $template_file = locate_template("{$slug}.php", false, false); - extract(array('template_params' => $params), EXTR_SKIP); + extract(['template_params' => $params], EXTR_SKIP); + require $template_file; if (!$output) { return ob_get_clean(); @@ -100,7 +123,7 @@ function nc_ajax_load_comments() { global $wp_query; - $type = sanitize_text_field($_POST['type']); + $type = sanitize_text_field($_POST['type']); $paged = sanitize_text_field($_POST['paged']); $q = sanitize_text_field($_POST['query']); @@ -109,12 +132,12 @@ function nc_ajax_load_comments() wp_die(); } - if ($type === 'page') { - $wp_query = new WP_Query(array('page_id' => $q, 'cpage' => $paged)); + if ('page' === $type) { + $wp_query = new WP_Query(['page_id' => $q, 'cpage' => $paged]); } - if ($type === 'post') { - $wp_query = new WP_Query(array('p' => $q, 'cpage' => $paged)); + if ('post' === $type) { + $wp_query = new WP_Query(['p' => $q, 'cpage' => $paged]); } if (have_posts()) { @@ -134,26 +157,27 @@ function nc_ajax_load_comments() function nc_get_next_page_number() { $page_number = get_comment_pages_count(); - if (get_option('default_comments_page') == 'newest') { + if ('newest' == get_option('default_comments_page')) { $next_page = $page_number - 1; } else { $next_page = 2; } + return $next_page; } function nc_like_init($key, $direct = false) { // $direct === true 时不计 cookie - $id = $_POST["id"]; - $action = $_POST["do_action"]; + $id = $_POST['id']; + $action = $_POST['do_action']; $lh_raters = get_post_meta($id, $key, true); - $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; + $domain = ('localhost' != $_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : false; - if ($action == 'do') { + if ('do' == $action) { $expire = time() + 99999999; - if (!isset($_COOKIE[$key . '_' . $id]) || $direct) { - gdk_set_cookie($key . '_' . $id, $id, $expire); + if (!isset($_COOKIE[$key.'_'.$id]) || $direct) { + gdk_set_cookie($key.'_'.$id, $id, $expire); if (!$lh_raters || !is_numeric($lh_raters)) { update_post_meta($id, $key, 1); } else { @@ -161,37 +185,42 @@ function nc_like_init($key, $direct = false) } } } - if ($action == 'undo' && !$direct) { + if ('undo' == $action && !$direct) { $expire = time() - 1; - if (isset($_COOKIE[$key . '_' . $id])) { - gdk_set_cookie($key . '_' . $id, $id, $expire); + if (isset($_COOKIE[$key.'_'.$id])) { + gdk_set_cookie($key.'_'.$id, $id, $expire); update_post_meta($id, $key, ($lh_raters - 1)); } } echo get_post_meta($id, $key, true); - die; + + exit; } function nc_timeago($ptime = null, $post = null) { - if ($post === null) { + if (null === $post) { global $post; } $ptime = $ptime ?: get_post_time('G', false, $post); - return human_time_diff($ptime, current_time('timestamp')) . '前'; + + return human_time_diff($ptime, current_time('timestamp')).'前'; } function nc_get_translated_role_name($user_id) { - $data = get_userdata($user_id); + $data = get_userdata($user_id); $roles = $data->roles; if (array_key_exists('administrator', $roles)) { return __('Administrator', 'jimu'); - } elseif (array_key_exists('editor', $roles)) { + } + if (array_key_exists('editor', $roles)) { return __('Certified Editor', 'jimu'); - } elseif (array_key_exists('author', $roles)) { + } + if (array_key_exists('author', $roles)) { return __('Special Author', 'jimu'); - } elseif (array_key_exists('subscriber', $roles)) { + } + if (array_key_exists('subscriber', $roles)) { return __('Subscriber', 'jimu'); } @@ -201,6 +230,7 @@ function nc_get_translated_role_name($user_id) function nc_get_meta($key, $single = true) { global $post; + return get_post_meta($post->ID, $key, $single); } @@ -215,12 +245,13 @@ function gdk_is_mobile() $ua = $_SERVER['HTTP_USER_AGENT']; if (empty($ua)) { return false; - } elseif ((in_string($ua, 'Mobile') && strpos($ua, 'iPad') === false) // many mobile devices (all iPh, etc.) + } + if ((in_string($ua, 'Mobile') && false === strpos($ua, 'iPad')) // many mobile devices (all iPh, etc.) || in_string($ua, 'Android') || in_string($ua, 'NetType/') || in_string($ua, 'Kindle') || in_string($ua, 'MQQBrowser') || in_string($ua, 'Opera Mini') || in_string($ua, 'Opera Mobi') || in_string($ua, 'HUAWEI') || in_string($ua, 'TBS/') || in_string($ua, 'Mi') || in_string($ua, 'iPhone')) { return true; - } else { - return false; } + + return false; } //判断是否是登陆页面 @@ -232,11 +263,11 @@ function is_login() //判断字符串内是否有指定字符串 function in_string($text, $find) { - if (strpos($text, $find) !== false) { + if (false !== strpos($text, $find)) { return true; - } else { - return false; } + + return false; } //判断是否是微信 @@ -244,17 +275,17 @@ function gdk_is_weixin() { if (in_string($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) { return true; - } else { - return false; } + + return false; } //获取浏览器信息 -function getBrowser() +function gdk_getBrowser() { - $u_agent = $_SERVER['HTTP_USER_AGENT']; - $bname = $u_agent; + $u_agent = $_SERVER['HTTP_USER_AGENT']; + $bname = $u_agent; $platform = ''; - $version = ''; + $version = ''; //First get the platform? if (preg_match('/linux/i', $u_agent)) { $platform = 'Linux'; @@ -266,26 +297,26 @@ function getBrowser() // Next get the name of the useragent yes seperately and for good reason if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) { $bname = 'Internet Explorer'; - $ub = "MSIE"; + $ub = 'MSIE'; } elseif (preg_match('/Firefox/i', $u_agent)) { $bname = 'Mozilla Firefox'; - $ub = "Firefox"; + $ub = 'Firefox'; } elseif (preg_match('/Chrome/i', $u_agent)) { $bname = 'Google Chrome'; - $ub = "Chrome"; + $ub = 'Chrome'; } elseif (preg_match('/Safari/i', $u_agent)) { $bname = 'Apple Safari'; - $ub = "Safari"; + $ub = 'Safari'; } elseif (preg_match('/Opera/i', $u_agent)) { $bname = 'Opera'; - $ub = "Opera"; + $ub = 'Opera'; } elseif (preg_match('/Netscape/i', $u_agent)) { $bname = 'Netscape'; - $ub = "Netscape"; + $ub = 'Netscape'; } // finally get the correct version number - $known = array('Version', $ub, 'other'); - $pattern = '#( ?' . join('|', $known) . + $known = ['Version', $ub, 'other']; + $pattern = '#( ?'.join('|', $known). ')[/ ]+( ?[0-9.|a-zA-Z.]*)#'; if (!preg_match_all($pattern, $u_agent, $matches)) { // we have no matching number just continue @@ -293,10 +324,10 @@ function getBrowser() if (isset($matches['browser']) && is_array($matches['browser'])) { // see how many we have $i = count($matches['browser']); - if ($i != 1) { + if (1 != $i) { //we will have two since we are not using 'other' argument yet //see if version is before or after the name - if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) { + if (strripos($u_agent, 'Version') < strripos($u_agent, $ub)) { $version = $matches['version'][0]; } else { $version = $matches['version'][1]; @@ -305,51 +336,58 @@ function getBrowser() $version = $matches['version'][0]; } } else { - $version = "?"; + $version = '?'; } - return array( + + return [ 'userAgent' => $u_agent, - 'name' => $bname, - 'version' => $version, - 'platform' => $platform, - 'pattern' => $pattern, - ); + 'name' => $bname, + 'version' => $version, + 'platform' => $platform, + 'pattern' => $pattern, + ]; } //获取IP地址 function gdk_get_ip() { - $proxy_headers = ["CLIENT_IP", "FORWARDED", "FORWARDED_FOR", "FORWARDED_FOR_IP", "HTTP_CLIENT_IP", "HTTP_FORWARDED", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED_FOR_IP", "HTTP_PC_REMOTE_ADDR", "HTTP_PROXY_CONNECTION", "HTTP_VIA", "HTTP_X_FORWARDED", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED_FOR_IP", "HTTP_X_IMFORWARDS", "HTTP_XROXY_CONNECTION", "VIA", "X_FORWARDED", "X_FORWARDED_FOR"]; + $proxy_headers = ['CLIENT_IP', 'FORWARDED', 'FORWARDED_FOR', 'FORWARDED_FOR_IP', 'HTTP_CLIENT_IP', 'HTTP_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED_FOR_IP', 'HTTP_PC_REMOTE_ADDR', 'HTTP_PROXY_CONNECTION', 'HTTP_VIA', 'HTTP_X_FORWARDED', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR_IP', 'HTTP_X_IMFORWARDS', 'HTTP_XROXY_CONNECTION', 'VIA', 'X_FORWARDED', 'X_FORWARDED_FOR']; foreach ($proxy_headers as $proxy_header) { if (isset($_SERVER[$proxy_header])) { if (gdk_validate_ip($_SERVER[$proxy_header])) { return $_SERVER[$proxy_header]; - } elseif (stristr(",", $_SERVER[$proxy_header]) !== false) { - $proxy_header_temp = trim(array_shift(explode(",", $_SERVER[$proxy_header]))); - if (($pos_temp = in_string($proxy_header_temp, ":"))) {$proxy_header_temp = substr($proxy_header_temp, 0, $pos_temp);} - if (gdk_validate_ip($proxy_header_temp)) {return $proxy_header_temp;} + } + if (false !== stristr(',', $_SERVER[$proxy_header])) { + $proxy_header_temp = trim(array_shift(explode(',', $_SERVER[$proxy_header]))); + if (($pos_temp = in_string($proxy_header_temp, ':'))) { + $proxy_header_temp = substr($proxy_header_temp, 0, $pos_temp); + } + if (gdk_validate_ip($proxy_header_temp)) { + return $proxy_header_temp; + } } } } - if (gdk_validate_ip($_SERVER["REMOTE_ADDR"])) { - return $_SERVER["REMOTE_ADDR"]; + if (gdk_validate_ip($_SERVER['REMOTE_ADDR'])) { + return $_SERVER['REMOTE_ADDR']; } - } /** * Ensures an ip address is both a valid IP and does not fall within * a private network range. + * + * @param mixed $ip */ function gdk_validate_ip($ip) { - if (strtolower($ip) === 'unknown') { + if ('unknown' === strtolower($ip)) { return false; } // generate ipv4 network address $ip = ip2long($ip); // if the ip is set and not equivalent to 255.255.255.255 - if ($ip !== false && $ip !== -1) { + if (false !== $ip && -1 !== $ip) { // make sure to get unsigned long representation of ip // due to discrepancies between 32 and 64 bit OSes and // signed numbers ( ints default to signed in PHP) @@ -386,8 +424,8 @@ function gdk_validate_ip($ip) if ($ip >= 4294967040) { return false; } - } + return true; } @@ -396,6 +434,7 @@ function gdk_die($ErrMsg) { header('HTTP/1.1 405 Method Not Allowed'); header('Content-Type: text/plain;charset=UTF-8'); + exit($ErrMsg); } @@ -410,75 +449,75 @@ function gdk_breadcrumbs($delimiter = '»', $hometitle = 'Home') echo '
'; global $post; $homeLink = home_url(); - echo ' ' . $hometitle . ' ' . $delimiter . ' '; + echo ' '.$hometitle.' '.$delimiter.' '; if (is_category()) { // 分类 存档 global $wp_query; - $cat_obj = $wp_query->get_queried_object(); - $thisCat = $cat_obj->term_id; - $thisCat = get_category($thisCat); + $cat_obj = $wp_query->get_queried_object(); + $thisCat = $cat_obj->term_id; + $thisCat = get_category($thisCat); $parentCat = get_category($thisCat->parent); - if ($thisCat->parent != 0) { - $cat_code = get_category_parents($parentCat, true, ' ' . $delimiter . ' '); + if (0 != $thisCat->parent) { + $cat_code = get_category_parents($parentCat, true, ' '.$delimiter.' '); echo $cat_code = str_replace('' . get_the_time('Y') . ' ' . $delimiter . ' '; - echo '' . get_the_time('F') . ' ' . $delimiter . ' '; - echo $before . get_the_time('d') . $after; + echo ''.get_the_time('Y').' '.$delimiter.' '; + echo ''.get_the_time('F').' '.$delimiter.' '; + echo $before.get_the_time('d').$after; } elseif (is_month()) { // 月 存档 - echo '' . get_the_time('Y') . ' ' . $delimiter . ' '; - echo $before . get_the_time('F') . $after; + echo ''.get_the_time('Y').' '.$delimiter.' '; + echo $before.get_the_time('F').$after; } elseif (is_year()) { // 年 存档 - echo $before . get_the_time('Y') . $after; + echo $before.get_the_time('Y').$after; } elseif (is_single() && !is_attachment()) { // 文章 - if (get_post_type() != 'post') { + if ('post' != get_post_type()) { // 自定义文章类型 $post_type = get_post_type_object(get_post_type()); - $slug = $post_type->rewrite; - echo '' . $post_type->labels->singular_name . ' ' . $delimiter . ' '; - echo $before . get_the_title() . $after; + $slug = $post_type->rewrite; + echo ''.$post_type->labels->singular_name.' '.$delimiter.' '; + echo $before.get_the_title().$after; } else { // 文章 post - $cat = get_the_category(); - $cat = $cat[0]; - $cat_code = get_category_parents($cat, true, ' ' . $delimiter . ' '); + $cat = get_the_category(); + $cat = $cat[0]; + $cat_code = get_category_parents($cat, true, ' '.$delimiter.' '); echo $cat_code = str_replace('labels->singular_name . $after; + echo $before.$post_type->labels->singular_name.$after; } elseif (is_attachment()) { // 附件 $parent = get_post($post->post_parent); - $cat = get_the_category($parent->ID); - $cat = $cat[0]; - echo '' . $parent->post_title . ' ' . $delimiter . ' '; - echo $before . get_the_title() . $after; + $cat = get_the_category($parent->ID); + $cat = $cat[0]; + echo ''.$parent->post_title.' '.$delimiter.' '; + echo $before.get_the_title().$after; } elseif (is_page() && !$post->post_parent) { // 页面 - echo $before . get_the_title() . $after; + echo $before.get_the_title().$after; } elseif (is_page() && $post->post_parent) { // 父级页面 - $parent_id = $post->post_parent; - $breadcrumbs = array(); + $parent_id = $post->post_parent; + $breadcrumbs = []; while ($parent_id) { - $page = get_page($parent_id); - $breadcrumbs[] = '' . get_the_title($page->ID) . ''; - $parent_id = $page->post_parent; + $page = get_page($parent_id); + $breadcrumbs[] = ''.get_the_title($page->ID).''; + $parent_id = $page->post_parent; } $breadcrumbs = array_reverse($breadcrumbs); foreach ($breadcrumbs as $crumb) { - echo $crumb . ' ' . $delimiter . ' '; + echo $crumb.' '.$delimiter.' '; } - echo $before . get_the_title() . $after; + echo $before.get_the_title().$after; } elseif (is_search()) { // 搜索结果 echo $before; @@ -500,6 +539,7 @@ function gdk_breadcrumbs($delimiter = '»', $hometitle = 'Home') // 404 页面 echo $before; _e('Not Found', 'cmp'); + echo $after; } if (get_query_var('paged')) { @@ -507,7 +547,6 @@ function gdk_breadcrumbs($delimiter = '»', $hometitle = 'Home') if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author()) { echo sprintf(__('( Page %s )', 'cmp'), get_query_var('paged')); } - } echo '
'; } @@ -525,21 +564,19 @@ function gdk_set_cookie($key, $value, $expire) $_COOKIE[$key] = $value; } -//判断是否是电话号码,是号码返回 true 不是返回false +//判断是否是电话号码,号码返回 true 不是返回false function gdk_is_mobile_number($number) { - return (bool)preg_match('/^0{0,1}(1[3,5,8][0-9]|14[5,7]|166|17[0,1,3,6,7,8]|19[8,9])[0-9]{8}$/', $number); + return (bool) preg_match('/^0{0,1}(1[3,5,8][0-9]|14[5,7]|166|17[0,1,3,6,7,8]|19[8,9])[0-9]{8}$/', $number); } //获取纯文本 function gdk_plain_text($text) { $text = wp_strip_all_tags($text); - $text = str_replace('"', '', $text); - $text = str_replace('\'', '', $text); - $text = str_replace("\r\n", ' ', $text); - $text = str_replace("\n", ' ', $text); - $text = str_replace(" ", ' ', $text); + $replace = ['"' => '', '\'' => '', "\r\n" => ' ', "\n" => ' ', ' ' => ' ']; + $text = strtr($text, $replace); + return trim($text); } @@ -550,53 +587,54 @@ function gdk_first_p($text) $text = explode("\n", trim(strip_tags($text))); $text = trim($text['0']); } + return $text; } //获取当前页面链接 function gdk_get_current_url() { - $ssl = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? true : false; - $sp = strtolower($_SERVER['SERVER_PROTOCOL']); - $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : ''); - $port = $_SERVER['SERVER_PORT']; - $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':' . $port; - $host = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME']; - return $protocol . '://' . $host . $port . $_SERVER['REQUEST_URI']; + $ssl = (!empty($_SERVER['HTTPS']) && 'on' == $_SERVER['HTTPS']) ? true : false; + $sp = strtolower($_SERVER['SERVER_PROTOCOL']); + $protocol = substr($sp, 0, strpos($sp, '/')).(($ssl) ? 's' : ''); + $port = $_SERVER['SERVER_PORT']; + $port = ((!$ssl && '80' == $port) || ($ssl && '443' == $port)) ? '' : ':'.$port; + $host = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME']; + + return $protocol.'://'.$host.$port.$_SERVER['REQUEST_URI']; } //发起HTTP请求 -function gdk_http_request($url, $args = array(), $err_args = array()) +function gdk_http_request($url, $args = [], $err_args = []) { - $args = wp_parse_args($args, array( - 'timeout' => 3, - 'method' => '', - 'body' => array(), - 'sslverify' => false, - 'blocking' => true, // 如果不需要立刻知道结果,可以设置为 false - 'stream' => false, // 如果是保存远程的文件,这里需要设置为 true - 'filename' => null, // 设置保存下来文件的路径和名字 - 'need_json_decode' => true, //对结果进行解码,一般都需要 - 'need_json_encode' => false, //对发起参数编码 - // 'headers' => array('Accept-Encoding'=>'gzip;'), //使用压缩传输数据 - // 'headers' => array('Accept-Encoding'=>''), - // 'compress' => false, - 'decompress' => true, - )); + $args = wp_parse_args($args, [ + 'timeout' => 3, + 'method' => '', + 'body' => [], + 'sslverify' => false, + 'blocking' => true, // 如果不需要立刻知道结果,可以设置为 false + 'stream' => false, // 如果是保存远程的文件,这里需要设置为 true + 'filename' => null, // 设置保存下来文件的路径和名字 + 'need_json_decode' => true, //对结果进行解码,一般都需要 + 'need_json_encode' => false, //对发起参数编码 + // 'headers' => array('Accept-Encoding'=>'gzip;'), //使用压缩传输数据 + // 'headers' => array('Accept-Encoding'=>''), + // 'compress' => false, + 'decompress' => true, + ]); $need_json_decode = $args['need_json_decode']; $need_json_encode = $args['need_json_encode']; - $method = ($args['method']) ? strtoupper($args['method']) : ($args['body'] ? 'POST' : 'GET'); - unset($args['need_json_decode']); - unset($args['need_json_encode']); - unset($args['method']); - if ($method == 'GET') { + $method = ($args['method']) ? strtoupper($args['method']) : ($args['body'] ? 'POST' : 'GET'); + unset($args['need_json_decode'], $args['need_json_encode'], $args['method']); + + if ('GET' == $method) { $response = wp_remote_get($url, $args); - } elseif ($method == 'POST') { + } elseif ('POST' == $method) { if ($need_json_encode && is_array($args['body'])) { $args['body'] = json_encode($args['body']); } $response = wp_remote_post($url, $args); - } elseif ($method == 'HEAD') { + } elseif ('HEAD' == $method) { if ($need_json_encode && is_array($args['body'])) { $args['body'] = json_encode($args['body']); } @@ -608,10 +646,11 @@ function gdk_http_request($url, $args = array(), $err_args = array()) $response = wp_remote_request($url, $args); } if (is_wp_error($response)) { - trigger_error($url . "\n" . $response->get_error_code() . ' : ' . $response->get_error_message() . "\n" . var_export($args['body'], true)); + trigger_error($url."\n".$response->get_error_code().' : '.$response->get_error_message()."\n".var_export($args['body'], true)); + return $response; } - $headers = $response['headers']; + $headers = $response['headers']; $response = $response['body']; if ($need_json_decode || isset($headers['content-type']) && strpos($headers['content-type'], '/json')) { if ($args['stream']) { @@ -622,24 +661,26 @@ function gdk_http_request($url, $args = array(), $err_args = array()) return $response; } } - extract(wp_parse_args($err_args, array( + extract(wp_parse_args($err_args, [ 'errcode' => 'errcode', - 'errmsg' => 'errmsg', - 'detail' => 'detail', + 'errmsg' => 'errmsg', + 'detail' => 'detail', 'success' => 0, - ))); + ])); if (isset($response[$errcode]) && $response[$errcode] != $success) { $errcode = $response[$errcode]; - $errmsg = isset($response[$errmsg]) ? $response[$errmsg] : ''; + $errmsg = isset($response[$errmsg]) ? $response[$errmsg] : ''; if (isset($response[$detail])) { $detail = $response[$detail]; - trigger_error($url . "\n" . $errcode . ' : ' . $errmsg . "\n" . var_export($detail, true) . "\n" . var_export($args['body'], true)); + trigger_error($url."\n".$errcode.' : '.$errmsg."\n".var_export($detail, true)."\n".var_export($args['body'], true)); + return new WP_Error($errcode, $errmsg, $detail); - } else { - trigger_error($url . "\n" . $errcode . ' : ' . $errmsg . "\n" . var_export($args['body'], true)); - return new WP_Error($errcode, $errmsg); } + trigger_error($url."\n".$errcode.' : '.$errmsg."\n".var_export($args['body'], true)); + + return new WP_Error($errcode, $errmsg); } + return $response; } @@ -649,14 +690,15 @@ function gdk_get_qq_vid($id_or_url) if (filter_var($id_or_url, FILTER_VALIDATE_URL)) { if (preg_match('#https://v.qq.com/x/page/(.*?).html#i', $id_or_url, $matches)) { return $matches[1]; - } elseif (preg_match('#https://v.qq.com/x/cover/.*/(.*?).html#i', $id_or_url, $matches)) { - return $matches[1]; - } else { - return ''; } - } else { - return $id_or_url; + if (preg_match('#https://v.qq.com/x/cover/.*/(.*?).html#i', $id_or_url, $matches)) { + return $matches[1]; + } + + return ''; } + + return $id_or_url; } //根据秒拍id或者网站获取视频直连 @@ -664,17 +706,19 @@ function get_video_mp4($id_or_url) { if (filter_var($id_or_url, FILTER_VALIDATE_URL)) { if (preg_match('#http://www.miaopai.com/show/(.*?).htm#i', $id_or_url, $matches)) { - return 'http://gslb.miaopai.com/stream/' . esc_attr($matches[1]) . '.mp4'; - } elseif (preg_match('#https://v.qq.com/x/page/(.*?).html#i', $id_or_url, $matches)) { - return get_qqv_mp4($matches[1]); - } elseif (preg_match('#https://v.qq.com/x/cover/.*/(.*?).html#i', $id_or_url, $matches)) { - return get_qqv_mp4($matches[1]); - } else { - return str_replace(['%3A', '%2F'], [':', '/'], urlencode($id_or_url)); + return 'http://gslb.miaopai.com/stream/'.esc_attr($matches[1]).'.mp4'; } - } else { - return get_qqv_mp4($id_or_url); + if (preg_match('#https://v.qq.com/x/page/(.*?).html#i', $id_or_url, $matches)) { + return get_qqv_mp4($matches[1]); + } + if (preg_match('#https://v.qq.com/x/cover/.*/(.*?).html#i', $id_or_url, $matches)) { + return get_qqv_mp4($matches[1]); + } + + return str_replace(['%3A', '%2F'], [':', '/'], urlencode($id_or_url)); } + + return get_qqv_mp4($id_or_url); } //获取腾讯视频 @@ -684,11 +728,11 @@ function get_qqv_mp4($vid) return new WP_Error('invalid_qqv_vid', '非法的腾讯视频 ID'); } $mp4 = wp_cache_get($vid, 'qqv_mp4'); - if ($mp4 === false) { - $response = gdk_http_request('http://vv.video.qq.com/getinfo?otype=json&platform=11001&vid=' . $vid, array( - 'timeout' => 4, + if (false === $mp4) { + $response = gdk_http_request('http://vv.video.qq.com/getinfo?otype=json&platform=11001&vid='.$vid, [ + 'timeout' => 4, 'need_json_decode' => false, - )); + ]); if (is_wp_error($response)) { return $response; } @@ -700,13 +744,14 @@ function get_qqv_mp4($vid) if (empty($response['vl'])) { return new WP_Error('illegal_qqv', '该腾讯视频不存在或者为收费视频!'); } - $u = $response['vl']['vi'][0]; - $p0 = $u['ul']['ui'][0]['url']; - $p1 = $u['fn']; - $p2 = $u['fvkey']; - $mp4 = $p0 . $p1 . '?vkey=' . $p2; + $u = $response['vl']['vi'][0]; + $p0 = $u['ul']['ui'][0]['url']; + $p1 = $u['fn']; + $p2 = $u['fvkey']; + $mp4 = $p0.$p1.'?vkey='.$p2; wp_cache_set($vid, $mp4, 'qqv_mp4', HOUR_IN_SECONDS * 6); } + return $mp4; } @@ -718,7 +763,7 @@ function gdk_str2arr($data, $delimiter = ',') return $data; } // 字符串处理 - $string = (string)$data; + $string = (string) $data; if (empty($string)) { $result = []; } elseif (preg_match('/^{.*?}$/', $string) || preg_match('/^\[.*?]$/', $string)) { @@ -733,6 +778,7 @@ function gdk_str2arr($data, $delimiter = ',') if (!is_array($result) || count($result) < 1) { return []; } + return $result; } @@ -764,21 +810,21 @@ function gdk_panlinks($links) } else { $linknane = '下载'; } + return $linknane; } //一个简单可重复使用的邮件模板 -function mail_temp($mail_title, $mail_cotent, $link, $link_title) +function gdk_mail_temp($mail_title, $mail_cotent, $link, $link_title) { - $content = '
-

' . $mail_title . '

-
' . $mail_cotent . '
- ' . $link_title . ' + return '
+

'.$mail_title.'

+
'.$mail_cotent.'
+ '.$link_title.'

本邮件为系统自动发送,请勿回复。
- 如果不想被此类邮件打扰,请前往 ' . get_option('blogname') . ' 留言说明,由我们来操作处理。 + 如果不想被此类邮件打扰,请前往 '.get_option('blogname').' 留言说明,由我们来操作处理。
'; - return $content; } //获取所有站点分类id,带缓存 @@ -787,17 +833,17 @@ function gdk_category() $cat_ids = get_transient('gdk_category'); if (false === $cat_ids) { $categories = get_terms('category', 'hide_empty=0'); - $k = []; + $k = []; foreach ($categories as $categorie) { $k[] = $categorie->term_id; } - $cat_ids = implode(",", $k); + $cat_ids = implode(',', $k); set_transient('gdk_category', $cat_ids, 60 * 60 * 24 * 5); //缓存5天 } - $cat_ids = explode(",", $cat_ids); + $cat_ids = explode(',', $cat_ids); foreach ($cat_ids as $catid) { $cat_name = get_cat_name($catid); - $output = '' . $cat_name . "=(" . $catid . ')  '; + $output = ''.$cat_name.'=('.$catid.')  '; echo $output; } } @@ -810,26 +856,34 @@ function gdk_category() */ function gdk_term_meta($term, $meta, $id) { - if ($term == 'cat') { + if ('cat' == $term) { $term_meta = gdk_str2arr(category_description($id), '@@'); - } elseif ($term == 'tag') { + } elseif ('tag' == $term) { $term_meta = gdk_str2arr(tag_description($id), '@@'); } else { return false; } + switch ($meta) { case 'des': $result = $term_meta[0]; + break; + case 'keyword': $result = $term_meta[1]; + break; + case 'img': $result = $term_meta[2]; + break; + default: return false; } + return $result; } @@ -840,16 +894,24 @@ function gdk_thumb_color() case '1': case '3': return '?imageAve'; + break; + case '2': return '!/exformat/hex'; + break; + case '4': return '?x-oss-process=image/average-hue'; + break; + case '5': return '?x-image-process=image/average-hue'; + break; + default: return false; } @@ -860,86 +922,104 @@ function gdk_thumb_style($width, $height) { switch (gdk_option('gdk_cdn_serves')) { case '1': - return '?imageView2/1/w/' . $width . '/h/' . $height; + return '?imageView2/1/w/'.$width.'/h/'.$height; + break; + case '2': - return '!/both/' . $width . 'x' . $height . '/force/true'; + return '!/both/'.$width.'x'.$height.'/force/true'; + break; + case '3': - return '?imageMogr2/thumbnail/' . $width . 'x' . $height . '!'; + return '?imageMogr2/thumbnail/'.$width.'x'.$height.'!'; + break; + case '4': - return '?x-oss-process=image/resize,m_fill,h_' . $height . ',w_' . $width . ',limit_0'; + return '?x-oss-process=image/resize,m_fill,h_'.$height.',w_'.$width.',limit_0'; + break; + case '5': - return '?x-image-process=image/resize,m_fill,h_' . $height . ',w_' . $width . ',limit_0'; + return '?x-image-process=image/resize,m_fill,h_'.$height.',w_'.$width.',limit_0'; + break; + default: return false; } } //输出缩略图地址 -function gdk_thumbnail_src() +function gdk_thumbnail_src($id = null) { - global $post; - $gdk_thumbnail_src = ''; - if ($values = get_post_custom_values('gdk_thumb')) { + if (isset($id)) { + $post_ID = $id; + $post_content = get_post($id)->post_content; + } else { + global $post; + $post_ID = $post->ID; + $post_content = $post->post_content; + } + + $gdk_thumb = get_post_meta($post_ID, 'gdk_thumb'); + if (isset($gdk_thumb)) { //输出自定义域图片地址 - $values = get_post_custom_values('gdk_thumb'); - $gdk_thumbnail_src = $values[0]; + + $gdk_thumbnail_url = $gdk_thumb[0]; } elseif (has_post_thumbnail()) { //如果有特色缩略图,则输出缩略图地址 - $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full'); - $gdk_thumbnail_src = $thumbnail_src[0]; + $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post_ID), 'full'); + $gdk_thumbnail_url = $thumbnail_src[0]; } else { ob_start(); ob_end_clean(); - $output = preg_match_all('//i', $post->post_content, $matches); - $gdk_thumbnail_src = $matches[1][0]; //获取该图片 src - if (empty($gdk_thumbnail_src)) { + preg_match_all('//i', $post_content, $output); + $gdk_thumbnail_url = $output[1][0]; //获取该图片 src + if (empty($gdk_thumbnail_url)) { //如果日志中没有图片,则显示随机图片 - $random = mt_rand(1, 12); - $gdk_thumbnail_src = GDK_BASE_URL . 'assets/img/thumb/' . $random . '.jpg'; + $gdk_thumbnail_url = GDK_BASE_URL.'assets/img/thumb/'.mt_rand(1, 12).'.jpg'; } } - ; - return $gdk_thumbnail_src; + + return $gdk_thumbnail_url; } /** * 获取略缩图,输出img标签代码 + * * @param [init] $way 缩略图方案代码,1=cdn,2=timthumb,3=aq_resize * @param [init] $width 缩略图宽度 * @param [init] $height 缩略图高度 * @param [string] $atrr img标签的属性 + * * @return [string] img标签的图片代码 */ function gdk_thumb_img($way, $width, $height, $atrr = 'class="thumb_img"') { $url = gdk_thumbnail_src(); - if ($way === 1) { -//cdn - $src = $url . gdk_thumb_style($width, $height); - } elseif ($way === 2) { - $src = GDK_BASE_URL . 'public/timthumb.php?src=' . $url . '&h=' . $height . '&w=' . $width . '&q=90&zc=1&ct=1'; - } elseif ($way === 3) { + if (1 === $way) {//cdn + $src = $url.gdk_thumb_style($width, $height); + } elseif (2 === $way) { + $src = GDK_BASE_URL.'public/timthumb.php?src='.$url.'&h='.$height.'&w='.$width.'&q=90&zc=1&ct=1'; + } elseif (3 === $way) { $src = aq_resize($url, $width, $height, true); if (empty($src)) { - $src = GDK_BASE_URL . 'public/timthumb.php?src=' . $url . '&h=' . $height . '&w=' . $width . '&q=90&zc=1&ct=1'; + $src = GDK_BASE_URL.'public/timthumb.php?src='.$url.'&h='.$height.'&w='.$width.'&q=90&zc=1&ct=1'; } } else { return false; } - echo ''; + echo ''; } //生成订单号编码 function gdk_order_id() { date_default_timezone_set('Asia/Shanghai'); - $order_id = 'E' . date("YmdHis") . mt_rand(10000, 99999); - return $order_id; + + return 'E'.date('YmdHis').mt_rand(10000, 99999); } //生成随机数 @@ -960,6 +1040,7 @@ function gdk_Remote_Notice($url = 'https: //u.gitcafe.net/api/notice.txt', $hour set_transient('Yunluo_Notice', '有点小尴尬哈啊,服务器菌暂时有点累了呢,先休息一会儿~,', 60 * 60 * $hours); //缓存12小时 } } + return $Yunluo_Notice; } @@ -968,20 +1049,22 @@ function gdk_page_id($pagephp) { global $wpdb; $pagephp = esc_sql($pagephp); - $pageid = $wpdb->get_row("SELECT `post_id` FROM `{$wpdb->postmeta}` WHERE `meta_value` = 'pages/{$pagephp}.php'", ARRAY_A)['post_id']; + $pageid = $wpdb->get_row("SELECT `post_id` FROM `{$wpdb->postmeta}` WHERE `meta_value` = 'pages/{$pagephp}.php'", ARRAY_A)['post_id']; + return $pageid; } //根据订单描述金币数据,d=订单号 u=用户id -function gdk_check($d, $u = null) +function gdk_order_check($d, $u = null) { global $wpdb; - $des = " WHERE `description` = '" . $d . "'"; - $userid = ""; - if (isset($u) && ($u !== null)) { - $userid = " AND `user_id` = '" . $u . "'"; + $des = " WHERE `description` = '".$d."'"; + $userid = ''; + if (isset($u) && (null !== $u)) { + $userid = " AND `user_id` = '".$u."'"; } - $result = $wpdb->query("SELECT `point_id` FROM " . GDK_Points_Database::points_get_table("users") . $des . $userid . " AND `status` = 'accepted' LIMIT 3", ARRAY_A); + $result = $wpdb->query('SELECT `point_id` FROM '.GDK_Points_Database::points_get_table('users').$des.$userid." AND `status` = 'accepted' LIMIT 3", ARRAY_A); + return $result; //0=无订单结果,1=有订单结果,>1均为异常重复入库数据 } @@ -999,31 +1082,31 @@ function payjs_action($body, $attach, $money) { $config = [ 'mchid' => gdk_option('gdk_payjs_id'), // 配置商户号 - 'key' => gdk_option('gdk_payjs_key'), // 配置通信密钥 + 'key' => gdk_option('gdk_payjs_key'), // 配置通信密钥 ]; // 初始化 $payjs = new GDK_Payjs($config); - $data = [ - 'body' => $body, // 订单标题 - 'attach' => $attach, // 订单备注 - 'out_trade_no' => gdk_order_id(), // 订单号 - 'total_fee' => intval($money) * 100, // 金额,单位:分 - 'notify_url' => GDK_BASE_URL . '/public/notify.php', //异步通知文件 - 'hide' => '1', + $data = [ + 'body' => $body, // 订单标题 + 'attach' => $attach, // 订单备注 + 'out_trade_no' => gdk_order_id(), // 订单号 + 'total_fee' => intval($money) * 100, // 金额,单位:分 + 'notify_url' => GDK_BASE_URL.'public/notify.php', //异步通知文件 + 'hide' => '1', ]; - $result['money'] = intval($money); //RMB金额 + $result['money'] = intval($money); //RMB金额 $result['trade_no'] = $data['out_trade_no']; - if ($_POST['way'] == 'alipay') { - $data['type'] = 'alipay'; + if ('alipay' == $_POST['way']) { + $data['type'] = 'alipay'; $result['way'] = '支付宝'; } else { $result['way'] = '微信'; } if (gdk_is_mobile()) { - $rst = $payjs->cashier($data); //手机使用收银台 + $rst = $payjs->cashier($data); //手机使用收银台 $result['img'] = $rst; } else { - $rst = $payjs->native($data); //电脑使用扫码 + $rst = $payjs->native($data); //电脑使用扫码 $result['img'] = $rst['code_url']; } if (in_string($attach, 'PP')) { //如果是付费可见,增加一个参数 @@ -1041,17 +1124,18 @@ function payjs_notify() // 配置通信参数 $config = [ 'mchid' => gdk_option('gdk_payjs_id'), // 配置商户号 - 'key' => gdk_option('gdk_payjs_key'), // 配置通信密钥 + 'key' => gdk_option('gdk_payjs_key'), // 配置通信密钥 ]; $payjs = new GDK_Payjs($config); - $data = $payjs->notify(); //需要做签名性检查 + $data = $payjs->notify(); //需要做签名性检查 // 对返回码判断 - if ($data['return_code'] == 1) { + if (1 == $data['return_code']) { echo 'success'; + return $data; - } else { - exit($data['return_msg']); } + + exit($data['return_msg']); } //充值按钮 @@ -1064,7 +1148,7 @@ function buy_points() '; } else { // no login - $result = '
本页面需要您登录才可以操作,请先 ' . weixin_login_btn() . ' 或者立即注册
'; + $result = '
本页面需要您登录才可以操作,请先 '.weixin_login_btn().' 或者立即注册
'; } + return $result; } //获取bing图 -function get_bing_img() +function gdk_get_bing_img() { $bing_imgurl = get_transient('Bing_img'); if (false === $bing_imgurl) { - $arr = json_decode(file_get_contents('https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'), true); - $bing_imgurl = 'https://cn.bing.com' . $arr['images'][0]['url']; + $arr = json_decode(file_get_contents('https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'), true); + $bing_imgurl = 'https://cn.bing.com'.$arr['images'][0]['url']; set_transient('Bing_img', $bing_imgurl, 60 * 60 * 12); } + return $bing_imgurl; } @@ -1102,46 +1188,48 @@ function login_modal() { $result = '登录 '; - return $result; + return $result; } -/**开始微信* */ -//生成随机字符 -//sk是12位随机字符, key格式是域名@sk +/*开始微信* + * 生成随机字符 + * sk是12位随机字符, key格式是域名@sk +*/ function gdk_weauth_token() { $strs = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm'; - $sk = substr(str_shuffle($strs), mt_rand(0, strlen($strs) - 11), 12); //12位 - set_transient($sk . '-OK', 1, 60); //1分钟缓存 get_transient($sk.'OK') == 1 - $key = $_SERVER['HTTP_HOST'] . '@' . $sk; + $sk = substr(str_shuffle($strs), mt_rand(0, strlen($strs) - 11), 12); //12位 + set_transient($sk.'-OK', 1, 60); //1分钟缓存 get_transient($sk.'OK') == 1 + $key = $_SERVER['HTTP_HOST'].'@'.$sk; + return $key; } function gdk_weauth_qr() { - $qr64 = []; - $qr64['key'] = gdk_weauth_token(); - $qr64['qrcode'] = gdk_http_request('https://wa.isdot.net/qrcode?str=' . $qr64['key'])['qrcode']; + $qr64 = []; + $qr64['key'] = gdk_weauth_token(); + $qr64['qrcode'] = gdk_http_request('https://wa.isdot.net/qrcode?str='.$qr64['key'])['qrcode']; //$qr64['qrcode'] = gdk_http_request('https://api.goauth.jysafe.cn/qrcode?str='.$qr64['key'])['qrcode'];//预备使用,备胎 return $qr64; } /** - * 微信登陆按钮 + * 微信登陆按钮. */ function weixin_login_btn() { $result = ''; if (is_user_logged_in()) { $user_id = get_current_user_id(); - $user = get_user_by('id', $user_id); + $user = get_user_by('id', $user_id); if ($user_id > 0) { if (!empty($user->user_email)) { $result .= ''; @@ -1149,36 +1237,37 @@ function weixin_login_btn() } //$result .= '

您已登陆

您的ID是:'.$user_id.'

您的昵称是:'.$user->nickname.'

'; } + return $result; } -//获取用户ID +// 获取用户ID function create_user_id($userdata) { - $nickname = $userdata[0]; - $wxavatar = $userdata[6]; - $openid = $userdata[7]; - $password = wp_generate_password(12, false); - $login_name = 'wx_' . wp_create_nonce($openid); + $nickname = $userdata[0]; + $wxavatar = $userdata[6]; + $openid = $userdata[7]; + $password = wp_generate_password(12, false); + $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, 'wx_avatar', $wxavatar); } else { - $weauth_user = get_users(array( - 'meta_key ' => 'wx_openid', - 'meta_value' => $openid, - ) + $weauth_user = get_users( + [ + 'meta_key ' => 'wx_openid', + 'meta_value' => $openid, + ] ); if (is_wp_error($weauth_user) || !count($weauth_user)) { - - $user_info = array( - 'user_login' => $login_name, + $user_info = [ + 'user_login' => $login_name, 'display_name' => $nickname, - 'user_pass' => $password, - 'nickname' => $nickname, - ); + 'user_pass' => $password, + 'nickname' => $nickname, + ]; $user_id = wp_insert_user($user_info); update_user_meta($user_id, 'wx_openid', $openid); update_user_meta($user_id, 'wx_avatar', $wxavatar); @@ -1186,6 +1275,7 @@ function create_user_id($userdata) $user_id = $weauth_user[0]->ID; } } + return $user_id; } @@ -1195,13 +1285,13 @@ function editorial_hover_color($hex, $steps) // Steps should be between -255 and 255. Negative = darker, positive = lighter $steps = max(-255, min(255, $steps)); // Normalize into a six character long hex string - $hex = str_replace('#', '', $hex); - if (strlen($hex) == 3) { - $hex = str_repeat(substr($hex, 0, 1), 2) . str_repeat(substr($hex, 1, 1), 2) . str_repeat(substr($hex, 2, 1), 2); + $hex = strtr($hex, '#', ''); + if (3 == strlen($hex)) { + $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2); } // Split into three parts: R, G and B $color_parts = str_split($hex, 2); - $return = '#'; + $return = '#'; foreach ($color_parts as $color) { $color = hexdec($color); // Convert to decimal @@ -1210,15 +1300,17 @@ function editorial_hover_color($hex, $steps) $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code } + return $return; } /** - * Get minified css and removed space + * Get minified css and removed space. + * + * @param mixed $css */ function pwd_minify_css($css) { - // Normalize whitespace $css = preg_replace('/\s+/', ' ', $css); // Remove ; before } @@ -1239,126 +1331,128 @@ function pwd_minify_css($css) function wx_captcha() { date_default_timezone_set('Asia/Shanghai'); - $min = floor(date("i") / 2); - $day = date("d"); - $day = ltrim($day, 0); - $home = home_url(); - $wx_token = trim(gdk_option('gdk_wxmp_token')); - $captcha = sha1($min . $home . $wx_token); - $captcha = substr($captcha, $day, 6); - return $captcha; + $min = floor(date('i') / 2); + $day = date('d'); + $day = ltrim($day, 0); + $home = home_url(); + $wx_token = gdk_option('gdk_wxmp_token'); + $captcha = sha1($min.$home.$wx_token); + return substr($captcha, $day, 6); } function gdk_post_dropdown() { - /* Option list of all post */ - $gdk_options_posts = []; + // Option list of all post + $gdk_options_posts = []; $gdk_options_posts_obj = get_posts('posts_per_page=-1'); foreach ($gdk_options_posts_obj as $gdk_posts) { $gdk_options_posts[$gdk_posts->ID] = $gdk_posts->post_title; } + return $gdk_options_posts; } function gdk_categories_dropdown() { - /* Option list of all categories */ - $gdk_args = array( - 'type' => 'post', - 'orderby' => 'name', - 'order' => 'ASC', - 'hide_empty' => 1, + // Option list of all categories + $args = [ + 'type' => 'post', + 'orderby' => 'name', + 'order' => 'ASC', + 'hide_empty' => 1, 'hierarchical' => 1, - 'taxonomy' => 'category', - ); - $gdk_option_categories = []; - $gdk_category_lists = get_categories($gdk_args); + 'taxonomy' => 'category', + ]; + $gdk_option_categories = []; + $gdk_category_lists = get_categories($args); foreach ($gdk_category_lists as $gdk_category) { $gdk_option_categories[$gdk_category->term_id] = $gdk_category->name; } + return $gdk_option_categories; } function gdk_tag_dropdown() { - /* Option list of all tags */ - $gdk_args = array( - 'type' => 'post', - 'orderby' => 'name', - 'order' => 'ASC', - 'hide_empty' => 1, + // Option list of all tags + $args = [ + 'type' => 'post', + 'orderby' => 'name', + 'order' => 'ASC', + 'hide_empty' => 1, 'hierarchical' => 1, - 'taxonomy' => 'tag', - ); - $gdk_option_tags = []; - $gdk_tag_lists = get_tags($gdk_args); + 'taxonomy' => 'tag', + ]; + $gdk_option_tags = []; + $gdk_tag_lists = get_tags($args); $gdk_option_tags[''] = '选择标签'; foreach ($gdk_tag_lists as $gdk_tag) { $gdk_option_tags[$gdk_tag->term_id] = $gdk_tag->name; } + return $gdk_option_tag; } //转化图片为base64格式 -function base64img($image_file) +function gdk_base64img($image_file) { - $base64_image = ''; - $image_info = getimagesize($image_file); - $image_data = file_get_contents($image_file); - $base64_image = 'data:' . $image_info['mime'] . ';base64,' . base64_encode($image_data); - return $base64_image; + $image_info = getimagesize($image_file); + $image_data = file_get_contents($image_file); + return 'data:'.$image_info['mime'].';base64,'.base64_encode($image_data); } //生成二维码 -function getQrcode($url) +function gdk_getQrcode($url) { //引入phpqrcode类库 - require_once GDK_ROOT_PATH . '/class/qrcode.class.php'; + require_once GDK_ROOT_PATH.'/class/qrcode.class.php'; $errorCorrectionLevel = 'L'; //容错级别 - $matrixPointSize = 6; //生成图片大小 + $matrixPointSize = 6; //生成图片大小 ob_start(); QRcode::png($url, false, $errorCorrectionLevel, $matrixPointSize, 2); $data = ob_get_contents(); ob_end_clean(); $imageString = base64_encode($data); - header("content-type:application/json; charset=utf-8"); - return 'data:image/jpeg;base64,' . $imageString; + header('content-type:application/json; charset=utf-8'); + + return 'data:image/jpeg;base64,'.$imageString; } -function unzip_url($url, $where) +function gdk_unzip_url($url, $where) { - $zippath = $where . '/' . (basename($url)); + $zippath = $where.'/'.(basename($url)); $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL,$url); - curl_setopt($curl, CURLOPT_HEADER,0); - curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); - curl_setopt($curl,CURLOPT_TIMEOUT,300); - $downfile = fopen($zippath,'wb'); - curl_setopt($curl,CURLOPT_FILE,$downfile); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_HEADER, 0); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_TIMEOUT, 300); + $downfile = fopen($zippath, 'wb'); + curl_setopt($curl, CURLOPT_FILE, $downfile); curl_exec($curl); curl_close($curl); - require_once ABSPATH . 'wp-admin/includes/file.php'; + + require_once ABSPATH.'wp-admin/includes/file.php'; \WP_Filesystem(); \unzip_file($zippath, $where); usleep(300000); - @unlink($zippath); + unlink($zippath); } //新窗口打开 -function blank_open() +function gdk_blank_open() { if (!gdk_option('gdk_target_blank')) { echo 'target="_blank"'; } - } function gdk_guest_form() { ?>

-

+

' . $content . '
' . $after; - }elseif(!empty($before)) { - return $before . '
' . $content; - }elseif(!empty($after)) { - return $content . '
' . $after; - }else{ - return $content; - } +function gdk_add_content($content) +{ + if (is_single()) { + $before = gdk_option('gdk_artical_top'); + $after = gdk_option('gdk_artical_bottom'); + if (!empty($before) && !empty($after)) { + return $before.'
'.$content.'
'.$after; + } + if (!empty($before)) { + return $before.'
'.$content; + } + if (!empty($after)) { + return $content.'
'.$after; + } - }else{ - return $content; - } + return $content; + } + + return $content; } add_filter('the_content', 'gdk_add_content'); @@ -44,18 +49,19 @@ 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) { + $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) && 1 !== $weauth_res) { return; } - $weauth_user = stripslashes($weauth_user); - $weauth_user = json_decode($weauth_user, true); + $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分钟缓存 + set_transient($weauth_sk.'-info', $oauth_result, 60); //1分钟缓存 header('goauth: ok'); echo 'success'; //给对方服务器打个招呼 + exit; } } @@ -66,11 +72,11 @@ function gdk_wx_avatar($avatar, $id_or_email, $size, $default, $alt) { $user = false; if (is_numeric($id_or_email)) { - $id = (int)$id_or_email; + $id = (int) $id_or_email; $user = get_user_by('id', $id); } elseif (is_object($id_or_email)) { if (!empty($id_or_email->user_id)) { - $id = (int)$id_or_email->user_id; + $id = (int) $id_or_email->user_id; $user = get_user_by('id', $id); } } else { @@ -82,6 +88,7 @@ function gdk_wx_avatar($avatar, $id_or_email, $size, $default, $alt) $avatar = "{$alt}"; } } + return $avatar; } add_filter('get_avatar', 'gdk_wx_avatar', 19, 5); @@ -91,18 +98,25 @@ function gdk_switch_get_avatar($avatar) { switch (gdk_option('gdk_switch_get_avatar')) { case 1: - $rand_avatar = 'https://cdn.jsdelivr.net/gh/yunluo/GitCafeApi/avatar/' . mt_rand(1, 1999) . '.jpg'; - $avatar = ""; + $rand_avatar = 'https://cdn.jsdelivr.net/gh/yunluo/GitCafeApi/avatar/'.mt_rand(1, 1999).'.jpg'; + $avatar = ""; + break; + case 2: - $avatar = preg_replace("/http[s]{0,1}:\/\/(secure|www|\d).gravatar.com\/avatar\//", "//cdn.v2ex.com/gravatar/", $avatar); + $avatar = preg_replace('/http[s]{0,1}:\\/\\/(secure|www|\\d).gravatar.com\\/avatar\\//', '//cdn.v2ex.com/gravatar/', $avatar); + break; + case 3: - $avatar = preg_replace("/http[s]{0,1}:\/\/(secure|www|\d).gravatar.com\/avatar\//", "//dn-qiniu-avatar.qbox.me/avatar/", $avatar); + $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); + $avatar = preg_replace('/http[s]{0,1}:\\/\\/(secure|www|\\d).gravatar.com\\/avatar\\//', '//cravatar.cn/avatar/', $avatar); } + return $avatar; } add_filter('get_avatar', 'gdk_switch_get_avatar'); @@ -111,12 +125,13 @@ 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 ('post' != get_post_type()) { + return $content; + } if (!is_feed() || !is_robots()) { $content = preg_replace('//i', "\n", $content); } + return $content; } add_filter('the_content', 'gdk_lazyload'); @@ -125,11 +140,11 @@ if (gdk_option('gdk_lazyload')) { //强制兼容
,和下面转义代码搭配使用
 function gdk_prettify_replace($text)
 {
-    $replace = array(
+    $replace = [
         '
' => '
',
-    );
-    $text = str_replace(array_keys($replace), $replace, $text);
-    return $text;
+    ];
+
+    return strtr($text, $replace);
 }
 add_filter('content_save_pre', 'gdk_prettify_replace');
 add_filter('the_content', 'gdk_prettify_replace');
@@ -138,15 +153,17 @@ add_filter('the_content', 'gdk_prettify_replace');
 function gdk_esc_html($content)
 {
     $regex = '/(]*?class\s*?=\s*?[",\'].*?prettyprint.*?[",\'].*?>)(.*?)(<\/pre>)/sim';
+
     return preg_replace_callback($regex, 'gdk_esc_callback', $content);
 }
 function gdk_esc_callback($matches)
 {
-    $tag_open  = $matches[1];
-    $content   = $matches[2];
+    $tag_open = $matches[1];
+    $content = $matches[2];
     $tag_close = $matches[3];
-    $content   = esc_html($content);
-    return $tag_open . $content . $tag_close;
+    $content = esc_html($content);
+
+    return $tag_open.$content.$tag_close;
 }
 add_filter('the_content', 'gdk_esc_html', 2);
 add_filter('comment_text', 'gdk_esc_html', 2);
@@ -155,10 +172,10 @@ add_filter('comment_text', 'gdk_esc_html', 2);
 if (gdk_option('gdk_lazyload')) {
     function gdk_fancybox($content)
     {
-        $pattern     = "/]*).(bmp|gif|jpeg|jpg|png|swf)('|\")(.*?)>(.*?)<\\/a>/i";
+        $pattern = "/]*).(bmp|gif|jpeg|jpg|png|swf)('|\")(.*?)>(.*?)<\\/a>/i";
         $replacement = '$7';
-        $content     = preg_replace($pattern, $replacement, $content);
-        return $content;
+
+        return preg_replace($pattern, $replacement, $content);
     }
     add_filter('the_content', 'gdk_fancybox');
 }
@@ -170,23 +187,24 @@ function gdk_link_go($content)
     if ($matches) {
         foreach ($matches[2] as $val) {
             if (in_string($val, '://') && !in_string($val, home_url()) && !preg_match('/\.(jpg|jepg|png|ico|bmp|gif|zip|rar|tiff)/i', $val) && !preg_match('/(ed2k|thunder|Flashget|flashget|qqdl):\/\//i', $val)) {
-                $content = str_replace("href=\"$val\"", "href=\"" . home_url() . "?go=$val\" ", $content);
+                $content = str_replace("href=\"{$val}\"", 'href="'.home_url()."?go={$val}\" ", $content);
             }
         }
     }
+
     return $content;
 }
 
 //邮箱SMTP设置
 function gdk_smtp($phpmailer)
 {
-    $phpmailer->FromName   = gdk_option('gdk_smtp_username'); //昵称
-    $phpmailer->Host       = gdk_option('gdk_smtp_host'); //服务器地址
-    $phpmailer->Port       = gdk_option('gdk_smtp_port'); //端口
-    $phpmailer->Username   = gdk_option('gdk_smtp_mail'); //邮箱地址
-    $phpmailer->Password   = gdk_option('gdk_smtp_password'); //密码
-    $phpmailer->From       = gdk_option('gdk_smtp_mail'); //邮箱地址
-    $phpmailer->SMTPAuth   = true;
+    $phpmailer->FromName = gdk_option('gdk_smtp_username'); //昵称
+    $phpmailer->Host = gdk_option('gdk_smtp_host'); //服务器地址
+    $phpmailer->Port = gdk_option('gdk_smtp_port'); //端口
+    $phpmailer->Username = gdk_option('gdk_smtp_mail'); //邮箱地址
+    $phpmailer->Password = gdk_option('gdk_smtp_password'); //密码
+    $phpmailer->From = gdk_option('gdk_smtp_mail'); //邮箱地址
+    $phpmailer->SMTPAuth = true;
     $phpmailer->SMTPSecure = 'ssl';
     $phpmailer->IsSMTP();
 }
@@ -199,28 +217,30 @@ function gdk_cdn_start()
 function gdk_cdn_replace($html)
 {
     $local_host = home_url(); //博客域名
-    $cdn_host   = gdk_option('gdk_cdn_host'); //cdn域名
-    $cdn_exts   = gdk_option('gdk_cdn_ext'); //扩展名(使用|分隔)
-    $cdn_dirs   = gdk_option('gdk_cdn_dir'); //目录(使用|分隔)
-    $cdn_dirs   = str_replace('-', '\-', $cdn_dirs);
-    if ($cdn_dirs) {
-        $regex = '/' . str_replace('/', '\/', $local_host) . '\/((' . $cdn_dirs . ')\/[^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_exts . '))([\"\\\'\s\?]{1})/';
-        $html  = preg_replace($regex, $cdn_host . '/$1$4', $html);
+    $cdn_host = gdk_option('gdk_cdn_host'); //cdn域名
+    $cdn_exts = gdk_option('gdk_cdn_ext'); //扩展名(使用|分隔)
+    $cdn_dirs = gdk_option('gdk_cdn_dir'); //目录(使用|分隔)
+    $cdn_dirs = str_replace('-', '\-', $cdn_dirs);
+    if (isset( $cdn_dirs)) {
+        $regex = '/'.str_replace('/', '\/', $local_host).'\/(('.$cdn_dirs.')\/[^\s\?\\\'\"\;\>\<]{1,}.('.$cdn_exts.'))([\"\\\'\s\?]{1})/';
+        $html = preg_replace($regex, $cdn_host.'/$1$4', $html);
     } else {
-        $regex = '/' . str_replace('/', '\/', $local_host) . '\/([^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_exts . '))([\"\\\'\s\?]{1})/';
-        $html  = preg_replace($regex, $cdn_host . '/$1$3', $html);
+        $regex = '/'.str_replace('/', '\/', $local_host).'\/([^\s\?\\\'\"\;\>\<]{1,}.('.$cdn_exts.'))([\"\\\'\s\?]{1})/';
+        $html = preg_replace($regex, $cdn_host.'/$1$3', $html);
     }
+
     return $html;
 }
 
 //CDN水印
 function gdk_cdn_water($content)
 {
-    if (get_post_type() == 'post') {
-        $pattern     = "//i";
+    if ('post' == get_post_type()) {
+        $pattern = "//i";
         $replacement = '';
-        $content     = preg_replace($pattern, $replacement, $content);
+        $content = preg_replace($pattern, $replacement, $content);
     }
+
     return $content;
 }
 
@@ -230,48 +250,50 @@ if (gdk_option('gdk_compress')) {
     {
         function gdk_compress_html_callback($buffer)
         {
-            if (substr(ltrim($buffer), 0, 5) == '", $buffer);
-            $count   = count($buffer);
-            $i       = '';
-            for ($i = 0; $i <= $count; $i++) {
+            $buffer = explode('', $buffer);
+            $count = count($buffer);
+            $i = '';
+            for ($i = 0; $i <= $count; ++$i) {
                 if (stristr($buffer[$i], '')) {
-                    $buffer[$i] = str_replace("", " ", $buffer[$i]);
+                    $buffer[$i] = str_replace('', ' ', $buffer[$i]);
                 } else {
-                    $buffer[$i] = str_replace("\t", " ", $buffer[$i]);
+                    $buffer[$i] = str_replace("\t", ' ', $buffer[$i]);
                     $buffer[$i] = str_replace("\n\n", "\n", $buffer[$i]);
-                    $buffer[$i] = str_replace("\n", "", $buffer[$i]);
-                    $buffer[$i] = str_replace("\r", "", $buffer[$i]);
+                    $buffer[$i] = str_replace("\n", '', $buffer[$i]);
+                    $buffer[$i] = str_replace("\r", '', $buffer[$i]);
                     while (stristr($buffer[$i], '  ')) {
-                        $buffer[$i] = str_replace("  ", " ", $buffer[$i]);
+                        $buffer[$i] = str_replace('  ', ' ', $buffer[$i]);
                     }
                 }
                 $buffer_out .= $buffer[$i];
             }
             $final = strlen($buffer_out);
-            if ($initial !== 0) {
+            if (0 !== $initial) {
                 $savings = ($initial - $final) / $initial * 100;
             } else {
                 $savings = 0;
             }
             $savings = round($savings, 2);
             $buffer_out .= "\n";
+
             return $buffer_out;
         }
-        ob_start("gdk_compress_html_callback");
+        ob_start('gdk_compress_html_callback');
     }
     add_action('get_header', 'gdk_compress_html');
 
     function gdk_unCompress($content)
     {
         if (preg_match_all('/(crayon-|)/i', $content, $matches)) {
-            $content = '' . $content;
+            $content = ''.$content;
             $content .= '';
         }
+
         return $content;
     }
     add_filter('the_content', 'gdk_unCompress');
@@ -282,17 +304,18 @@ function gdk_search_by_title($search, $wp_query)
 {
     if (!empty($search) && !empty($wp_query->query_vars['search_terms'])) {
         global $wpdb;
-        $q      = $wp_query->query_vars;
-        $n      = !empty($q['exact']) ? '' : '%';
-        $search = array();
-        foreach ((array)$q['search_terms'] as $term) {
-            $search[] = $wpdb->prepare("{$wpdb->posts}.post_title LIKE %s", $n . $wpdb->esc_like($term) . $n);
+        $q = $wp_query->query_vars;
+        $n = !empty($q['exact']) ? '' : '%';
+        $search = [];
+        foreach ((array) $q['search_terms'] as $term) {
+            $search[] = $wpdb->prepare("{$wpdb->posts}.post_title LIKE %s", $n.$wpdb->esc_like($term).$n);
         }
         if (!is_user_logged_in()) {
             $search[] = "{$wpdb->posts}.post_password = ''";
         }
-        $search = ' AND ' . implode(' AND ', $search);
+        $search = ' AND '.implode(' AND ', $search);
     }
+
     return $search;
 }
 add_filter('posts_search', 'gdk_search_by_title', 10, 2);
@@ -308,6 +331,7 @@ function gdk_comment_author($query_vars)
             unset($query_vars['author_name']);
         }
     }
+
     return $query_vars;
 }
 add_filter('request', 'gdk_comment_author');
@@ -315,34 +339,34 @@ add_filter('request', 'gdk_comment_author');
 function gdk_comment_author_link($link, $author_id, $author_nicename)
 {
     $my_name = get_user_meta($author_id, 'first_name', true);
-    if ($my_name) {
-        $link = str_replace($author_nicename, $my_name, $link);
+    if (isset($my_name)) {
+        $link = strtr($link, [$author_nicename => $my_name]);
     }
+
     return $link;
 }
 add_filter('author_link', 'gdk_comment_author_link', 10, 3);
 
-function weauth_page_activate()
+function gdk_weauth_page_activate()
 {
     $awesome_page_id = get_option('weixin_page_id');
     if (!$awesome_page_id) {
-        $post = array(
-            'post_title'   => '微信登录', //这里是自动生成页面的页面标题
-             'post_content' => '[gdk_login_btn]', //这里是页面的内容
-             'post_status'  => 'publish',
-            'post_type'    => 'page',
-            'post_name'    => 'weixin',
-        );
+        $post = [
+            'post_title' => '微信登录', //这里是自动生成页面的页面标题
+            'post_content' => '[gdk_login_btn]', //这里是页面的内容
+            'post_status' => 'publish',
+            'post_type' => 'page',
+            'post_name' => 'weixin',
+        ];
         $postID = wp_insert_post($post);
         update_post_meta($postID, '_wp_page_template', ''); //这里是生成页面的模板类型
         update_option('weixin_page_id', $postID);
     }
-
 }
-add_action('admin_init', 'weauth_page_activate');
+add_action('admin_init', 'gdk_weauth_page_activate');
 
 //强制微信登录
-function force_weauth_login_url($login_url, $redirect, $force_reauth)
+function gdk_force_weauth_login_url($login_url, $redirect, $force_reauth)
 {
     $login_url = get_permalink(get_option('weixin_page_id'));
     if (!empty($redirect)) {
@@ -351,45 +375,43 @@ function force_weauth_login_url($login_url, $redirect, $force_reauth)
     if ($force_reauth) {
         $login_url = add_query_arg('reauth', '1', $login_url);
     }
+
     return $login_url;
 }
 
-function change_my_register_url($url)
+function gdk_change_register_url($url)
 {
     if (is_admin()) {
         return $url;
     }
+
     return wp_login_url();
 }
 
 if (gdk_option('gdk_weauth_oauth') && gdk_option('gdk_weauth_force')) {
-    add_filter('login_url', 'force_weauth_login_url', 10, 3);
-    add_filter('register_url', 'change_my_register_url');
+    add_filter('login_url', 'gdk_force_weauth_login_url', 10, 3);
+    add_filter('register_url', 'gdk_change_register_url');
 }
 
-
-
 /**
- * 清除文章相关的缓存
+ * 清除文章相关的缓存.
  */
 function gdk_clear_post_cache()
 {
     delete_transient('gdk-sitemap');
     delete_transient('gdk-sitemap-html');
 }
-add_action('save_post', 'gdk_clear_post_cache' );
-add_action('deleted_post', 'gdk_clear_post_cache' );
+add_action('save_post', 'gdk_clear_post_cache');
+add_action('deleted_post', 'gdk_clear_post_cache');
 add_action('publish_post', 'gdk_clear_post_cache');
 add_action('publish_page', 'gdk_clear_post_cache');
-add_action('save_post', 'gdk_clear_post_cache');
 
 /**
- * 清除链接缓存
+ * 清除链接缓存.
  */
 function gdk_clear_link_cache()
 {
     delete_transient('gdk-daohang-html');
 }
-add_action('edit_link', 'gdk_clear_link_cache' );
-add_action('add_link', 'gdk_clear_link_cache' );
-add_action('set_object_terms', 'gdk_clear_link_cache');
\ No newline at end of file
+add_action('edit_link', 'gdk_clear_link_cache');
+add_action('add_link', 'gdk_clear_link_cache');
diff --git a/functions/email.php b/functions/email.php
index 8460274..537494a 100644
--- a/functions/email.php
+++ b/functions/email.php
@@ -1,68 +1,44 @@
 From = gdk_option('gdk_maildizhi_b'); //发件人地址
-$phpmailer->FromName = gdk_option('gdk_mailnichen_b'); //发件人昵称
-$phpmailer->Host = gdk_option('gdk_mailsmtp_b'); //SMTP服务器地址
-$phpmailer->Port = gdk_option('gdk_mailport_b'); //SMTP邮件发送端口
-if (gdk_option('gdk_smtpssl_b')) {
-$phpmailer->SMTPSecure = 'ssl';
-} else {
-$phpmailer->SMTPSecure = '';
-} //SMTP加密方式(SSL/TLS)没有为空即可
-$phpmailer->Username = gdk_option('gdk_mailuser_b'); //邮箱帐号
-$phpmailer->Password = gdk_option('gdk_mailpass_b'); //邮箱密码
-$phpmailer->IsSMTP();
-$phpmailer->SMTPAuth = true; //启用SMTPAuth服务
-
-}
-add_action('phpmailer_init', 'googlo_mail_smtp');
-}
- */
 //修改默认发信地址
-function deel_res_from_email($email)
+function gdk_from_email($email)
 {
-    $wp_from_email = get_option('admin_email');
-    return $wp_from_email;
+    return get_option('admin_email');
 }
-function deel_res_from_name($email)
+function gdk_from_name($email)
 {
-    $wp_from_name = get_option('blogname');
-    return $wp_from_name;
+    return get_option('blogname');
 }
-add_filter('wp_mail_from', 'deel_res_from_email');
-add_filter('wp_mail_from_name', 'deel_res_from_name');
+add_filter('wp_mail_from', 'gdk_from_email');
+add_filter('wp_mail_from_name', 'gdk_from_name');
 
 //评论回应邮件通知
 function comment_mail_notify($comment_id)
 {
-    $admin_notify         = '0'; // admin 要不要收回复通知 ( '1'=要 ; '0'=不要 )
-    $admin_email          = get_bloginfo('admin_email'); // $admin_email 可改为你指定的 e-mail.
-    $comment              = get_comment($comment_id);
+    $admin_notify = '0'; // admin 要不要收回复通知 ( '1'=要 ; '0'=不要 )
+    $admin_email = get_bloginfo('admin_email'); // $admin_email 可改为你指定的 e-mail.
+    $comment = get_comment($comment_id);
     $comment_author_email = trim($comment->comment_author_email);
-    $parent_id            = $comment->comment_parent ? $comment->comment_parent : '';
-    $blogname             = get_option("blogname");
+    $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
+    $blogname = get_option('blogname');
     global $wpdb;
-    if ($wpdb->query("Describe {$wpdb->comments} comment_mail_notify") == '') {
+    if ('' == $wpdb->query("Describe {$wpdb->comments} comment_mail_notify")) {
         $wpdb->query("ALTER TABLE {$wpdb->comments} ADD COLUMN comment_mail_notify TINYINT NOT NULL DEFAULT 0;");
     }
 
-    if (($comment_author_email != $admin_email && isset($_POST['comment_mail_notify'])) || ($comment_author_email == $admin_email && $admin_notify == '1')) {
-        $wpdb->query("UPDATE {$wpdb->comments} SET comment_mail_notify='1' WHERE comment_ID='$comment_id'");
+    if (($comment_author_email != $admin_email && isset($_POST['comment_mail_notify'])) || ($comment_author_email == $admin_email && '1' == $admin_notify)) {
+        $wpdb->query("UPDATE {$wpdb->comments} SET comment_mail_notify='1' WHERE comment_ID='{$comment_id}'");
     }
 
-    $notify         = $parent_id ? get_comment($parent_id)->comment_mail_notify : '0';
+    $notify = $parent_id ? get_comment($parent_id)->comment_mail_notify : '0';
     $spam_confirmed = $comment->comment_approved;
-    if ($parent_id != '' && $spam_confirmed != 'spam' && $notify == '1') {
-        $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); // e-mail 发出点, no-reply 可改为可用的 e-mail.
-        $to       = trim(get_comment($parent_id)->comment_author_email);
-        $subject  = 'Hi,您在 [' . get_option("blogname") . '] 的留言有人回复啦!';
-        $message  = '

> 您在 ' . $blogname . ' 网站上的留言有回复啦!

您好, ' . trim(get_comment($parent_id)->comment_author) . '! 您发表在文章 《' . get_the_title($comment->comment_post_ID) . '》 的评论:

' . nl2br(strip_tags(get_comment($parent_id)->comment_content)) . '

' . trim($comment->comment_author) . ' 给您的回复如下:

' . nl2br(strip_tags($comment->comment_content)) . '

您可以点击 这里查看回复的完整內容,也欢迎再次光临 ' . $blogname . '。祝您天天开心,欢迎下次访问 ' . $blogname . '!谢谢。

(此邮件由系统自动发出, 请勿回复)

Copyright © 2013-2018 ' . $blogname . '
'; - $from = "From: \"" . get_option('blogname') . "\" <$wp_email>"; - $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n"; + if ('' != $parent_id && 'spam' != $spam_confirmed && '1' == $notify) { + $wp_email = 'no-reply@'.preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); // e-mail 发出点, no-reply 可改为可用的 e-mail. + $to = trim(get_comment($parent_id)->comment_author_email); + $subject = 'Hi,您在 ['.get_option('blogname').'] 的留言有人回复啦!'; + $message = '

> 您在 '.$blogname.' 网站上的留言有回复啦!

您好, '.trim(get_comment($parent_id)->comment_author).'! 您发表在文章 《'.get_the_title($comment->comment_post_ID).'》 的评论:

'.nl2br(strip_tags(get_comment($parent_id)->comment_content)).'

'.trim($comment->comment_author).' 给您的回复如下:

'.nl2br(strip_tags($comment->comment_content)).'

您可以点击 这里查看回复的完整內容,也欢迎再次光临 '.$blogname.'。祝您天天开心,欢迎下次访问 '.$blogname.'!谢谢。

(此邮件由系统自动发出, 请勿回复)

Copyright © 2013-2018 '.$blogname.'
'; + $from = 'From: "'.get_option('blogname')."\" <{$wp_email}>"; + $headers = "{$from}\nContent-Type: text/html; charset=".get_option('blog_charset')."\n"; wp_mail($to, $subject, $message, $headers); } } @@ -72,7 +48,8 @@ add_action('comment_post', 'comment_mail_notify'); function gdk_notify_postauthor($notify_message, $comment_ID) { $notify = $notify_message; - $notify .= '快速回复此评论: ' . admin_url("edit-comments.php") . '#comment-' . $comment_ID; + $notify .= '快速回复此评论: '.admin_url('edit-comments.php').'#comment-'.$comment_ID; + return $notify; } add_filter('comment_notification_text', 'gdk_notify_postauthor', 10, 2); @@ -81,12 +58,12 @@ add_filter('comment_notification_text', 'gdk_notify_postauthor', 10, 2); function gdk_register_mail($user_id) { - $user = get_user_by('id', $user_id); + $user = get_user_by('id', $user_id); $user_pass = $_POST['password']; - $blogname = get_option('blogname'); - $message = '

注册成功通知

尊敬的' . $user->user_login . ',您好!

欢迎您注册[' . $blogname . '],下面是您的账号信息,请妥善保管!

您的详细注册信息
登录邮箱' . $user->user_email . '
登录密码' . $user_pass . '

如果您的账号有异常,请您在第一时间和我们取得联系哦,联系邮箱:' . get_bloginfo('admin_email') . '

'; - $headers = "Content-Type:text/html;charset=UTF-8\n"; - wp_mail($user->user_email, '[' . $blogname . ']欢迎注册' . $blogname, $message, $headers); + $blogname = get_option('blogname'); + $message = '

注册成功通知

尊敬的'.$user->user_login.',您好!

欢迎您注册['.$blogname.'],下面是您的账号信息,请妥善保管!

您的详细注册信息
登录邮箱'.$user->user_email.'
登录密码'.$user_pass.'

如果您的账号有异常,请您在第一时间和我们取得联系哦,联系邮箱:'.get_bloginfo('admin_email').'

'; + $headers = "Content-Type:text/html;charset=UTF-8\n"; + wp_mail($user->user_email, '['.$blogname.']欢迎注册'.$blogname, $message, $headers); } add_action('user_register', 'gdk_register_mail'); @@ -96,12 +73,12 @@ function gdk_login_failed_notify() { date_default_timezone_set('PRC'); $admin_email = get_bloginfo('admin_email'); - $to = $admin_email; - $subject = '您的网站登录错误警告'; - $message = '

您好!您的网站(' . get_option("blogname") . ')有登录错误!

' . '

请确定是您自己的登录失误,以防别人攻击!登录信息如下:

' . '

登录名:' . $_POST['log'] . '

' . '

登录密码:' . $_POST['pwd'] . '

' . '

登录时间:' . date("Y-m-d H:i:s") . '

' . '

登录IP:' . $_SERVER['REMOTE_ADDR'] . '

' . '

————本邮件由系统发送,无需回复

'; - $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); - $from = "From: \"" . get_option('blogname') . "\" <$wp_email>"; - $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n"; + $to = $admin_email; + $subject = '您的网站登录错误警告'; + $message = '

您好!您的网站('.get_option('blogname').')有登录错误!

'.'

请确定是您自己的登录失误,以防别人攻击!登录信息如下:

'.'

登录名:'.$_POST['log'].'

'.'

登录密码:'.$_POST['pwd'].'

'.'

登录时间:'.date('Y-m-d H:i:s').'

'.'

登录IP:'.$_SERVER['REMOTE_ADDR'].'

'.'

————本邮件由系统发送,无需回复

'; + $wp_email = 'no-reply@'.preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); + $from = 'From: "'.get_option('blogname')."\" <{$wp_email}>"; + $headers = "{$from}\nContent-Type: text/html; charset=".get_option('blog_charset')."\n"; wp_mail($to, $subject, $message, $headers); } add_action('wp_login_failed', 'gdk_login_failed_notify'); diff --git a/functions/func_load.php b/functions/func_load.php index 4b0e849..0bee829 100644 --- a/functions/func_load.php +++ b/functions/func_load.php @@ -1,16 +1,25 @@ 首页!'); + wp_die('Feed已经关闭, 请访问网站首页!'); } add_action('do_feed', 'gdk_feed_disabled', 1); @@ -28,13 +28,12 @@ function gdk_disable_srcset_img() } add_filter('max_srcset_image_width', 'gdk_disable_srcset_img'); -add_filter( 'big_image_size_threshold', '__return_false' ); +add_filter('big_image_size_threshold', '__return_false'); //移除默认的图片宽度以及高度 function gdk_remove_img_width($html) { - $html = preg_replace('/(width|height)=\"\d*\"\s/', "", $html); - return $html; + return preg_replace('/(width|height)=\"\d*\"\s/', '', $html); } add_filter('post_thumbnail_html', 'gdk_remove_img_width', 10); add_filter('image_send_to_editor', 'gdk_remove_img_width', 10); @@ -60,11 +59,12 @@ function gdk_disable_attachment_pages() if (is_attachment()) { if (!empty($post->post_parent)) { wp_redirect(get_permalink($post->post_parent), 301); - exit; - } else { - wp_redirect(home_url()); + exit; } + wp_redirect(home_url()); + + exit; } } add_action('template_redirect', 'gdk_disable_attachment_pages', 1); @@ -95,8 +95,8 @@ if (gdk_option('gdk_auto_space')) { function gdk_auto_space($data) { $data = preg_replace('/([\\x{4e00}-\\x{9fa5}]+)([A-Za-z0-9_]+)/u', '${1} ${2}', $data); - $data = preg_replace('/([A-Za-z0-9_]+)([\\x{4e00}-\\x{9fa5}]+)/u', '${1} ${2}', $data); - return $data; + + return preg_replace('/([A-Za-z0-9_]+)([\\x{4e00}-\\x{9fa5}]+)/u', '${1} ${2}', $data); } add_filter('the_content', 'gdk_auto_space'); } @@ -116,11 +116,11 @@ function gdk_after_init_theme() update_option('thumbnail_size_h', '0'); //关闭默认缩略图 update_option('default_ping_status', 'closed'); //关闭默认ping状态 update_option('comment_order', 'desc'); //关闭默认评论显示顺序 - if (get_option('permalink_structure') == '' || define('GDK_HTML_LINK', true)) { //如果是默认连接格式或者主题声明 define( 'GDK_HTML_LINK', true ); + 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' ); //禁用新版小工具 + if (gdk_option('gdk_diasble_widgets_block')) { //如果 + remove_theme_support('widgets-block-editor'); //禁用新版小工具 } update_option('posts_per_page', '30'); //每页文章数目 } @@ -129,7 +129,7 @@ add_action('after_setup_theme', 'gdk_after_init_theme'); //新标签打开顶部网站链接 function gdk_blank_site_bar($wp_admin_bar) { - $node = $wp_admin_bar->get_node('view-site'); + $node = $wp_admin_bar->get_node('view-site'); $node->meta['target'] = '_blank'; $wp_admin_bar->add_node($node); } @@ -138,7 +138,7 @@ add_action('admin_bar_menu', 'gdk_blank_site_bar', 80); //移除 WP_Head 无关紧要的代码 if (gdk_option('gdk_diasble_head_useless')) { remove_action('wp_head', 'wp_generator'); //删除 head 中的 WP 版本号 - foreach (array('rss2_head', 'commentsrss2_head', 'rss_head', 'rdf_header', 'atom_head', 'comments_atom_head', 'opml_head', 'app_head') as $action) { + foreach (['rss2_head', 'commentsrss2_head', 'rss_head', 'rdf_header', 'atom_head', 'comments_atom_head', 'opml_head', 'app_head'] as $action) { remove_action($action, 'the_generator'); } @@ -167,8 +167,7 @@ add_action('in_admin_header', function () { //清理菜单类 add_filter('nav_menu_css_class', function ($var) { return is_array($var) ? array_intersect($var, ['current-menu-item', 'menu-item', 'menu-item-has-children']) : ''; -} - , 100, 1); +}, 100, 1); //移除前台加载jquery-migrate function gdk_disable_migrate($scripts) @@ -183,12 +182,12 @@ function gdk_disable_migrate($scripts) add_action('wp_default_scripts', 'gdk_disable_migrate'); //移除 WordPress 标记 -add_filter('the_generator', function () {return '';}); +add_filter('the_generator', function () {return ''; }); //移除标题中的空字符 -add_filter('wp_title', function ($title) {return trim($title);}); +add_filter('wp_title', function ($title) {return trim($title); }); -/** 开始关闭WordPress更新 **/ +// 开始关闭WordPress更新 if (gdk_option('gdk_diasble_wp_update')) { add_filter('automatic_updater_disabled', '__return_true'); // 彻底关闭自动更新 remove_action('init', 'wp_schedule_update_checks'); // 关闭更新检查定时作业 @@ -205,9 +204,9 @@ if (gdk_option('gdk_diasble_wp_update')) { remove_action('load-update.php', 'wp_update_themes'); remove_action('load-update-core.php', 'wp_update_themes'); remove_action('admin_init', '_maybe_update_themes'); - add_filter('pre_site_transient_update_core', function () {return null;}); - add_filter('pre_site_transient_update_plugins', function () {return null;}); - add_filter('pre_site_transient_update_themes', function () {return null;}); + add_filter('pre_site_transient_update_core', function () {return null; }); + add_filter('pre_site_transient_update_plugins', function () {return null; }); + add_filter('pre_site_transient_update_themes', function () {return null; }); } add_action('wp_before_admin_bar_render', function () { @@ -244,8 +243,10 @@ function ds_disable_core_privacy_tools($caps, $cap) case 'erase_others_personal_data': case 'manage_privacy_options': $caps[] = 'do_not_allow'; + break; } + return $caps; } @@ -255,6 +256,7 @@ function gdk_remove_dns($hints, $relation_type) if ('dns-prefetch' === $relation_type) { return array_diff(wp_dependencies_unique_hosts(), $hints); } + return $hints; } add_filter('wp_resource_hints', 'gdk_remove_dns', 10, 2); @@ -277,10 +279,10 @@ if (gdk_option('gdk_disable_emojis')) { function gdk_disable_emojis_tinymce($plugins) { if (is_array($plugins)) { - return array_diff($plugins, array('wpemoji')); + return array_diff($plugins, ['wpemoji']); } - return array(); + return []; } } @@ -305,16 +307,18 @@ if (!defined('WP_POST_REVISIONS')) { //前台禁用dashicon和editor if (gdk_option('gdk_disable_dashicons')) { - add_action('init', function () { - if (!is_user_logged_in()) { - wp_deregister_style('dashicons'); - wp_register_style('dashicons', false); - wp_enqueue_style('dashicons', ''); - wp_deregister_style('editor-buttons'); - wp_register_style('editor-buttons', false); - wp_enqueue_style('editor-buttons', ''); + add_action( + 'init', + function () { + if (!is_user_logged_in()) { + wp_deregister_style('dashicons'); + wp_register_style('dashicons', false); + wp_enqueue_style('dashicons', ''); + wp_deregister_style('editor-buttons'); + wp_register_style('editor-buttons', false); + wp_enqueue_style('editor-buttons', ''); + } } - } ); } @@ -329,15 +333,18 @@ add_action('wp_dashboard_setup', 'gdk_dweandw_remove', 20); //国内更新WordPress加速 if (gdk_option('gdk_porxy_update') && !gdk_option('gdk_diasble_wp_update')) { - add_filter('site_transient_update_core', function ($value) { - foreach ($value->updates as &$update) { - if ($update->locale == 'zh_CN') { - $update->download = 'http://cn.wp101.net/latest-zh_CN.zip'; - $update->packages->full = 'http://cn.wp101.net/latest-zh_CN.zip'; + add_filter( + 'site_transient_update_core', + function ($value) { + foreach ($value->updates as &$update) { + if ('zh_CN' == $update->locale) { + $update->download = 'http://cn.wp101.net/latest-zh_CN.zip'; + $update->packages->full = 'http://cn.wp101.net/latest-zh_CN.zip'; + } } + + return $value; } - return $value; - } ); } @@ -345,14 +352,15 @@ if (gdk_option('gdk_porxy_update') && !gdk_option('gdk_diasble_wp_update')) { if (gdk_option('gdk_upload_rename')) { function gdk_upload_rename($file) { - $info = pathinfo($file['name']); - $ext = $info['extension']; + $info = pathinfo($file['name']); + $ext = $info['extension']; $ignore_exts = ['zip', 'rar', '7z']; //被忽略的文件格式 if (!array_key_exists($ext, $ignore_exts)) { - $filedate = date('YmdHis') . mt_rand(100, 999); - $file['name'] = $filedate . '.' . $ext; + $filedate = date('YmdHis').mt_rand(100, 999); + $file['name'] = $filedate.'.'.$ext; } + return $file; } add_filter('wp_handle_upload_prefilter', 'gdk_upload_rename'); @@ -361,12 +369,12 @@ if (gdk_option('gdk_upload_rename')) { // 禁用自动生成的图片尺寸 function gdk_disable_image_sizes($sizes) { - unset($sizes['thumbnail']); // disable thumbnail size - unset($sizes['medium']); // disable medium size - unset($sizes['large']); // disable large size - unset($sizes['medium_large']); // disable medium-large size - unset($sizes['1536x1536']); // disable 2x medium-large size - unset($sizes['2048x2048']); // disable 2x large size + unset($sizes['thumbnail'], $sizes['medium'], $sizes['large'], $sizes['medium_large'], $sizes['1536x1536'], $sizes['2048x2048']); // disable thumbnail size + // disable medium size + // disable large size + // disable medium-large size + // disable 2x medium-large size + // disable 2x large size return $sizes; } add_action('intermediate_image_sizes_advanced', 'gdk_disable_image_sizes'); @@ -385,8 +393,9 @@ function gdk_redirect_single_search_result() { if (is_search()) { global $wp_query; - if ($wp_query->post_count == 1) { + if (1 == $wp_query->post_count) { wp_redirect(get_permalink($wp_query->posts['0']->ID)); + exit(); } } @@ -397,7 +406,8 @@ add_action('template_redirect', 'gdk_redirect_single_search_result'); function gdk_redirect_search() { if (is_search() && !empty($_GET['s'])) { - wp_redirect(home_url("/search/") . urlencode(get_query_var('s'))); + wp_redirect(home_url('/search/').urlencode(get_query_var('s'))); + exit(); } } @@ -420,7 +430,7 @@ if (gdk_option('gdk_disable_restapi')) { status_header(405); wp_die('{"code":"rest_api_disabled","message":"REST API services are disabled on this site.","data":{"status":405}}'); } -// Remove the REST API endpoint. + // Remove the REST API endpoint. remove_action('rest_api_init', 'wp_oembed_register_route'); } @@ -449,76 +459,80 @@ function gdk_custom_footer_code() add_action('wp_footer', 'gdk_custom_footer_code', 400); if (gdk_option('gdk_no_category')) { - if (!function_exists('gdk_no_category_base_refresh_rules')): + if (!function_exists('gdk_no_category_base_refresh_rules')) { add_action('load-themes.php', 'gdk_no_category_base_refresh_rules'); add_action('created_category', 'gdk_no_category_base_refresh_rules'); add_action('edited_category', 'gdk_no_category_base_refresh_rules'); add_action('delete_category', 'gdk_no_category_base_refresh_rules'); function gdk_no_category_base_refresh_rules() - { + { global $wp_rewrite; $wp_rewrite->flush_rules(); } add_action('init', 'gdk_no_category_base_permastruct'); function gdk_no_category_base_permastruct() - { + { global $wp_rewrite; $wp_rewrite->extra_permastructs['category']['struct'] = '%category%'; } // Add our custom category rewrite rules add_filter('category_rewrite_rules', 'gdk_no_category_base_rewrite_rules'); function gdk_no_category_base_rewrite_rules($category_rewrite) - { + { //var_dump($category_rewrite); // For Debugging - $category_rewrite = array(); - $categories = get_categories(array('hide_empty' => false)); + $category_rewrite = []; + $categories = get_categories(['hide_empty' => false]); foreach ($categories as $category) { $gdk_category = $category->slug; - if ($category->parent == $category->cat_ID) // recursive recursion - { + if ($category->parent == $category->cat_ID) { // recursive recursion $category->parent = 0; - } elseif ($category->parent != 0) { - $gdk_category = get_category_parents($category->parent, false, '/', true) . $gdk_category; + } elseif (0 != $category->parent) { + $gdk_category = get_category_parents($category->parent, false, '/', true).$gdk_category; + } + + $category_rewrite['('.$gdk_category.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]'; + $category_rewrite['('.$gdk_category.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]'; + $category_rewrite['('.$gdk_category.')/?$'] = 'index.php?category_name=$matches[1]'; + } + // Redirect support from Old Category Base + global $wp_rewrite; + $old_category_base = get_option('category_base') ? get_option('category_base') : 'category'; + $old_category_base = trim($old_category_base, '/'); + $category_rewrite[$old_category_base.'/(.*)$'] = 'index.php?category_redirect=$matches[1]'; + + return $category_rewrite; + } + // Add 'category_redirect' query variable + add_filter('query_vars', 'gdk_no_category_base_query_vars'); + function gdk_no_category_base_query_vars($public_query_vars) + { + $public_query_vars[] = 'category_redirect'; + + return $public_query_vars; + } + + add_filter('request', 'gdk_no_category_base_request'); + function gdk_no_category_base_request($query_vars) + { + if (isset($query_vars['category_redirect'])) { + $catlink = trailingslashit(get_option('home')).user_trailingslashit($query_vars['category_redirect'], 'category'); + status_header(301); + header("Location: {$catlink}"); + + exit(); } - $category_rewrite['(' . $gdk_category . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]'; - $category_rewrite['(' . $gdk_category . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]'; - $category_rewrite['(' . $gdk_category . ')/?$'] = 'index.php?category_name=$matches[1]'; + return $query_vars; } - // Redirect support from Old Category Base - global $wp_rewrite; - $old_category_base = get_option('category_base') ? get_option('category_base') : 'category'; - $old_category_base = trim($old_category_base, '/'); - $category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]'; - return $category_rewrite; } - // Add 'category_redirect' query variable - add_filter('query_vars', 'gdk_no_category_base_query_vars'); - function gdk_no_category_base_query_vars($public_query_vars) - { - $public_query_vars[] = 'category_redirect'; - return $public_query_vars; - } - - add_filter('request', 'gdk_no_category_base_request'); - function gdk_no_category_base_request($query_vars) - { - if (isset($query_vars['category_redirect'])) { - $catlink = trailingslashit(get_option('home')) . user_trailingslashit($query_vars['category_redirect'], 'category'); - status_header(301); - header("Location: $catlink"); - exit(); - } - return $query_vars; - } - endif; } //站长评论邮件添加评论链接 function gdk_notify_admin($notify_message, $comment_ID) { $notify = $notify_message; - $notify .= '快速回复此评论: ' . admin_url("edit-comments.php") . '#comment-' . $comment_ID; + $notify .= '快速回复此评论: '.admin_url('edit-comments.php').'#comment-'.$comment_ID; + return $notify; } add_filter('comment_notification_text', 'gdk_notify_admin', 10, 2); @@ -527,8 +541,9 @@ add_filter('comment_notification_text', 'gdk_notify_admin', 10, 2); function gdk_comment_add_at($comment_text, $comment = '') { if ($comment->comment_parent > 0) { - $comment_text = '@' . get_comment_author($comment->comment_parent) . ' ' . $comment_text; + $comment_text = '@'.get_comment_author($comment->comment_parent).' '.$comment_text; } + return $comment_text; } add_filter('comment_text', 'gdk_comment_add_at', 20, 2); @@ -539,6 +554,7 @@ function gdk_search_filter_page($query) if ($query->is_search && !$query->is_admin) { $query->set('post_type', 'post'); } + return $query; } add_filter('pre_get_posts', 'gdk_search_filter_page'); diff --git a/functions/rewrite.php b/functions/rewrite.php index 5ac842b..1143c8d 100644 --- a/functions/rewrite.php +++ b/functions/rewrite.php @@ -1,6 +1,6 @@ get_page_permastruct(), '.html')) { - $wp_rewrite->page_structure = $wp_rewrite->page_structure . '.html'; + $wp_rewrite->page_structure = $wp_rewrite->page_structure.'.html'; } } add_action('init', 'gdk_page_permalink', -1); @@ -42,9 +42,9 @@ function gdk_custom_cancel_redirect($redirect_url) $api_daohang = get_query_var('daohang'); if (!empty($api_sitemap) || !empty($api_daohang)) { return false; - } else { - return $redirect_url; } + + return $redirect_url; } add_filter('redirect_canonical', 'gdk_custom_cancel_redirect'); @@ -55,6 +55,7 @@ function gdk_public_query_vars($public_query_vars) $public_query_vars[] = 'dl'; $public_query_vars[] = 'sitemap'; $public_query_vars[] = 'daohang'; + return $public_query_vars; } add_action('query_vars', 'gdk_public_query_vars'); diff --git a/functions/security.php b/functions/security.php index 0dccf1b..aae21f8 100644 --- a/functions/security.php +++ b/functions/security.php @@ -7,19 +7,19 @@ function gdk_prevent_requst() { global $user_ID; if (!current_user_can('level_10')) { - if (strlen($_SERVER['REQUEST_URI']) > 255 || - stripos($_SERVER['REQUEST_URI'], 'eval(') || - stripos($_SERVER['REQUEST_URI'], 'CONCAT') || - stripos($_SERVER['REQUEST_URI'], 'UNION+SELECT') || - stripos($_SERVER['REQUEST_URI'], 'GLOBALS(') || - stripos($_SERVER['REQUEST_URI'], '_REQUEST') || - stripos($_SERVER['REQUEST_URI'], '/localhost') || - stripos($_SERVER['QUERY_STRING'], '127.0.0.1') || - stripos($_SERVER['REQUEST_URI'], '/config.') || - stripos($_SERVER['REQUEST_URI'], 'wp-config.') || - stripos($_SERVER['REQUEST_URI'], 'etc/passwd') || - stripos($_SERVER['REQUEST_URI'], '<') || - stripos($_SERVER['REQUEST_URI'], 'base64')) { + if (strlen($_SERVER['REQUEST_URI']) > 255 + || stripos($_SERVER['REQUEST_URI'], 'eval(') + || stripos($_SERVER['REQUEST_URI'], 'CONCAT') + || stripos($_SERVER['REQUEST_URI'], 'UNION+SELECT') + || stripos($_SERVER['REQUEST_URI'], 'GLOBALS(') + || stripos($_SERVER['REQUEST_URI'], '_REQUEST') + || stripos($_SERVER['REQUEST_URI'], '/localhost') + || stripos($_SERVER['QUERY_STRING'], '127.0.0.1') + || stripos($_SERVER['REQUEST_URI'], '/config.') + || stripos($_SERVER['REQUEST_URI'], 'wp-config.') + || stripos($_SERVER['REQUEST_URI'], 'etc/passwd') + || stripos($_SERVER['REQUEST_URI'], '<') + || stripos($_SERVER['REQUEST_URI'], 'base64')) { @header('HTTP/1.1 403 Forbidden'); @header('Status: 403 Forbidden'); @header('Connection: Close'); @@ -43,12 +43,13 @@ if (gdk_option('gdk_disable_trackbacks')) { function gdk_xmlrpc_methods($methods) { unset($methods['system.multicall']); - $methods['pingback.ping'] = '__return_false'; + $methods['pingback.ping'] = '__return_false'; $methods['pingback.extensions.getPingbacks'] = '__return_false'; + return $methods; } -//阻止站内PingBack + //阻止站内PingBack function gdk_noself_ping(&$links) { $home = home_url(); @@ -57,12 +58,11 @@ if (gdk_option('gdk_disable_trackbacks')) { unset($links[$l]); } } - } add_action('pre_ping', 'gdk_noself_ping'); -//禁用 pingbacks, enclosures, trackbacks + //禁用 pingbacks, enclosures, trackbacks remove_action('do_pings', 'do_all_pings', 10); -//去掉 _encloseme 和 do_ping 操作。 + //去掉 _encloseme 和 do_ping 操作。 remove_action('publish_post', '_publish_post_hook', 5); } @@ -73,10 +73,11 @@ if (!function_exists('security_stop_user_enumeration')) { { if (preg_match('/\?author=([0-9]*)(\/*)/i', $request)) { wp_redirect(get_site_url(), 301); - die(); - } else { - return $redirect; + + exit(); } + + return $redirect; } } @@ -84,15 +85,16 @@ if (!function_exists('security_stop_user_enumeration')) { if (!class_exists('GDK_Limit_Login_Attempts')) { class GDK_Limit_Login_Attempts { + public $transient_name = 'attempted_login'; //Transient used private $__failed_login_limit; //登录失败的次数限制 private $__lockout_duration; //暂停登陆时间 - public $transient_name = 'attempted_login'; //Transient used + public function __construct($config = null) { $this->failed_login_limit = $config['failed_login_limit']; - $this->lockout_duration = $config['lockout_duration']; - add_filter('authenticate', array($this, 'check_attempted_login'), 30, 3); - add_action('wp_login_failed', array($this, 'login_failed'), 10, 1); + $this->lockout_duration = $config['lockout_duration']; + add_filter('authenticate', [$this, 'check_attempted_login'], 30, 3); + add_action('wp_login_failed', [$this, 'login_failed'], 10, 1); } public function check_attempted_login($user, $username, $password) @@ -100,12 +102,13 @@ if (!class_exists('GDK_Limit_Login_Attempts')) { if (get_transient($this->transient_name)) { $datas = get_transient($this->transient_name); if ($datas['tried'] >= $this->failed_login_limit) { - $until = get_option('_transient_timeout_' . $this->transient_name); - $time = $this->when($until); + $until = get_option('_transient_timeout_'.$this->transient_name); + $time = $this->when($until); //Display error message to the user when limit is reached return new WP_Error('too_many_tried', sprintf(esc_attr('ERROR:您已触发登陆安全保护,请在 %1$s 后再次尝试.'), $time)); } } + return $user; } @@ -113,13 +116,12 @@ if (!class_exists('GDK_Limit_Login_Attempts')) { { if (get_transient($this->transient_name)) { $datas = get_transient($this->transient_name); - $datas['tried']++; + ++$datas['tried']; if ($datas['tried'] <= $this->failed_login_limit) { set_transient($this->transient_name, $datas, $this->lockout_duration); } - } else { - $datas = array('tried' => 1); + $datas = ['tried' => 1]; set_transient($this->transient_name, $datas, $this->lockout_duration); } } @@ -131,13 +133,13 @@ if (!class_exists('GDK_Limit_Login_Attempts')) { } $right_now = time(); - $diff = abs($right_now - $time); - $second = 1; - $minute = $second * 60; - $hour = $minute * 60; - $day = $hour * 24; + $diff = abs($right_now - $time); + $second = 1; + $minute = $second * 60; + $hour = $minute * 60; + $day = $hour * 24; if ($diff < $minute) { - return floor($diff / $second) . ' ' . esc_attr('秒'); + return floor($diff / $second).' '.esc_attr('秒'); } if ($diff < $minute * 2) { @@ -145,21 +147,21 @@ if (!class_exists('GDK_Limit_Login_Attempts')) { } if ($diff < $hour) { - return floor($diff / $minute) . ' ' . esc_attr('分钟'); + return floor($diff / $minute).' '.esc_attr('分钟'); } if ($diff < $hour * 2) { return esc_attr('about 1 hour'); } - return floor($diff / $hour) . ' ' . esc_attr('小时'); + return floor($diff / $hour).' '.esc_attr('小时'); } } } //Enable it: $LLA_config = [ 'failed_login_limit' => gdk_option('gdk_failed_login_limit'), // 登录失败的次数限制 - 'lockout_duration' => gdk_option('gdk_lockout_duration'), // 暂停登陆时间 + 'lockout_duration' => gdk_option('gdk_lockout_duration'), // 暂停登陆时间 ]; if (gdk_option('gdk_lock_login')) { new GDK_Limit_Login_Attempts($LLA_config); @@ -174,6 +176,7 @@ function gdk_disable_login_errors($error) // For security reason return esc_attr('Access Denied!'); } + return $error; } //add_filter('login_errors', 'gdk_disable_login_errors'); @@ -182,7 +185,7 @@ function gdk_disable_login_errors($error) function gdk_maintenance_mode() { if (!current_user_can('edit_themes') || !is_user_logged_in()) { - wp_die('网站维护中ing, 没事儿您就别来啦……', 'Maintenance - Could you please not disturb me ', array('response' => '503')); + wp_die('网站维护中ing, 没事儿您就别来啦……', 'Maintenance - Could you please not disturb me ', ['response' => '503']); } } if (gdk_option('gdk_maintenance_mode')) { @@ -194,7 +197,7 @@ if (gdk_option('gdk_fuck_spam')) { //拦截无来路的评论 function gdk_comment_check_referrer() { - if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == '') { + if (!isset($_SERVER['HTTP_REFERER']) || '' == $_SERVER['HTTP_REFERER']) { wp_die(esc_attr('Please enable referrers in your browser!')); } } @@ -214,17 +217,18 @@ if (gdk_option('gdk_fuck_spam')) { $pattern = '/[一-龥]/u'; // 禁止全英文评论 if (!preg_match($pattern, $commentdata['comment_content'])) { - gdk_die("您的评论中必须包含汉字!"); + gdk_die('您的评论中必须包含汉字!'); } $pattern = '/[あ-んア-ン]/u'; // 禁止日文评论 if (preg_match($pattern, $commentdata['comment_content'])) { - gdk_die("评论禁止包含日文!"); + gdk_die('评论禁止包含日文!'); } //屏蔽评论里面黑名单内容 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; } add_filter('preprocess_comment', 'gdk_comment_lang'); @@ -232,42 +236,43 @@ if (gdk_option('gdk_fuck_spam')) { //隐藏用户名字 if (gdk_option('gdk_hide_user_name')) { + // 文本加密 function gdk_text_encrypt($string, $operation, $key = '') { - $string = $operation == 'D' ? str_replace(array('!', '-', '_'), array('=', '+', '/'), $string) : $string; - $key = md5($key); - $key_length = strlen($key); - $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string; + $string = 'D' == $operation ? str_replace(['!', '-', '_'], ['=', '+', '/'], $string) : $string; + $key = md5($key); + $key_length = strlen($key); + $string = 'D' == $operation ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string; $string_length = strlen($string); - $rndkey = $box = array(); - $result = ''; - for ($i = 0; $i <= 255; $i++) { + $rndkey = $box = []; + $result = ''; + for ($i = 0; $i <= 255; ++$i) { $rndkey[$i] = ord($key[$i % $key_length]); - $box[$i] = $i; + $box[$i] = $i; } - for ($j = $i = 0; $i < 256; $i++) { - $j = ($j + $box[$i] + $rndkey[$i]) % 256; - $tmp = $box[$i]; + for ($j = $i = 0; $i < 256; ++$i) { + $j = ($j + $box[$i] + $rndkey[$i]) % 256; + $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } - for ($a = $j = $i = 0; $i < $string_length; $i++) { - $a = ($a + 1) % 256; - $j = ($j + $box[$a]) % 256; - $tmp = $box[$a]; + for ($a = $j = $i = 0; $i < $string_length; ++$i) { + $a = ($a + 1) % 256; + $j = ($j + $box[$a]) % 256; + $tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp; $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } - if ($operation == 'D') { - if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) { + if ('D' == $operation) { + if (substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) { return substr($result, 8); - } else { - return ''; } - } else { - return str_replace(array('=', '+', '/'), array('!', '-', '_'), base64_encode($result)); + + return ''; } + + return strtr(base64_encode($result), '=+/', '!-_'); } function gdk_custom_author_link_request($query_vars) @@ -275,11 +280,12 @@ if (gdk_option('gdk_hide_user_name')) { if (array_key_exists('author_name', $query_vars)) { global $wpdb; $author_id = gdk_text_encrypt($query_vars['author_name'], 'D', AUTH_KEY); - if ($author_id) { + if (isset($author_id)) { $query_vars['author'] = $author_id; unset($query_vars['author_name']); } } + return $query_vars; } add_filter('request', 'gdk_custom_author_link_request'); @@ -287,14 +293,13 @@ if (gdk_option('gdk_hide_user_name')) { function gdk_custom_author_link($link, $author_id) { global $wp_rewrite; - $author_id = (int)$author_id; - $link = $wp_rewrite->get_author_permastruct(); + $author_id = (int) $author_id; + $link = $wp_rewrite->get_author_permastruct(); if (empty($link)) { - $file = home_url('/'); - $link = $file . '?author=' . gdk_text_encrypt($author_id, 'E', AUTH_KEY); + $link = home_url('/').'?author='.gdk_text_encrypt($author_id, 'E', AUTH_KEY); } else { $link = str_replace('%author%', gdk_text_encrypt($author_id, 'E', AUTH_KEY), $link); - $link = home_url() . user_trailingslashit($link); + $link = home_url().user_trailingslashit($link); } return $link; @@ -305,6 +310,7 @@ if (gdk_option('gdk_hide_user_name')) { function gdk_custom_rest_prepare_user($response, $user, $request) { $response->data['slug'] = gdk_text_encrypt($user->ID, 'E', AUTH_KEY); + return $response; } add_filter('rest_prepare_user', 'gdk_custom_rest_prepare_user', 10, 3); @@ -312,20 +318,17 @@ if (gdk_option('gdk_hide_user_name')) { //记录登陆失败发邮件 if (gdk_option('gdk_login_email')) { -add_action('wp_authenticate', 'log_login', 10, 2); + add_action('wp_authenticate', 'gdk_log_login', 10, 2); } -function log_login($username, $password) +function gdk_log_login($username, $password) { - - if (!empty($username) && !empty($password)) { - + if (isset($username, $password)) { $check = wp_authenticate_username_password(null, $username, $password); if (is_wp_error($check)) { - - $ua = getBrowser(); + $ua = gdk_getBrowser(); $agent = $ua['name']; - $referrer = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : $_SERVER['PHP_SELF']; + $referrer = $_SERVER['HTTP_REFERER'] ?? $_SERVER['PHP_SELF']; if (strstr($referrer, 'wp-login')) { $ref = 'wp-login.php'; } @@ -336,40 +339,36 @@ function log_login($username, $password) $contact_errors = false; // get the posted data - $name = get_bloginfo('name'); + $name = get_bloginfo('name'); $email_address = get_bloginfo('admin_email'); // write the email content $header = "MIME-Version: 1.0\n"; $header .= "Content-Type: text/html; charset=utf-8\n"; - $header .= "From: $name <$email_address>\n"; + $header .= "From: {$name} <{$email_address}>\n"; - $message = "" . $name . " 登陆失败提醒
" . PHP_EOL; - - $message .= "Browser: " . $agent . "
" . PHP_EOL; - $message .= "OS: " . $ua['platform'] . "
" . PHP_EOL; - $message .= 'IP: '. gdk_get_ip() . '
' . PHP_EOL; - $message .= "Date: " . date('Y-m-d H:i:s') . "
" . PHP_EOL; - $message .= "Referrer: " . $referrer . "
" . PHP_EOL; - $message .= "User Agent: " . $ua['userAgent'] . "
" . PHP_EOL; - $message .= "Username: " . $username . "
" . PHP_EOL; - $message .= "Password: " . $password . "
" . PHP_EOL; - - $subject = "登陆失败提醒 - " . $name; - $to = $email_address; - $mail_content = mail_temp($subject, $message , home_url(), $name ); - if (!empty($to)) { + $message = "".$name.' 登陆失败提醒
'.PHP_EOL; + $message .= 'Browser: '.$agent.'
'.PHP_EOL; + $message .= 'OS: '.$ua['platform'].'
'.PHP_EOL; + $message .= 'IP: '.gdk_get_ip().'
'.PHP_EOL; + $message .= 'Date: '.date('Y-m-d H:i:s').'
'.PHP_EOL; + $message .= 'Referrer: '.$referrer.'
'.PHP_EOL; + $message .= 'User Agent: '.$ua['userAgent'].'
'.PHP_EOL; + $message .= 'Username: '.$username.'
'.PHP_EOL; + $message .= 'Password: '.$password.'
'.PHP_EOL; + $subject = '登陆失败提醒 - '.$name; + $mail_content = gdk_mail_temp($subject, $message, home_url(), $name); + if (isset($email_address)) { // send the email using wp_mail() - if (!wp_mail($to, $subject, $mail_content , $header)) { + if (!wp_mail($email_address, $subject, $mail_content, $header)) { $contact_errors = true; } } - } } } -//ban yonghu +//封禁用户 function gdk_edit_user_profile($user) { if (!current_user_can('edit_users')) { @@ -378,20 +377,19 @@ function gdk_edit_user_profile($user) if (get_current_user_id() == $user->ID) { return; - } - - ?> - - - - - -
封禁用户 - -
- + + + + + +
封禁用户 + +
+ID, false)) { return new WP_Error( - 'gdk_banned', 'ERROR: 此账号已被封禁.' + 'gdk_banned', + 'ERROR: 此账号已被封禁.' ); } + return $user; } add_action('edit_user_profile', 'gdk_edit_user_profile'); add_action('edit_user_profile_update', 'gdk_edit_user_profile_update'); -add_filter('wp_authenticate_user', 'gdk_authenticate_user', 10, 2); \ No newline at end of file +add_filter('wp_authenticate_user', 'gdk_authenticate_user', 10, 2); diff --git a/functions/seo.php b/functions/seo.php index 53ec547..c3927e5 100644 --- a/functions/seo.php +++ b/functions/seo.php @@ -2,8 +2,9 @@ //加载网站地图xml if (gdk_option('gdk_sitemap_xml')) { - include GDK_ROOT_PATH . 'public/sitemap-xml.php'; - include GDK_ROOT_PATH . 'public/sitemap.php'; + include GDK_ROOT_PATH.'public/sitemap-xml.php'; + + include GDK_ROOT_PATH.'public/sitemap.php'; } // 屏蔽蜘蛛爬取作者页面 @@ -23,11 +24,12 @@ if (gdk_option('gdk_robots')) { function gdk_robots_txt($robotext) { if (gdk_option('gdk_sitemap_xml')) { - $sitemap = 'Sitemap: ' . home_url('/sitemap.xml'); + $sitemap = 'Sitemap: '.home_url('/sitemap.xml'); } else { $sitemap = ''; } - $robotext = "User-agent: * + + return "User-agent: * Disallow: /wp-admin/ Disallow: /wp-content/plugins/ Disallow: /wp-includes/ @@ -37,7 +39,6 @@ Disallow: /*/feed Disallow: /attachment/ Disallow: /wp-content/themes/ {$sitemap}"; - return $robotext; } } @@ -48,14 +49,15 @@ if (gdk_option('gdk_tag_link')) { $post_tags = get_the_tags(); if ($post_tags) { foreach ($post_tags as $tag) { - $link = get_tag_link($tag->term_id); - $keyword = $tag->name; + $link = get_tag_link($tag->term_id); + $keyword = $tag->name; $cleankeyword = stripslashes($keyword); - $url = '' . addcslashes($cleankeyword, '$') . ''; - $regEx = '\'(?!((<.*?)|(]*?)>)|([^>]*?))\'s'; - $content = preg_replace($regEx, $url, $content, gdk_option('gdk_tag_num') ?? 5); + $url = ''.addcslashes($cleankeyword, '$').''; + $regEx = '\'(?!((<.*?)|(]*?)>)|([^>]*?))\'s'; + $content = preg_replace($regEx, $url, $content, gdk_option('gdk_tag_num') ?? 5); } } + return $content; } add_filter('the_content', 'gdk_tag_link', 1); @@ -71,13 +73,14 @@ if (gdk_option('gdk_nofollow')) { } function gdk_nofollow_callback($matches) { - $link = $matches[0]; + $link = $matches[0]; $site_link = get_bloginfo('url'); - if (strpos($link, 'rel') === false) { - $link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link); - } elseif (preg_match("%href=\S(?!$site_link)%i", $link)) { + if (false === strpos($link, 'rel')) { + $link = preg_replace("%(href=\\S(?!{$site_link}))%i", 'rel="nofollow" $1', $link); + } elseif (preg_match("%href=\\S(?!{$site_link})%i", $link)) { $link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link); } + return $link; } } @@ -87,35 +90,34 @@ if (gdk_option('gdk_baidu_push')) { function gdk_baidu_submit($post_ID) { global $post; - $bd_submit_site = get_bloginfo('url'); + $bd_submit_site = get_bloginfo('url'); $bd_submit_token = gdk_option('gdk_baidu_token'); if (empty($post_ID) || empty($bd_submit_site) || empty($bd_submit_token)) { return; } - if (get_post_meta($post_ID, 'gdk_baidu_submit', true) == 1) { + if (1 == get_post_meta($post_ID, 'gdk_baidu_submit', true)) { return; } - $url = get_permalink($post_ID); - $api = $api = 'http://data.zz.baidu.com/urls?site=' . $bd_submit_site . '&token=' . $bd_submit_token; + $url = get_permalink($post_ID); + $api = $api = 'http://data.zz.baidu.com/urls?site='.$bd_submit_site.'&token='.$bd_submit_token; $status = $post->post_status; - if ($status != '' && $status != 'publish') { - $request = new WP_Http; - $result = $request->request($api, array( - 'method' => 'POST', - 'body' => $url, + if ('' != $status && 'publish' != $status) { + $request = new WP_Http(); + $result = $request->request($api, [ + 'method' => 'POST', + 'body' => $url, 'headers' => 'Content-Type: text/plain', - )); - if (is_array($result) && !is_wp_error($result) && $result['response']['code'] == '200') { - error_log('baidu_submit_result:' . $result['body']); + ]); + if (is_array($result) && !is_wp_error($result) && '200' == $result['response']['code']) { + error_log('baidu_submit_result:'.$result['body']); $result = json_decode($result['body'], true); } if (array_key_exists('success', $result)) { add_post_meta($post_ID, 'gdk_baidu_submit', 1, true); } } - } add_action('publish_post', 'gdk_baidu_submit', 0); add_action('wp_footer', 'gdk_baidu_auto_push', 500); @@ -145,9 +147,10 @@ if (gdk_option('gdk_seo_img')) { function gdk_imagesalt($content) { global $post; - $pattern = "//i"; - $replacement = ''; - $content = preg_replace($pattern, $replacement, $content); + $pattern = "//i"; + $replacement = ''; + $content = preg_replace($pattern, $replacement, $content); + return $content; } add_filter('the_content', 'gdk_imagesalt'); @@ -157,10 +160,11 @@ if (gdk_option('gdk_seo_img')) { preg_match_all('//', $content, $images); if (!is_null($images)) { foreach ($images[1] as $index => $value) { - $new_img = str_replace('ID)) { foreach (get_the_tags($post->ID) as $tag) { - $keywords .= $tag->name . ', '; + $keywords .= $tag->name.', '; } - } foreach (get_the_category($post->ID) as $category) { - $keywords .= $category->cat_name . ', '; + $keywords .= $category->cat_name.', '; } $keywords = substr_replace($keywords, '', -2); @@ -203,7 +206,7 @@ function gdk_keywords() $keywords = trim(wp_title('', false)); } if ($keywords) { - echo "\n"; + echo "\n"; } } add_action('wp_head', 'gdk_keywords'); @@ -213,48 +216,47 @@ function gdk_description() { global $s, $post; $description = ''; - $blog_name = get_bloginfo('name'); - $excerpt = $post->post_excerpt; + $blog_name = get_bloginfo('name'); + $excerpt = $post->post_excerpt; if (is_singular()) { if (!empty($excerpt)) { $text = $excerpt; } else { $text = strip_shortcodes($post->post_content); } - $description = trim(str_replace(array( + $description = trim(str_replace([ "\r\n", "\r", "\n", - " ", - " ", - ), " ", str_replace("\"", "'", strip_tags($text)))); + ' ', + ' ', + ], ' ', str_replace('"', "'", strip_tags($text)))); if (!($description)) { - $description = $blog_name . "-" . trim(wp_title('', false)); + $description = $blog_name.'-'.trim(wp_title('', false)); } - } elseif (is_home() || is_front_page()) { $description = gdk_option('gdk_description'); // 首頁要自己加 } elseif (is_tag()) { if (in_string(tag_description(), '@@')) { - $description = $blog_name . "'" . gdk_term_meta('tag', 'des') . "'"; + $description = $blog_name."'".gdk_term_meta('tag', 'des')."'"; } else { - $description = $blog_name . "'" . single_tag_title('', false) . "'"; + $description = $blog_name."'".single_tag_title('', false)."'"; } } elseif (is_category()) { if (in_string(category_description(), '@@')) { - $description = $blog_name . "'" . trim(strip_tags(gdk_term_meta('tag', 'des'))); + $description = $blog_name."'".trim(strip_tags(gdk_term_meta('tag', 'des'))); } else { - $description = $blog_name . "'" . trim(strip_tags(category_description())); + $description = $blog_name."'".trim(strip_tags(category_description())); } } elseif (is_archive()) { - $description = $blog_name . "'" . trim(wp_title('', false)) . "'"; + $description = $blog_name."'".trim(wp_title('', false))."'"; } elseif (is_search()) { - $description = $blog_name . ": '" . esc_html($s, 1) . "' 的搜索結果"; + $description = $blog_name.": '".esc_html($s, 1)."' 的搜索結果"; } else { - $description = $blog_name . "'" . trim(wp_title('', false)) . "'"; + $description = $blog_name."'".trim(wp_title('', false))."'"; } $description = mb_substr($description, 0, 220, 'utf-8'); - echo "\n"; + echo "\n"; } add_action('wp_head', 'gdk_description'); @@ -266,28 +268,28 @@ function meta_og() if (has_post_thumbnail($post->ID)) { $img_src = gdk_thumbnail_src(); } - $excerpt = strip_tags($post->post_content); + $excerpt = strip_tags($post->post_content); $excerpt_more = ''; if (strlen($excerpt) > 155) { - $excerpt = substr($excerpt, 0, 155); + $excerpt = substr($excerpt, 0, 155); $excerpt_more = ' ...'; } - $excerpt = str_replace('"', '', $excerpt); - $excerpt = str_replace("'", '', $excerpt); + $excerpt = str_replace('"', '', $excerpt); + $excerpt = str_replace("'", '', $excerpt); $excerptwords = preg_split('/[\n\r\t ]+/', $excerpt, -1, PREG_SPLIT_NO_EMPTY); array_pop($excerptwords); - $excerpt = implode(' ', $excerptwords) . $excerpt_more; - ?> - - - - - - - - - + + + + + + + + +ID); echo "' />\n"; - echo ""; + echo ''; } } -add_action('wp_head', 'gdk_canonical'); \ No newline at end of file +add_action('wp_head', 'gdk_canonical'); diff --git a/functions/server.php b/functions/server.php index c52e3ac..f0552f4 100644 --- a/functions/server.php +++ b/functions/server.php @@ -2,11 +2,11 @@ //百度收录提示 if (gdk_option('gdk_baidurecord_b') && function_exists('curl_init')) { - function baidu_check($url, $post_id) + function gdk_baidu_check($url, $post_id) { $baidu_record = get_post_meta($post_id, 'baidu_record', true); - if ($baidu_record != 1) { - $url = 'http://www.baidu.com/s?wd=' . $url; + if (1 != $baidu_record) { + $url = 'http://www.baidu.com/s?wd='.$url; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); @@ -14,51 +14,51 @@ if (gdk_option('gdk_baidurecord_b') && function_exists('curl_init')) { curl_close($curl); if (!strpos($rs, '没有找到该URL,您可以直接访问') && !strpos($rs, '很抱歉,没有找到与')) { update_post_meta($post_id, 'baidu_record', 1) || add_post_meta($post_id, 'baidu_record', 1, true); + return 1; - } else { - return 0; } - } else { - return 1; + + return 0; } + + return 1; } function baidu_record() { - global $wpdb; - $post_id = null === $post_id ? get_the_ID() : $post_id; - if (baidu_check(get_permalink($post_id), $post_id) == 1) { - echo '已收录'; + $post_id = get_the_ID() ?? null; + if (1 == gdk_baidu_check(get_permalink($post_id), $post_id)) { + echo '已收录'; } else { - echo '未收录'; + echo '未收录'; } } } //百度主动推送 if (gdk_option('gdk_sitemap_api')) { - function Git_Baidu_Submit($post_ID) + function gdk_Baidu_Submit($post_ID) { - if (get_post_meta($post_ID, 'gdk_baidu_submit', true) == 1) { + if (1 == get_post_meta($post_ID, 'gdk_baidu_submit', true)) { return; } - $url = get_permalink($post_ID); - $api = gdk_option('gdk_sitemap_api'); - $request = new WP_Http; - $result = $request->request($api, array( - 'method' => 'POST', - 'body' => $url, + $url = get_permalink($post_ID); + $api = gdk_option('gdk_sitemap_api'); + $request = new WP_Http(); + $result = $request->request($api, [ + 'method' => 'POST', + 'body' => $url, 'headers' => 'Content-Type: text/plain', - )); - if (is_array($result) && !is_wp_error($result) && $result['response']['code'] == '200') { - error_log('baidu_submit_result:' . $result['body']); + ]); + if (is_array($result) && !is_wp_error($result) && '200' == $result['response']['code']) { + error_log('baidu_submit_result:'.$result['body']); $result = json_decode($result['body'], true); } if (array_key_exists('success', $result)) { add_post_meta($post_ID, 'gdk_baidu_submit', 1, true); } } - add_action('publish_post', 'Git_Baidu_Submit', 0); + add_action('publish_post', 'gdk_Baidu_Submit', 0); } //强制微信登录 @@ -71,16 +71,17 @@ function force_weauth_login_url($login_url, $redirect, $force_reauth) if ($force_reauth) { $login_url = add_query_arg('reauth', '1', $login_url); } + return $login_url; -}if (gdk_option('gdk_weauth_oauth') && gdk_option('gdk_weauth_oauth_force')) { +} if (gdk_option('gdk_weauth_oauth') && gdk_option('gdk_weauth_oauth_force')) { add_filter('login_url', 'force_weauth_login_url', 10, 3); } //在登录框添加额外的微信登录 function weixin_login_button() { - echo '

微信登录


'; -}if (gdk_option('gdk_weauth_oauth')) { + echo '

微信登录


'; +} if (gdk_option('gdk_weauth_oauth')) { add_action('login_form', 'weixin_login_button'); } @@ -88,29 +89,30 @@ function weixin_login_button() if (gdk_option('gdk_Server') && !is_admin()) { function sc_send($comment_id) { - $text = '网站上有新的评论,请及时查看'; //微信推送信息标题 + $text = '网站上有新的评论,请及时查看'; //微信推送信息标题 $comment = get_comment($comment_id); - $desp = '' . $comment->comment_content . ' + $desp = ''.$comment->comment_content.' ***
-* 评论人 :' . get_comment_author($comment_id) . ' -* 文章标题 :' . get_the_title() . ' -* 文章链接 :' . get_the_permalink($comment->comment_post_ID) . ' +* 评论人 :'.get_comment_author($comment_id).' +* 文章标题 :'.get_the_title().' +* 文章链接 :'.get_the_permalink($comment->comment_post_ID).' '; //微信推送内容正文 - $key = gdk_option('gdk_Server_key'); - $postdata = http_build_query(array( + $key = gdk_option('gdk_Server_key'); + $postdata = http_build_query([ 'text' => $text, 'desp' => $desp, - )); - $opts = array( - 'http' => array( - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', + ]); + $opts = [ + 'http' => [ + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata, - ), - ); - $context = stream_context_create($opts); - return $result = file_get_contents('http://sc.ftqq.com/' . $key . '.send', false, $context); + ], + ]; + $context = stream_context_create($opts); + + return $result = file_get_contents('http://sc.ftqq.com/'.$key.'.send', false, $context); } add_action('comment_post', 'sc_send', 19, 2); } @@ -124,30 +126,21 @@ function wp_bili($matches, $attr, $url, $rawattr) } else { $height = 480; } - $iframe = ''; + $iframe = ''; + return apply_filters('iframe_bili', $iframe, $matches, $attr, $url, $ramattr); } wp_embed_register_handler('bili_iframe', '#https://www.bilibili.com/video/av(.*?)/#i', 'wp_bili'); //bing美图自定义登录页面背景 -function custom_login_head() +function gdk_custom_login_head() { if (gdk_option('gdk_loginbg')) { - $imgurl = gdk_option('gdk_loginbg'); - } else { - $imgurl = get_transient('Bing_img'); - if (false === $imgurl) { - $arr = json_decode(curl_post('https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1')['data']); - $imgurl = 'http://cn.bing.com' . $arr->images[0]->url; - set_transient('Bing_img', $imgurl, 60 * 60 * 24); - } + $imgurl = gdk_get_bing_img(); } - if (defined('UM_DIR')) { - echo ''; - } - echo ''; + echo ''; } -add_action('login_head', 'custom_login_head'); +add_action('login_head', 'gdk_custom_login_head'); // add youku using iframe function wp_iframe_handler_youku($matches, $attr, $url, $rawattr) @@ -157,7 +150,8 @@ function wp_iframe_handler_youku($matches, $attr, $url, $rawattr) } else { $height = 485; } - $iframe = ''; + $iframe = ''; + return apply_filters('iframe_youku', $iframe, $matches, $attr, $url, $ramattr); } wp_embed_register_handler('youku_iframe', '#http://v.youku.com/v_show/id_(.*?).html#i', 'wp_iframe_handler_youku'); diff --git a/functions/shortcode.php b/functions/shortcode.php index fe2ca84..c3a8eef 100644 --- a/functions/shortcode.php +++ b/functions/shortcode.php @@ -13,7 +13,6 @@ function gdk_potin() } add_shortcode('gdk_potin_btn', 'gdk_potin'); -// function gdk_login_fancybox() { return weixin_login_btn(); @@ -23,37 +22,40 @@ add_shortcode('gdk_login_btn', 'gdk_login_fancybox'); //添加钮Download function gdk_DownloadUrl($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'href' => 'http://', - ), $atts)); - return '' . $content . ''; + ], $atts)); + + return ''.$content.''; } add_shortcode('dl', 'gdk_DownloadUrl'); //添加钮git function gdk_GithubUrl($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'href' => 'http://', - ), $atts)); - return '' . $content . ''; + ], $atts)); + + return ''.$content.''; } add_shortcode('gt', 'gdk_GithubUrl'); //添加钮Demo function gdk_DemoUrl($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'href' => 'http://', - ), $atts)); - return '' . $content . ''; + ], $atts)); + + return ''.$content.''; } add_shortcode('dm', 'gdk_DemoUrl'); //使用短代码添加回复后可见内容开始 function gdk_reply_to_read($atts, $content = null) { - extract(shortcode_atts(array( - 'notice' => '

注意:本段内容须成功“回复本文”后“刷新本页”方可查看!

', - ), $atts)); - $email = null; + extract(shortcode_atts([ + 'notice' => '

注意:本段内容须成功“回复本文”后“刷新本页”方可查看!

', + ], $atts)); + $email = null; $user_ID = get_current_user_id(); if ($user_ID > 0) { $email = get_user_by('id', $user_ID)->user_email; @@ -62,8 +64,8 @@ function gdk_reply_to_read($atts, $content = null) if ($email == $admin_email) { return $content; } - } elseif (isset($_COOKIE['comment_author_email_' . COOKIEHASH])) { - $email = str_replace('%40', '@', $_COOKIE['comment_author_email_' . COOKIEHASH]); + } elseif (isset($_COOKIE['comment_author_email_'.COOKIEHASH])) { + $email = str_replace('%40', '@', $_COOKIE['comment_author_email_'.COOKIEHASH]); } else { return $notice; } @@ -72,144 +74,150 @@ function gdk_reply_to_read($atts, $content = null) } global $wpdb; $post_id = get_the_ID(); - $query = "SELECT `comment_ID` FROM {$wpdb->comments} WHERE `comment_post_ID`={$post_id} and `comment_approved`='1' and `comment_author_email`='{$email}' LIMIT 1"; + $query = "SELECT `comment_ID` FROM {$wpdb->comments} WHERE `comment_post_ID`={$post_id} and `comment_approved`='1' and `comment_author_email`='{$email}' LIMIT 1"; if ($wpdb->get_results($query)) { return do_shortcode($content); - } else { - return $notice; } + + return $notice; } add_shortcode('reply', 'gdk_reply_to_read'); //绿色提醒框 function gdk_toz($atts, $content = null) { - return '
' . $content . '
'; + return '
'.$content.'
'; } add_shortcode('v_notice', 'gdk_toz'); //红色提醒框 function gdk_toa($atts, $content = null) { - return '
' . $content . '
'; + return '
'.$content.'
'; } add_shortcode('v_error', 'gdk_toa'); //黄色提醒框 function gdk_toc($atts, $content = null) { - return '
' . $content . '
'; + return '
'.$content.'
'; } add_shortcode('v_warn', 'gdk_toc'); //蓝色提醒框 function gdk_tod($atts, $content = null) { - return '
' . $content . '
'; + return '
'.$content.'
'; } add_shortcode('v_blue', 'gdk_tod'); //蓝边文本框 function gdk_toe($atts, $content = null) { - return '
' . $content . '
'; + return '
'.$content.'
'; } add_shortcode('v_tips', 'gdk_toe'); //灵魂按钮 function gdk_tom($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'href' => 'http://', - ), $atts)); - return '' . $content . ''; + ], $atts)); + + return ''.$content.''; } add_shortcode('lhb', 'gdk_tom'); //添加视频按钮 function gdk_too($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'play' => '0', - ), $atts)); - if ($play == 0) { - return ''; + ], $atts)); + if (0 == $play) { + return ''; } - if ($play == 1) { - return ''; + if (1 == $play) { + return ''; } } add_shortcode('video', 'gdk_too'); //添加音频按钮 function gdk_tkk($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'play' => '0', - ), $atts)); - if ($play == 0) { - return ''; + ], $atts)); + if (0 == $play) { + return ''; } - if ($play == 1) { - return ''; + if (1 == $play) { + return ''; } } add_shortcode('audio', 'gdk_tkk'); //弹窗下载 function gdk_ton($atts, $content = null) { - extract(shortcode_atts(array( - 'href' => 'http://', + extract(shortcode_atts([ + 'href' => 'http://', 'filename' => '', 'filesize' => '', 'filedown' => '', - ), $atts)); - return '文件下载'; + ], $atts)); + + return '文件下载'; } add_shortcode('fanctdl', 'gdk_ton'); - //下载单页短代码 function gdk_download($atts, $content = null) { - extract(shortcode_atts(array('title' => '点击下载',), $atts)); - return '' . $title . ''; + extract(shortcode_atts(['title' => '点击下载'], $atts)); + + return ''.$title.''; } add_shortcode('pdownload', 'gdk_download'); //为WordPress添加展开收缩功能 function gdk_xcollapse($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'title' => '', - ), $atts)); - return '
'; + ], $atts)); + + return '
'; } add_shortcode('collapse', 'gdk_xcollapse'); //简单的下载面板 function gdk_xdltable($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'file' => '', 'size' => '', - ), $atts)); - return '

文件下载

  文件名称:' . $file . '  文件大小:' . $size . '
  下载声明:' . gdk_option('gdk_dltable_b') . '
  下载地址:' . $content . '
'; + ], $atts)); + + return '

文件下载

  文件名称:'.$file.'  文件大小:'.$size.'
  下载声明:'.gdk_option('gdk_dltable_b').'
  下载地址:'.$content.'
'; } add_shortcode('dltable', 'gdk_xdltable'); //网易云音乐 function gdk_music163($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'play' => '1', - ), $atts)); - return ''; + ], $atts)); + + return ''; } add_shortcode('netmusic', 'gdk_music163'); //登录可见 function gdk_login_to_read($atts, $content = null) { - $logina = '登录'; - extract(shortcode_atts(array( - 'notice' => '

注意:本段内容须“' . $logina . '”后方可查看!

', - ), $atts)); + $logina = '登录'; + extract(shortcode_atts([ + 'notice' => '

注意:本段内容须“'.$logina.'”后方可查看!

', + ], $atts)); if (is_user_logged_in() && !is_null($content) && !is_feed()) { - return '
隐藏内容

' . $content . '

'; + return '
隐藏内容

'.$content.'

'; } + return $notice; } add_shortcode('vip', 'gdk_login_to_read'); @@ -220,8 +228,9 @@ function gdk_secret_view($atts, $content = null) $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')) { - return '
隐藏内容

' . $content . '

'; + return '
隐藏内容

'.$content.'

'; } //admin show + return '
@@ -230,23 +239,24 @@ function gdk_secret_view($atts, $content = null)
'; - } add_shortcode('wxcaptcha', 'gdk_secret_view'); // 支持文章和页面运行PHP代码 function gdk_php_include($attr) { - $file = $attr['file']; + $file = $attr['file']; $upload_dir = wp_upload_dir(); - $folder = $upload_dir['basedir'] . '/php-content' . "/{$file}.php"; + $folder = $upload_dir['basedir'].'/php-content'."/{$file}.php"; ob_start(); + include $folder; + return ob_get_clean(); } add_shortcode('phpcode', 'gdk_php_include'); @@ -254,26 +264,27 @@ add_shortcode('phpcode', 'gdk_php_include'); //给文章加内链短代码 function gdk_insert_posts($atts, $content = null) { - extract(shortcode_atts(array( + extract(shortcode_atts([ 'ids' => '', - ), $atts)); + ], $atts)); global $post; - $content = ''; - $postids = explode(',', $ids); - $inset_posts = get_posts(array( + $content = ''; + $postids = explode(',', $ids); + $inset_posts = get_posts([ 'post__in' => $postids, - )); + ]); foreach ($inset_posts as $key => $post) { setup_postdata($post); - $content .= '
'; + $content .= '
'; $content .= get_the_title(); $content .= '

'; $content .= get_the_excerpt(); - $content .= '

'; } wp_reset_postdata(); + return $content; } add_shortcode('neilian', 'gdk_insert_posts'); @@ -281,42 +292,42 @@ add_shortcode('neilian', 'gdk_insert_posts'); //给文章加内链短代码 function gdk_insert_temp($atts, $content = null) { - extract(shortcode_atts(array('id' => ''), $atts)); - $data = get_post($id); - $content = $data->post_content; - return $content; + extract(shortcode_atts(['id' => ''], $atts)); + $data = get_post($id); + + return $data->post_content; } add_shortcode('temp', 'gdk_insert_temp'); //快速插入列表 -function gdk_list_shortcode_handler($atts, $content = '') +function gdk_list_shortcode_handler($atts, $content = null) { $content = trim($content); - $lists = explode("\n", $content); - $output = ''; + $lists = explode("\n", $content); + $output = ''; foreach ($lists as $li) { - if (trim($li) != '') { + if ('' != trim($li)) { $output .= "
  • {$li}
  • "; } } - $output = "
      " . $output . "
    \n"; - return $output; + + return '
      '.$output."
    \n"; } add_shortcode('list', 'gdk_list_shortcode_handler'); //表格短代码 -function gdk_table_shortcode_handler($atts, $content = '') +function gdk_table_shortcode_handler($atts, $content = null) { extract(shortcode_atts(['width' => '100%'], $atts)); - $output = ''; + $output = ''; $content = trim($content); - $trs = explode("\r\n", $content); - $ths = explode(" ", $trs[0]); //表头数组 + $trs = explode("\r\n", $content); + $ths = explode(' ', $trs[0]); //表头数组 $output .= ''; //var_dump($ths); foreach ($ths as $th) { $th = trim($th); - $output .= '' . $th . ''; + $output .= ''.$th.''; } $output .= ''; $output .= ''; @@ -324,194 +335,204 @@ function gdk_table_shortcode_handler($atts, $content = '') foreach ($trs as $tr) { $tr = trim($tr); if ($tr) { - $tds = explode(" ", $tr); + $tds = explode(' ', $tr); $output .= ''; foreach ($tds as $td) { $td = trim($td); if ($td) { - $output .= '' . $td . ''; + $output .= ''.$td.''; } } $output .= ''; } } $output .= ''; - $width = ' width="' . $width . '"'; - $output = '' . $output . '
    '; + $width = ' width="'.$width.'"'; - return $output; + return ''.$output.'
    '; } add_shortcode('table', 'gdk_table_shortcode_handler'); -add_shortcode('youku', function ($atts, $content = '') { - extract(shortcode_atts(array( - 'width' => '510', +add_shortcode('youku', function ($atts, $content = null) { + extract(shortcode_atts([ + 'width' => '510', 'height' => '498', - ), $atts)); + ], $atts)); - $width = (isset($_GET['width']) && intval($_GET['width'])) ? intval($_GET['width']) : $width; // 用于 JSON 接口 + $width = (isset($_GET['width']) && intval($_GET['width'])) ? intval($_GET['width']) : $width; // 用于 JSON 接口 $height = round($width / 4 * 3); if (preg_match('#http://v.youku.com/v_show/id_(.*?).html#i', $content, $matches)) { - return ''; + return ''; } }); add_shortcode('qqv', function ($atts, $content = '') { - extract(shortcode_atts(array( - 'width' => '510', + extract(shortcode_atts([ + 'width' => '510', 'height' => '498', - ), $atts)); + ], $atts)); - $width = (isset($_GET['width']) && intval($_GET['width'])) ? intval($_GET['width']) : $width; // 用于 JSON 接口 + $width = (isset($_GET['width']) && intval($_GET['width'])) ? intval($_GET['width']) : $width; // 用于 JSON 接口 $height = round($width / 4 * 3); if (preg_match('#//v.qq.com/iframe/player.html\?vid=(.+)#i', $content, $matches)) { //var_dump($matches);exit(); - return ''; - } elseif (preg_match('#//v.qq.com/iframe/preview.html\?vid=(.+)#i', $content, $matches)) { + return ''; + } + if (preg_match('#//v.qq.com/iframe/preview.html\?vid=(.+)#i', $content, $matches)) { //var_dump($matches);exit(); - return ''; + return ''; } }); add_shortcode('tudou', function ($atts, $content = '') { - extract(shortcode_atts(array( - 'width' => '480', + extract(shortcode_atts([ + 'width' => '480', 'height' => '400', - ), $atts)); + ], $atts)); - $width = (isset($_GET['width']) && intval($_GET['width'])) ? intval($_GET['width']) : $width; // 用于 JSON 接口 + $width = (isset($_GET['width']) && intval($_GET['width'])) ? intval($_GET['width']) : $width; // 用于 JSON 接口 $height = round($width / 4 * 3); if (preg_match('#http://www.tudou.com/programs/view/(.*?)#i', $content, $matches)) { - return ''; + return ''; } }); add_shortcode('sohutv', function ($atts, $content = '') { - extract(shortcode_atts(array( - 'width' => '510', + extract(shortcode_atts([ + 'width' => '510', 'height' => '498', - ), $atts)); + ], $atts)); - $width = (isset($_GET['width']) && intval($_GET['width'])) ? intval($_GET['width']) : $width; // 用于 JSON 接口 + $width = (isset($_GET['width']) && intval($_GET['width'])) ? intval($_GET['width']) : $width; // 用于 JSON 接口 $height = round($width / 4 * 3); if (preg_match('#http://tv.sohu.com/upload/static/share/share_play.html\#(.+)#i', $content, $matches)) { //var_dump($matches);exit(); - return ''; + return ''; } }); //付费可见短代码 function gdk_pay_nologin($atts, $content = '') { - $content = do_shortcode($content); - extract(shortcode_atts(array('money' => '1'), $atts)); + $content = do_shortcode($content); + extract(shortcode_atts(['money' => '1'], $atts)); $pid = get_the_ID(); //文章ID add_post_meta($pid, '_pay_content', $content, true) or update_post_meta($pid, '_pay_content', $content); //没有新建,有就更新 if (current_user_can('administrator')) { - return '
    隐藏内容

    ' . $content . '

    '; + return '
    隐藏内容

    '.$content.'

    '; } //admin show - $pay_log = get_post_meta($pid, 'pay_log', true); //购买记录数据 - $pay_arr = explode(",", $pay_log); + $pay_log = get_post_meta($pid, 'pay_log', true); //购买记录数据 + $pay_arr = explode(',', $pay_log); $pay_count = count($pay_arr); //已购买人数 - $notice = '
    付费内容'; - $notice .= '

    当前隐藏内容需要支付

    ' . $money . '元'; - $notice .= '

    已有' . $pay_count . '人支付

    '; - $notice .= '

    '; + $notice = '
    付费内容'; + $notice .= '

    当前隐藏内容需要支付

    '.$money.'元'; + $notice .= '

    已有'.$pay_count.'人支付

    '; + $notice .= '

    '; $notice .= '
    '; + return $notice; } add_shortcode('pax', 'gdk_pay_nologin'); +function box_shortcode($atts, $content = null) +{ + extract( + shortcode_atts([ + 's' => '1', + ], $atts) + ); -function box_shortcode( $atts, $content = null ) { - extract( - shortcode_atts(array( - 's' => '1' - ), $atts)); + if ('1' == $s) { + $box_classes = 'c1_4 aside'; + } + if ('2' == $s) { + $box_classes = 'c2_4 main'; + } + if ('3' == $s) { + $box_classes = 'c3_4'; + } + if ('4' == $s) { + $box_classes = 'c4_4'; + } - 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 '
    ' . $content . '
    '; + return '
    '.$content.'
    '; } -add_shortcode( 'b', 'box_shortcode' ); +add_shortcode('b', 'box_shortcode'); -function contentblock_shortcode( $atts, $content = null ) { - return '
    ' . do_shortcode($content) . '
    '; +function contentblock_shortcode($atts, $content = null) +{ + return '
    '.do_shortcode($content).'
    '; } -add_shortcode( 'cb', 'contentblock_shortcode' ); - +add_shortcode('cb', 'contentblock_shortcode'); //WordPress 段代码按钮集合 function gdk_shortcode_list() { $wpshortcodes = [ - '横线' => '
    ', - 'H3标题' => '

    ', - '记号笔' => ' ', - '链接按钮' => '[dm href=] [/dm]', - '下载按钮' => '[dl href=] [/dl]', - '透明按钮' => '[lhb href=] [/lhb]', - '视频按钮' => '[video play=0] [/video]', - '音频按钮' => '[audio play=0] [/audio]', - '绿色通知' => '[v_notice] + '横线' => '
    ', + 'H3标题' => '

    ', + '记号笔' => ' ', + '链接按钮' => '[dm href=] [/dm]', + '下载按钮' => '[dl href=] [/dl]', + '透明按钮' => '[lhb href=] [/lhb]', + '视频按钮' => '[video play=0] [/video]', + '音频按钮' => '[audio play=0] [/audio]', + '绿色通知' => '[v_notice] [/v_notice]', - '红色警告' => '[v_error] + '红色警告' => '[v_error] [/v_error]', - '黄色错误' => '[v_warn] + '黄色错误' => '[v_warn] [/v_warn]', - '蓝色提示' => '[v_blue] + '蓝色提示' => '[v_blue] [/v_blue]', - '默认提示' => '[v_tips] + '默认提示' => '[v_tips] [/v_tips]', - '隐藏收缩' => '[collapse title=\'\'] + '隐藏收缩' => '[collapse title=\'\'] [/collapse]', - '回复可见' => '[reply] + '回复可见' => '[reply] [/reply]', - '登陆可见' => '[vip] + '登陆可见' => '[vip] [/vip]', '微信验证码可见' => '[wxcaptcha] [/wxcaptcha]', - '积分购买可见' => '[pay point=\'10\']这里是需要付费的内容[/pay]', - '游客付费可见' => '[pax money=1] + '积分购买可见' => '[pay point=\'10\']这里是需要付费的内容[/pay]', + '游客付费可见' => '[pax money=1] [/pax]', - '弹窗下载' => '[fanctdl filename=\'这里填写文件名\' filepass=\'这里填写文件密码什么的\' href=\'这里填写的主下载链接\' filedown=\'这里填写的是文件的主下载名称\']这里填写的文件的辅助下载链接,可写多个,空格间隔[/fanctdl]', - '面板下载' => '[dltable file=\'在此处写下文件名称\' pass=\'在这里写下文件密码\']这里填写的文件的辅助下载链接,可写多个,空格间隔[/dltable]', - '单页下载' => '[pdownload title=点击下载]', - '文章内链' => '[neilian ids=]', - '无序列表' => '[list] + '弹窗下载' => '[fanctdl filename=\'这里填写文件名\' filepass=\'这里填写文件密码什么的\' href=\'这里填写的主下载链接\' filedown=\'这里填写的是文件的主下载名称\']这里填写的文件的辅助下载链接,可写多个,空格间隔[/fanctdl]', + '面板下载' => '[dltable file=\'在此处写下文件名称\' pass=\'在这里写下文件密码\']这里填写的文件的辅助下载链接,可写多个,空格间隔[/dltable]', + '单页下载' => '[pdownload title=点击下载]', + '文章内链' => '[neilian ids=]', + '无序列表' => '[list] [/list]', - '表格简码' => '[table] + '表格简码' => '[table] [/table]', ]; $output = ''; foreach ($wpshortcodes as $name => $alt) { - $output .= '' . $name . ''; + $output .= ''.$name.''; } + return $output; } function gdk_shortcode_button() { - $context = '短代码
    ' . gdk_shortcode_list() . '
    '; - echo $context; + echo '短代码
    '.gdk_shortcode_list().'
    '; } add_action('media_buttons', 'gdk_shortcode_button'); diff --git a/functions/user.php b/functions/user.php index b37d7b0..4ad3a33 100644 --- a/functions/user.php +++ b/functions/user.php @@ -6,59 +6,57 @@ function gdk_reset_password_message($message, $key) if (strpos($_POST['user_login'], '@')) { $user_data = get_user_by('email', trim($_POST['user_login'])); } else { - $login = trim($_POST['user_login']); + $login = trim($_POST['user_login']); $user_data = get_user_by('login', $login); } $user_login = $user_data->user_login; - $msg = "有人要求重设如下帐号的密码:\r\n\r\n"; - $msg .= network_site_url() . "\r\n\r\n"; - $msg .= sprintf('用户名:%s', $user_login) . "\r\n\r\n"; + $msg = "有人要求重设如下帐号的密码:\r\n\r\n"; + $msg .= network_site_url()."\r\n\r\n"; + $msg .= sprintf('用户名:%s', $user_login)."\r\n\r\n"; $msg .= "若这不是您本人要求的,请忽略本邮件,一切如常。\r\n\r\n"; $msg .= "要重置您的密码,请打开下面的链接:\r\n\r\n"; - $msg .= wp_login_url() . "?action=rp&key=$key&login=" . rawurlencode($user_login); + $msg .= wp_login_url()."?action=rp&key={$key}&login=".rawurlencode($user_login); + return $msg; } add_filter('retrieve_password_message', 'gdk_reset_password_message', null, 2); -if (!defined('UM_DIR')) { /*判断是否按照UM插件*/ +if (!defined('UM_DIR')) { // 判断是否按照UM插件 //注册表单 function gdk_show_extra_register_fields() { ?> -

    -

    + -

    -

    -

    +

    + -

    - +add('passwords_not_matched', "错误提示: 两次填写密码不一致"); + $errors->add('passwords_not_matched', '错误提示: 两次填写密码不一致'); } if (strlen($_POST['password']) < 8) { - $errors->add('password_too_short', "错误提示: 密码必须大于8个字符"); + $errors->add('password_too_short', '错误提示: 密码必须大于8个字符'); } } - add_action('register_post', 'gdk_check_extra_register_fields', 10, 3); - /* - * 提交用户密码进数据库 - */ + add_action('register_post', 'gdk_order_check_extra_register_fields', 10, 3); + // 提交用户密码进数据库 function gdk_register_extra_fields($user_id) { - $userdata = array(); + $userdata = []; $userdata['ID'] = $user_id; - if ($_POST['password'] !== '') { + if ('' !== $_POST['password']) { $userdata['user_pass'] = $_POST['password']; } $pattern = '/[一-龥]/u'; @@ -76,7 +74,7 @@ if (gdk_option('gdk_login_verify')) { { $num1 = mt_rand(0, 20); $num2 = mt_rand(0, 20); - echo "

    "; + echo "

    "; } add_action('login_form', 'gdk_login_verify'); add_action('register_form', 'gdk_login_verify'); @@ -84,12 +82,16 @@ if (gdk_option('gdk_login_verify')) { function gdk_login_verify_val() { $sum = $_POST['sum']; + switch ($sum) { case $_POST['num1'] + $_POST['num2']: break; + case null: wp_die('错误: 请输入验证码  返回上页'); + break; + default: wp_die('错误: 验证码错误,请重试  返回上页'); } @@ -101,7 +103,7 @@ if (gdk_option('gdk_login_verify')) { //仅显示作者自己的文章 function gdk_show_mypost($wp_query) { - if (strpos($_SERVER['REQUEST_URI'], '/wp-admin/edit.php') !== false) { + if (false !== strpos($_SERVER['REQUEST_URI'], '/wp-admin/edit.php')) { if (!current_user_can('manage_options')) { $wp_query->set('author', get_current_user_id()); } @@ -117,22 +119,20 @@ function gdk_show_myupload($wp_query_obj) return; } - if ('admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments') { + if ('admin-ajax.php' != $pagenow || 'query-attachments' != $_REQUEST['action']) { return; } if (!current_user_can('manage_options') && !current_user_can('manage_media_library')) { $wp_query_obj->set('author', get_current_user_id()); } - - return; } add_action('pre_get_posts', 'gdk_show_myupload'); //在[媒体库]只显示用户上传的文件 function gdk_show_myupload_library($wp_query) { - if (strpos($_SERVER['REQUEST_URI'], '/wp-admin/upload.php') !== false) { + if (false !== strpos($_SERVER['REQUEST_URI'], '/wp-admin/upload.php')) { if (!current_user_can('manage_options') && !current_user_can('manage_media_library')) { $wp_query->set('author', get_current_user_id()); } @@ -143,12 +143,11 @@ add_filter('parse_query', 'gdk_show_myupload_library'); //添加后台个人信息 function gdk_contact_fields($contactmethods) { - $contactmethods['qq'] = 'QQ'; + $contactmethods['qq'] = 'QQ'; $contactmethods['sina_weibo'] = '新浪微博'; - $contactmethods['weixin'] = '微信'; - unset($contactmethods['yim']); - unset($contactmethods['aim']); - unset($contactmethods['jabber']); + $contactmethods['weixin'] = '微信'; + unset($contactmethods['yim'], $contactmethods['aim'], $contactmethods['jabber']); + return $contactmethods; } add_filter('user_contactmethods', 'gdk_contact_fields'); @@ -164,8 +163,8 @@ function gdk_sanitize_user($username, $raw_username, $strict) $username = preg_replace('|[^a-z\p{Han}0-9 _.\-@]|iu', '', $username); } $username = trim($username); - $username = preg_replace('|\s+|', ' ', $username); - return $username; + + return preg_replace('|\s+|', ' ', $username); } add_filter('sanitize_user', 'gdk_sanitize_user', 10, 3); @@ -173,12 +172,13 @@ add_filter('sanitize_user', 'gdk_sanitize_user', 10, 3); function gdk_userid_column($cols) { $cols['ssid'] = 'ID'; + return $cols; } add_action('manage_users_columns', 'gdk_userid_column'); function gdk_userid_value($value, $column_name, $id) { - if ($column_name == 'ssid') { + if ('ssid' == $column_name) { $value = $id; } @@ -191,12 +191,13 @@ add_filter('manage_users_columns', 'gdk_add_user_nickname'); function gdk_add_user_nickname($columns) { $columns['user_nickname'] = '昵称'; + return $columns; } add_action('manage_users_custom_column', 'gdk_show_user_nickname_val', 20, 3); function gdk_show_user_nickname_val($value, $column_name, $user_id) { - $user = get_userdata($user_id); + $user = get_userdata($user_id); $user_nickname = $user->nickname; if ('user_nickname' == $column_name) { return $user_nickname; @@ -209,20 +210,20 @@ add_filter('manage_users_columns', 'gdk_points_columns'); function gdk_points_columns($columns) { $columns['points'] = '金币'; + return $columns; } function gdk_points_value($value, $column_name, $user_id) { - if ($column_name == 'points') { + if ('points' == $column_name) { $jinbi = GDK_Points::get_user_total_points($user_id, 'accepted'); - if ($jinbi != "") { - $ret = $jinbi; - return $ret; - } else { - $ret = '暂无充值'; - return $ret; + if ('' != $jinbi) { + return $jinbi; } + + return '暂无充值'; } + return $value; } add_action('manage_users_custom_column', 'gdk_points_value', 10, 3); @@ -231,25 +232,25 @@ add_action('manage_users_custom_column', 'gdk_points_value', 10, 3); function gdk_users_comments($columns) { $columns['comments'] = '评论'; + return $columns; } add_filter('manage_users_columns', 'gdk_users_comments'); function gdk_show_users_comments($value, $column_name, $user_id) { - if ($column_name == 'comments') { - $comments_counts = get_comments(array( - 'status' => '1', + if ('comments' == $column_name) { + $comments_counts = get_comments([ + 'status' => '1', 'user_id' => $user_id, - 'count' => true, - )); - if ($comments_counts != "") { - $ret = $comments_counts; - return $ret; - } else { - $ret = '暂未评论'; - return $ret; + 'count' => true, + ]); + if ('' != $comments_counts) { + return $comments_counts; } + + return '暂未评论'; } + return $value; } add_action('manage_users_custom_column', 'gdk_show_users_comments', 10, 3); @@ -264,21 +265,21 @@ add_action('user_register', 'gdk_log_ip'); function gdk_signup_ip($column_headers) { $column_headers['signup_ip'] = 'IP地址'; + return $column_headers; } add_filter('manage_users_columns', 'gdk_signup_ip'); function gdk_ripms_columns($value, $column_name, $user_id) { - if ($column_name == 'signup_ip') { + if ('signup_ip' == $column_name) { $ip = get_user_meta($user_id, 'signup_ip', true); - if ($ip != "") { - $ret = $ip; - return $ret; - } else { - $ret = '没有记录'; - return $ret; + if ('' != $ip) { + return $ip; } + + return '没有记录'; } + return $value; } add_action('manage_users_custom_column', 'gdk_ripms_columns', 10, 3); @@ -294,22 +295,22 @@ function gdk_add_last_login_column($columns) { $columns['last_login'] = '上次登录'; unset($columns['name']); + return $columns; } add_filter('manage_users_columns', 'gdk_add_last_login_column'); // 显示登录时间到新增栏目 function gdk_add_last_login($value, $column_name, $user_id) { - if ($column_name == 'last_login') { + if ('last_login' == $column_name) { $login = get_user_meta($user_id, 'last_login', true); - if ($login != "") { - $ret = $login; - return $ret; - } else { - $ret = '暂未登录'; - return $ret; + if ('' != $login) { + return $login; } + + return '暂未登录'; } + return $value; } -add_action('manage_users_custom_column', 'gdk_add_last_login', 10, 3); \ No newline at end of file +add_action('manage_users_custom_column', 'gdk_add_last_login', 10, 3); diff --git a/public/download.php b/public/download.php index d769eef..d8fa293 100644 --- a/public/download.php +++ b/public/download.php @@ -4,8 +4,8 @@ add_action('template_redirect', 'gdk_edl_redirect'); function gdk_edl_redirect() { - global $wp, $wp_query; - $b = $wp_query->query_vars['dl'] ?? ''; + global $wp_query; + $b = $wp_query->query_vars['dl'] ?? null; if ($b) { gdk_edl(); exit; @@ -16,7 +16,7 @@ function gdk_edl_redirect() function gdk_edl() { header('Content-type: text/html; charset=utf-8'); - $pid = isset($_GET['dl']) ? trim(htmlspecialchars($_GET['dl'], ENT_QUOTES)) : ''; + $pid = isset($_GET['dl']) ? trim(htmlspecialchars($_GET['dl'], ENT_QUOTES)) : null; if (!$pid) { wp_die('

    下载页面不是直接打开的哦

    '); } @@ -63,7 +63,7 @@ function gdk_edl()
    -