13 Commits

Author SHA1 Message Date
Cooper Dalrymple
75334270f0 Updated package updater 2025-07-22 10:05:01 -05:00
Cooper Dalrymple
b51a286e4b Remove external libraries 2025-07-22 09:58:37 -05:00
Cooper Dalrymple
cc5f5cf8f0 Remove old credentials 2025-07-22 09:58:09 -05:00
dcooperdalrymple
457c17d5d3 Fixed settings color picker loading issue. 2022-12-06 16:01:27 -06:00
dcooperdalrymple
7743278185 Fixed bug in build system. 2022-11-16 15:29:47 -06:00
dcooperdalrymple
dd02b7546b Updated Makefile to use slug as file name. 2022-11-16 14:16:17 -06:00
dcooperdalrymple
24efd02e0a Converted array() to [] 2022-04-13 10:18:38 -05:00
dcooperdalrymple
b3ea11c7ce Body class filter implemented. has-alert and has-alert-{id} 2022-04-13 09:48:14 -05:00
dcooperdalrymple
60e924ba32 has_active function with ogrealert/has_active filter. 2022-04-13 09:47:35 -05:00
dcooperdalrymple
bb08ce8a51 Pushed to version 0.1.9. 2021-05-24 15:05:36 -05:00
dcooperdalrymple
0dfafdbf68 Added z-index setting for all alerts. 2021-05-24 15:05:08 -05:00
dcooperdalrymple
f383778510 WP 5.5.0 deprecated filter. 2021-05-24 14:56:31 -05:00
dcooperdalrymple
400b1109f7 Renamed display.js to frontend.js to prevent blockers. 2021-05-24 14:56:21 -05:00
88 changed files with 225 additions and 11530 deletions

5
.gitignore vendored
View File

@@ -1,4 +1,7 @@
/assets/sass/*.css
*.map
/OgreAlert
OgreAlert.zip
ogrealert.zip
lib
composer.lock
vendor

View File

@@ -1,22 +0,0 @@
{
"uploadOnSave": true,
"useAtomicWrites": false,
"deleteLocal": false,
"hostname": "dev.ogre.me",
"port": "22",
"target": "public_html/wp-content/plugins/OgreAlert",
"ignore": [
".remote-sync.json",
".git/**",
"Makefile",
"OgreAlert/**",
"OgreAlert.zip"
],
"username": "template",
"password": "?,GtD}MtPgF&",
"watch": [
"/assets/sass/style.css",
"/assets/sass/style.css.map"
],
"transport": "scp"
}

View File

@@ -1,9 +1,10 @@
PACKAGE = OgreAlert
SLUG = ogrealert
DIR = ./$(PACKAGE)
all: $(PACKAGE).zip
all: $(SLUG).zip
$(PACKAGE).zip: clean dir copy zip
$(SLUG).zip: clean dir copy zip
dir:
mkdir $(DIR)
@@ -16,16 +17,18 @@ copy:
cp -f ./* $(DIR) || true
rm $(DIR)/Makefile
rm $(DIR)/$(PACKAGE).zip || true
rm $(DIR)/composer.json
rm $(DIR)/composer.lock
rm $(DIR)/$(SLUG).zip || true
rm -r $(DIR)/assets/sass/lib
rm $(DIR)/assets/sass/*.scss
rm $(DIR)/assets/sass/*.map
zip:
zip -r ./$(PACKAGE).zip $(DIR)
zip -r ./$(SLUG).zip $(DIR)
rm -r $(DIR) || true
clean:
rm -r $(DIR) || true
rm ./$(PACKAGE).zip || true
rm ./$(SLUG).zip || true

View File

@@ -2,7 +2,7 @@
Plugin Name: OgreAlert
Plugin URI: https://plugins.cleverogre.com/plugin/ogrealert/
Description: OgreAlert is a plugin developed by CleverOgre in Pensacola, Florida.
Version: 0.1.7
Version: 0.1.9
Author: CleverOgre
Author URI: https://cleverogre.com/
Icon1x: https://plugins.cleverogre.com/plugin/ogrealert/?asset=icon-sm
@@ -29,7 +29,7 @@ Copyright: © 2020 CleverOgre, Inc. All rights reserved.
`'---' `--' `" `'-'
*/
jQuery(function ($) {
(function ($) {
if (typeof ogrealert === 'undefined' || ogrealert == null || ogrealert.length <= 0) return falase;
// Cookie functions
@@ -196,4 +196,4 @@ jQuery(function ($) {
}
$(document).ready(documentReady);
});
})(jQuery);

View File

@@ -29,8 +29,8 @@ Copyright: © 2020 CleverOgre, Inc. All rights reserved.
`'---' `--' `" `'-'
*/
jQuery(function ($) {
$(document).on('ready', function () {
(function ($) {
$(document).ready(function () {
if ($.fn.datepicker) {
// Not using datepicker atm
/* $('.ogrealert-date-picker').datepicker({
@@ -40,4 +40,4 @@ jQuery(function ($) {
console.log('OgreAlert Error: datepicker does not exist.');
}
});
});
})(jQuery);

View File

@@ -29,12 +29,12 @@ Copyright: © 2020 CleverOgre, Inc. All rights reserved.
`'---' `--' `" `'-'
*/
jQuery(function ($) {
$(document).on('ready', function () {
(function ($) {
$(document).ready(function () {
if ($.fn.wpColorPicker) {
$('.ogrealert-color-picker').wpColorPicker();
} else {
console.log('OgreAlert Error: wpColorPicker does not exist.');
}
});
});
})(jQuery);

View File

@@ -2,7 +2,7 @@
Plugin Name: OgreAlert
Plugin URI: https://plugins.cleverogre.com/plugin/ogrealert/
Description: OgreAlert is a plugin developed by CleverOgre in Pensacola, Florida.
Version: 0.1.8
Version: 0.1.9
Author: CleverOgre
Author URI: https://cleverogre.com/
Icon1x: https://plugins.cleverogre.com/plugin/ogrealert/?asset=icon-sm
@@ -57,15 +57,13 @@ $content-line: 1.5 * $content-text;
$icon-text: $content-line;
// Layering
$messages-index: 10001;
/*******************
* Message *
*******************/
section.ogrealert-messages {
--messages-index: 10001;
display: block;
width: 100%;
height: auto;
@@ -73,7 +71,7 @@ section.ogrealert-messages {
padding: 0;
position: relative;
z-index: $messages-index;
z-index: var(--messages-index);
font-size: 0;
line-height: 0;

48
composer.json Normal file
View File

@@ -0,0 +1,48 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "cleverogre/ogre-alert",
"version": "0.2.0",
"title": "OgreAlert",
"description": "OgreAlert is a plugin developed by CleverOgre in Pensacola, Florida.",
"author": "CleverOgre",
"license": "GPL-2.0+",
"keywords": [
"WordPress",
"Plugin",
"Alert",
"Banner"
],
"homepage": "https://cleverogre.com",
"repositories": {
"wp-package-updater": {
"type": "package",
"package": {
"name": "froger-me/wp-package-updater",
"version": "1.4.0",
"source": {
"url": "https://github.com/froger-me/wp-package-updater.git",
"type": "git",
"reference": "master"
}
}
},
"wpackagist": {
"type": "composer",
"url": "https://wpackagist.org",
"only": [
"wpackagist-plugin/*",
"wpackagist-theme/*"
]
}
},
"require": {
"yahnis-elsts/plugin-update-checker": "^5.0",
"froger-me/wp-package-updater": "^1.4.0",
"magicoli/wp-package-updater-lib": "^0.1.9"
},
"scripts": {
"post-update-cmd": [
"php vendor/magicoli/wp-package-updater-lib/install.php"
]
}
}

View File

@@ -2,7 +2,7 @@
/**
* @package CleverOgre
* @subpackage OgreAlert
* @since OgreAlert 0.1.7
* @since OgreAlert 0.1.9
*/
namespace OgreAlert;
@@ -12,9 +12,9 @@ if (!defined('ABSPATH')) exit;
class Alert {
public static function load() {
add_action('init', array(__CLASS__, 'init'));
add_filter('manage_alert_posts_columns', array(__CLASS__, 'register_columns'));
add_action('manage_alert_posts_custom_column', array(__CLASS__, 'display_column'), 10, 2);
add_action('init', [__CLASS__, 'init']);
add_filter('manage_alert_posts_columns', [__CLASS__, 'register_columns']);
add_action('manage_alert_posts_custom_column', [__CLASS__, 'display_column'], 10, 2);
// OgreAlert Content Filters
add_filter('ogrealert/content', 'wptexturize');
@@ -22,13 +22,13 @@ class Alert {
add_filter('ogrealert/content', 'wpautop');
add_filter('ogrealert/content', 'shortcode_unautop');
add_filter('ogrealert/content', 'prepend_attachment');
add_filter('ogrealert/content', 'wp_make_content_images_responsive');
add_filter('ogrealert/content', 'wp_filter_content_tags');
add_filter('ogrealert/content', 'do_shortcode', 11); // After wpautop
}
static function init() {
$post_type_args = array(
'supports' => array('title', 'editor', 'revisions'),
$post_type_args = [
'supports' => ['title', 'editor', 'revisions'],
'public' => true,
'exclude_from_search' => true,
'publicly_queryable' => false,
@@ -38,22 +38,22 @@ class Alert {
'show_in_admin_bar' => true,
'menu_position' => apply_filters('ogrealert/menu_position', 20),
'menu_icon' => 'dashicons-format-status',
);
];
if (class_exists('Ogre')) {
$post_type_args['labels'] = \Ogre::get_labels(__('Alerts', 'ogrealert'), __('Alert', 'ogrealert'));
} else {
$post_type_args['labels'] = array(
$post_type_args['labels'] = [
'name' => __('Alerts', 'ogrealert'),
'singular_name' => __('Alert', 'ogrealert'),
);
];
}
register_post_type('alert', apply_filters('ogrealert/post_type_args', $post_type_args));
}
static function register_columns($columns) {
$_columns = array();
$_columns = [];
foreach ($columns as $key => $label) {
if ($key == 'date') {
@@ -97,7 +97,7 @@ class Alert {
$ids = array_map('intval', $ids);
$remove_keys = array();
$remove_keys = [];
foreach ($ids as $key => $id) {
if (!self::valid($id)) $remove_keys[] = $key;
}
@@ -125,7 +125,7 @@ class Alert {
}
public static function get_active() {
$alerts = get_posts(apply_filters('ogrealert/get_active_args', array(
$alerts = get_posts(apply_filters('ogrealert/get_active_args', [
'posts_per_page' => -1,
'offset' => 0,
'orderby' => 'rand',
@@ -133,13 +133,16 @@ class Alert {
'post_type' => 'alert',
'post_stauts' => 'publish',
'fields' => 'ids',
)));
]));
$alerts = !is_wp_error($alerts) && !empty($alerts) ? $alerts : false;
self::validate_ids($alerts);
return apply_filters('ogrealert/get_active', $alerts);
}
public static function has_active() {
return apply_filters('ogrealert/has_active', !empty(self::get_active()));
}
public static function get_random() {
$alerts = self::get_active();
@@ -170,29 +173,29 @@ class AlertMetaBox {
public static function load() {
if (is_admin()) {
add_action('load-post.php', array(__ClASS__, 'init'));
add_action('load-post-new.php', array(__ClASS__, 'init'));
add_action('load-post.php', [__CLASS__, 'init']);
add_action('load-post-new.php', [__CLASS__, 'init']);
}
}
public static function init() {
add_action('add_meta_boxes_alert', array(__CLASS__, 'add'));
add_action('save_post', array(__CLASS__, 'save'), 10, 2);
add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'));
add_action('add_meta_boxes_alert', [__CLASS__, 'add']);
add_action('save_post', [__CLASS__, 'save'], 10, 2);
add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_scripts']);
}
static function enqueue_scripts() {
if (!wp_style_is('jquery-ui-datepicker', 'enqueued')) {
wp_enqueue_style('jquery-ui-datepicker');
}
wp_enqueue_script('ogrealert-post', \OgreAlert\Settings::get('dir') . 'assets/js/post.js', array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker'), \OgreAlert\Settings::get('version'), true);
wp_enqueue_script('ogrealert-post', \OgreAlert\Settings::get('dir') . 'assets/js/post.js', ['jquery', 'jquery-ui-core', 'jquery-ui-datepicker'], \OgreAlert\Settings::get('version'), true);
}
static function add() {
add_meta_box(
'ogrealert_post_settings',
__('Message Settings', 'ogrealert'),
array(__CLASS__, 'render'),
[__CLASS__, 'render'],
'alert',
'side',
'default'
@@ -203,35 +206,35 @@ class AlertMetaBox {
wp_nonce_field('post_settings', '_ogrealert_nonce');
echo '<p>';
self::field_select(array(
self::field_select([
'id' => 'ogrealert_post_settings_priority',
'name' => '_ogrealert_priority',
'label' => __('Priority', 'ogrealert'),
'options' => array(
'options' => [
'high' => __('High', 'ogrealert'),
'normal' => __('Normal', 'ogrealert'),
'low' => __('Low', 'ogrealert'),
),
],
'default' => 'normal',
'class' => 'widefat',
));
]);
echo '</p>';
echo '<p>';
self::field_date(array(
self::field_date([
'id' => 'ogrealert_post_settings_expiration',
'name' => '_ogrealert_expiration',
'label' => __('Expires On', 'ogrealer'),
'label' => __('Expires On', 'ogrealert'),
'class' => 'widefat',
));
]);
echo '</p>';
echo '<p>';
self::field_select(array(
self::field_select([
'id' => 'ogrealert_post_settings_duration',
'name' => '_ogrealert_duration',
'label' => __('Dismiss Duration', 'ogrealert'),
'options' => array(
'options' => [
'none' => __('None', 'ogrealert'),
'page' => __('Page', 'ogrealert'),
'minute' => __('Minute', 'ogrealert'),
@@ -240,11 +243,11 @@ class AlertMetaBox {
'week' => __('Week', 'ogrealert'),
'month' => __('Month', 'ogrealert'),
'year' => __('Year', 'ogrealert'),
),
],
'default' => \OgreAlert\Settings::get('message_dismiss_duration'),
'class' => 'widefat',
'description' => __('If "None" is selected, the notice will not be able to be dismissed.', 'ogrealert'),
));
]);
echo '</p>';
}
@@ -258,11 +261,11 @@ class AlertMetaBox {
// Check if not an autosave or revision
if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) return;
$keys = array(
$keys = [
'_ogrealert_priority',
'_ogrealert_expiration',
'_ogrealert_duration',
);
];
foreach ($keys as $key) {
if (isset($_POST[$key])) update_post_meta($post_id, $key, $_POST[$key]);
}
@@ -272,10 +275,10 @@ class AlertMetaBox {
if (!isset($args['id']) || empty($args['id'])) return;
if (isset($args['label']) && !empty($args['label'])) {
self::field_label(array(
self::field_label([
'title' => $args['label'],
'required' => isset($args['required']) && $args['required'] == true,
));
]);
}
$selected = '';
@@ -321,10 +324,10 @@ class AlertMetaBox {
if (!isset($args['id']) || empty($args['id'])) return;
if (isset($args['label']) && !empty($args['label'])) {
self::field_label(array(
self::field_label([
'title' => $args['label'],
'required' => isset($args['required']) && $args['required'] == true,
));
]);
}
$value = get_post_meta(get_the_ID(), $args['name'], true);

View File

@@ -2,7 +2,7 @@
/**
* @package CleverOgre
* @subpackage OgreAlert
* @since OgreAlert 0.1.8
* @since OgreAlert 0.1.9
*/
namespace OgreAlert;
@@ -14,50 +14,62 @@ class Display {
public static function load() {
if (is_admin()) return;
add_action('wp', array(__CLASS__, 'init'));
add_action('wp', [__CLASS__, 'init']);
}
static function init() {
if (empty(\OgreAlert\Alert::get_active())) return;
if (!\OgreAlert\Alert::has_active()) return;
add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'));
add_action('wp_enqueue_scripts', [__CLASS__, 'enqueue_scripts']);
$position = \OgreAlert\Settings::get('message_position');
switch ($position) {
case 'top':
case 'bottom':
case 'footer':
add_action('wp_footer', array(__CLASS__, 'display_alerts'));
add_action('wp_footer', [__CLASS__, 'display_alerts']);
break;
case 'custom':
add_action('display_alerts', array(__CLASS__, 'display_alerts'));
add_action('display_alerts', [__CLASS__, 'display_alerts']);
break;
}
add_filter('body_class', [__CLASS__, 'body_class'], 10, 1);
}
static function enqueue_scripts() {
wp_enqueue_style('ogrealert', \OgreAlert\Settings::get('dir') . 'assets/sass/style.css', array(), \OgreAlert\Settings::get('version'), 'all');
wp_enqueue_script('ogrealert', \OgreAlert\Settings::get('dir') . 'assets/js/display.js', array('jquery'), \OgreAlert\Settings::get('version'), true);
wp_localize_script('ogrealert', 'ogrealert', array(
wp_enqueue_style('ogrealert', \OgreAlert\Settings::get('dir') . 'assets/sass/style.css', [], \OgreAlert\Settings::get('version'), 'all');
wp_enqueue_script('ogrealert', \OgreAlert\Settings::get('dir') . 'assets/js/frontend.js', ['jquery'], \OgreAlert\Settings::get('version'), true);
wp_localize_script('ogrealert', 'ogrealert', [
'text_color' => \OgreAlert\Settings::get('message_text_color'),
'background_color' => \OgreAlert\Settings::get('message_background_color'),
'transition_duration' => intval(\OgreAlert\Settings::get('message_transition_duration')),
'transition_animation' => \OgreAlert\Settings::get('message_transition_animation'),
));
]);
}
static function display_alerts() {
$ids = \OgreAlert\Alert::get_active();
if (empty($ids)) return;
if (!\OgreAlert\Alert::has_active()) return;
self::load_template('loop-start');
foreach ($ids as $id) {
self::load_template('alert', \OgreAlert\Priority::get($id), true, array('id' => $id));
foreach (\OgreAlert\Alert::get_active() as $id) {
self::load_template('alert', \OgreAlert\Priority::get($id), true, ['id' => $id]);
}
self::load_template('loop-end');
}
private static function load_template($filename, $filepart = '', $echo = true, $vars = array()) {
static function body_class($classes) {
if (is_admin() || !\OgreAlert\Alert::has_active()) return $classes;
$classes[] = 'has-alert';
foreach (\OgreAlert\Alert::get_active() as $id) {
$classes[] = sprintf('has-alert-%d', $id);
}
return $classes;
}
private static function load_template($filename, $filepart = '', $echo = true, $vars = []) {
$path = \OgreAlert\Settings::get('path') . 'templates/' . $filename . '-' . $filepart . '.php';
if (!file_exists($path)) {
$path = \OgreAlert\Settings::get('path') . 'templates/' . $filename . '.php';

View File

@@ -12,7 +12,7 @@ if (!defined('ABSPATH')) exit;
class Expiration {
public static function load() {
add_filter('ogrealert/valid_id', array(__CLASS__, 'check'), 10, 2);
add_filter('ogrealert/valid_id', [__CLASS__, 'check'], 10, 2);
}
static function check($valid, $id) {

View File

@@ -11,25 +11,25 @@ if (!defined('ABSPATH')) exit;
class Priority {
private static $priorities = array(
private static $priorities = [
'high',
'normal',
'low',
);
];
public static function load() {
add_filter('ogrealert/get_active', array(__CLASS__, 'order'), 10, 1);
add_filter('ogrealert/get_active', [__CLASS__, 'order'], 10, 1);
}
static function order($alerts) {
if (!is_array($alerts) || empty($alerts)) return $alerts;
$_alerts = array();
$_alerts = [];
foreach ($alerts as $id) {
$_alerts[] = array(
$_alerts[] = [
'id' => $id,
'priority' => self::get($id),
);
];
}
usort($_alerts, function ($a, $b) {

View File

@@ -28,6 +28,7 @@ class Settings {
public static $message_transition_duration;
public static $message_transition_animation;
public static $message_dismiss_duration;
public static $message_index;
public static $message_high_text_color;
public static $message_high_background_color;
@@ -39,13 +40,14 @@ class Settings {
public static $message_low_background_color;
public static function init() {
self::$defaults = array(
self::$defaults = [
'message_enabled' => '1',
'message_position' => 'bottom',
'message_container' => '1200',
'message_transition_duration' => '250',
'message_dismiss_duration' => 'day',
'message_animation' => 'slide',
'message_index' => '10001',
'message_high_text_color' => 'rgba(255, 255, 255, 1)',
'message_high_background_color' => 'rgba(220, 53, 69, 1)',
@@ -55,7 +57,7 @@ class Settings {
'message_low_text_color' => 'rgba(255, 255, 255, 1)',
'message_low_background_color' => 'rgba(23, 162, 184, 1)',
);
];
}
public static function get($key) {
@@ -95,7 +97,7 @@ class Settings {
default:
$options = get_option('ogrealert_options');
if (!is_array($options)) $options = array();
if (!is_array($options)) $options = [];
$options["ogrealert_settings_{$key}"] = $value;
update_option('ogrealert_options', $options);
break;
@@ -120,7 +122,7 @@ class Settings {
$regex = '/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/';
if (preg_match($regex, $hex) != 1) return false;
$dec = array('r' => 0, 'g' => 0, 'b' => 0);
$dec = ['r' => 0, 'g' => 0, 'b' => 0];
if (strlen($hex) == strlen('#000')) {
$dec['r'] = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
@@ -167,28 +169,28 @@ class Settings {
class SettingsPage {
public static function init() {
add_action('admin_init', array(__CLASS__, 'register_settings'));
add_action('admin_menu', array(__CLASS__, 'menu'));
add_action('admin_init', [__CLASS__, 'register_settings']);
add_action('admin_menu', [__CLASS__, 'menu']);
}
static function menu() {
if (!current_user_can(\OgreAlert\Settings::get('capability'))) return;
$page = add_submenu_page('edit.php?post_type=alert', __('OgreAlert Settings', 'ogrealert'), __('Settings', 'ogrealert'), \OgreAlert\Settings::get('capability'), 'ogrealert_settings', array(__CLASS__, 'page'));
add_action('load-' . $page, array(__CLASS__, 'load_page'));
$page = add_submenu_page('edit.php?post_type=alert', __('OgreAlert Settings', 'ogrealert'), __('Settings', 'ogrealert'), \OgreAlert\Settings::get('capability'), 'ogrealert_settings', [__CLASS__, 'page']);
add_action('load-' . $page, [__CLASS__, 'load_page']);
}
static function load_page() {
if (!current_user_can(\OgreAlert\Settings::get('capability'))) return;
add_action('admin_enqueue_scripts', array(__CLASS__, 'admin_enqueue_scripts'));
add_action('admin_enqueue_scripts', [__CLASS__, 'admin_enqueue_scripts']);
}
static function admin_enqueue_scripts() {
if (!wp_style_is('wp-color-picker', 'enqueued')) {
wp_enqueue_style('wp-color-picker');
}
wp_enqueue_script('ogrealert-settings', \OgreAlert\Settings::get('dir') . 'assets/js/settings.js', array('jquery', 'wp-color-picker'), \OgreAlert\Settings::get('version'), true);
wp_enqueue_script('ogrealert-settings', \OgreAlert\Settings::get('dir') . 'assets/js/settings.js', ['jquery', 'wp-color-picker'], \OgreAlert\Settings::get('version'), true);
}
static function register_settings() {
@@ -196,53 +198,53 @@ class SettingsPage {
// Message Settings
add_settings_section('ogrealert_section_general', __('General Settings', 'ogrealert'), array(__CLASS__, 'section'), 'ogrealert');
add_settings_section('ogrealert_section_general', __('General Settings', 'ogrealert'), [__CLASS__, 'section'], 'ogrealert');
add_settings_field('ogrealert_message_enabled', __('Enable Alerts', 'ogrealert'), array(__CLASS__, 'field_checkbox'), 'ogrealert', 'ogrealert_section_general', array(
add_settings_field('ogrealert_message_enabled', __('Enable Alerts', 'ogrealert'), [__CLASS__, 'field_checkbox'], 'ogrealert', 'ogrealert_section_general', [
'id' => 'ogrealert_settings_message_enabled',
'default' => \OgreAlert\Settings::get_default('message_enabled'),
));
]);
add_settings_field('ogrealert_message_position', __('Position', 'ogrealert'), array(__CLASS__, 'field_select'), 'ogrealert', 'ogrealert_section_general', array(
add_settings_field('ogrealert_message_position', __('Position', 'ogrealert'), [__CLASS__, 'field_select'], 'ogrealert', 'ogrealert_section_general', [
'id' => 'ogrealert_settings_message_position',
'options' => array(
'options' => [
'top' => __('Fixed Top', 'ogrealert'),
'bottom' => __('Fixed Bottom', 'ogrealert'),
'footer' => __('After Footer', 'ogrealert'),
'custom' => __('Custom', 'ogrealert'),
),
],
'default' => \OgreAlert\Settings::get_default('message_position'),
'description' => __('If you choose Custom, you must add "do_action(\'display_alerts\');" to a suitable location in your template files.', 'ogrealert'),
));
]);
add_settings_field('ogrealert_message_container', __('Container Width', 'ogrealert'), array(__CLASS__, 'field_text'), 'ogrealert', 'ogrealert_section_general', array(
add_settings_field('ogrealert_message_container', __('Container Width', 'ogrealert'), [__CLASS__, 'field_text'], 'ogrealert', 'ogrealert_section_general', [
'id' => 'ogrealert_settings_message_container',
'description' => 'A positive integer in pixels.',
'placeholder' => \OgreAlert\Settings::get_default('message_container'),
'default' => \OgreAlert\Settings::get_default('message_container'),
));
]);
add_settings_field('ogrealert_message_transition_duration', __('Transition Duration', 'ogrealert'), array(__CLASS__, 'field_text'), 'ogrealert', 'ogrealert_section_general', array(
add_settings_field('ogrealert_message_transition_duration', __('Transition Duration', 'ogrealert'), [__CLASS__, 'field_text'], 'ogrealert', 'ogrealert_section_general', [
'id' => 'ogrealert_settings_message_transition_duration',
'description' => 'A positive integer in milliseconds.',
'placeholder' => \OgreAlert\Settings::get_default('message_transition_duration'),
'default' => \OgreAlert\Settings::get_default('message_transition_duration'),
));
]);
add_settings_field('ogrealert_message_transition_animation', __('Transition Animation', 'ogrealert'), array(__CLASS__, 'field_select'), 'ogrealert', 'ogrealert_section_general', array(
add_settings_field('ogrealert_message_transition_animation', __('Transition Animation', 'ogrealert'), [__CLASS__, 'field_select'], 'ogrealert', 'ogrealert_section_general', [
'id' => 'ogrealert_settings_message_transition_animation',
'options' => array(
'options' => [
'slide' => __('Slide', 'ogrealert'),
'fade' => __('Fade', 'ogrealert'),
'custom' => __('Custom', 'ogrealert'),
),
],
'default' => \OgreAlert\Settings::get_default('message_transition_animation'),
'description' => __('If you choose Custom, the animation must be handled with the "ogrealert-message-transition-custom" class in css.', 'ogrealert'),
));
]);
add_settings_field('ogrealert_message_dismiss_duration', __('Default Dismiss Duration', 'ogrealert'), array(__CLASS__, 'field_select'), 'ogrealert', 'ogrealert_section_general', array(
add_settings_field('ogrealert_message_dismiss_duration', __('Default Dismiss Duration', 'ogrealert'), [__CLASS__, 'field_select'], 'ogrealert', 'ogrealert_section_general', [
'id' => 'ogrealert_settings_message_dismiss_duration',
'options' => array(
'options' => [
'none' => __('None', 'ogrealert'),
'page' => __('Page', 'ogrealert'),
'minute' => __('Minute', 'ogrealert'),
@@ -251,45 +253,52 @@ class SettingsPage {
'week' => __('Week', 'ogrealert'),
'month' => __('Month', 'ogrealert'),
'year' => __('Year', 'ogrealert'),
),
],
'default' => \OgreAlert\Settings::get_default('message_dismiss_duration'),
));
]);
add_settings_section('ogrealert_section_high', __('High Priority', 'ogrealert'), array(__CLASS__, 'section'), 'ogrealert');
add_settings_field('ogrealert_message_index', __('Z-Index', 'ogrealert'), [__CLASS__, 'field_text'], 'ogrealert', 'ogrealert_section_general', [
'id' => 'ogrealert_settings_message_index',
'description' => 'Sets the z-index value of all OgreAlert messages. Useful for ensuring your messages appear above certain elements of your site.',
'placeholder' => \OgreAlert\Settings::get_default('message_index'),
'default' => \OgreAlert\Settings::get_default('message_index'),
]);
add_settings_field('ogrealert_message_high_text_color', __('Text Color', 'ogrealert'), array(__CLASS__, 'field_color'), 'ogrealert', 'ogrealert_section_high', array(
add_settings_section('ogrealert_section_high', __('High Priority', 'ogrealert'), [__CLASS__, 'section'], 'ogrealert');
add_settings_field('ogrealert_message_high_text_color', __('Text Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_high', [
'id' => 'ogrealert_settings_message_high_text_color',
'default' => \OgreAlert\Settings::get_default('message_high_text_color'),
));
]);
add_settings_field('ogrealert_message_high_background_color', __('Background Color', 'ogrealert'), array(__CLASS__, 'field_color'), 'ogrealert', 'ogrealert_section_high', array(
add_settings_field('ogrealert_message_high_background_color', __('Background Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_high', [
'id' => 'ogrealert_settings_message_high_background_color',
'default' => \OgreAlert\Settings::get_default('message_high_background_color'),
));
]);
add_settings_section('ogrealert_section_normal', __('Normal Priority', 'ogrealert'), array(__CLASS__, 'section'), 'ogrealert');
add_settings_section('ogrealert_section_normal', __('Normal Priority', 'ogrealert'), [__CLASS__, 'section'], 'ogrealert');
add_settings_field('ogrealert_message_normal_text_color', __('Text Color', 'ogrealert'), array(__CLASS__, 'field_color'), 'ogrealert', 'ogrealert_section_normal', array(
add_settings_field('ogrealert_message_normal_text_color', __('Text Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_normal', [
'id' => 'ogrealert_settings_message_normal_text_color',
'default' => \OgreAlert\Settings::get_default('message_normal_text_color'),
));
]);
add_settings_field('ogrealert_message_normal_background_color', __('Background Color', 'ogrealert'), array(__CLASS__, 'field_color'), 'ogrealert', 'ogrealert_section_normal', array(
add_settings_field('ogrealert_message_normal_background_color', __('Background Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_normal', [
'id' => 'ogrealert_settings_message_normal_background_color',
'default' => \OgreAlert\Settings::get_default('message_normal_background_color'),
));
]);
add_settings_section('ogrealert_section_low', __('Low Priority', 'ogrealert'), array(__CLASS__, 'section'), 'ogrealert');
add_settings_section('ogrealert_section_low', __('Low Priority', 'ogrealert'), [__CLASS__, 'section'], 'ogrealert');
add_settings_field('ogrealert_message_low_text_color', __('Text Color', 'ogrealert'), array(__CLASS__, 'field_color'), 'ogrealert', 'ogrealert_section_low', array(
add_settings_field('ogrealert_message_low_text_color', __('Text Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_low', [
'id' => 'ogrealert_settings_message_low_text_color',
'default' => \OgreAlert\Settings::get_default('message_low_text_color'),
));
]);
add_settings_field('ogrealert_message_low_background_color', __('Background Color', 'ogrealert'), array(__CLASS__, 'field_color'), 'ogrealert', 'ogrealert_section_low', array(
add_settings_field('ogrealert_message_low_background_color', __('Background Color', 'ogrealert'), [__CLASS__, 'field_color'], 'ogrealert', 'ogrealert_section_low', [
'id' => 'ogrealert_settings_message_low_background_color',
'default' => \OgreAlert\Settings::get_default('message_low_background_color'),
));
]);
}
static function page() {
@@ -376,12 +385,12 @@ class SettingsPage {
if (isset($args['default'])) $value = $args['default'];
if (isset($options[$args['id']]) && !empty($options[$args['id']])) $value = $options[$args['id']];
$settings = array(
$settings = [
'tinymce' => true,
'textarea_name' => 'ogrealert_options[' . $args['id'] . ']',
'textarea_rows' => 15,
'tabindex' => 1,
);
];
wp_editor($value, $args['id'], $settings);
if (isset($args['description']) && !empty($args['description'])) {

View File

@@ -1,6 +0,0 @@
<?php
if ( !class_exists('Puc_v4_Factory', false) ):
class Puc_v4_Factory extends Puc_v4p4_Factory { }
endif;

View File

@@ -1,49 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Autoloader', false) ):
class Puc_v4p4_Autoloader {
private $prefix = '';
private $rootDir = '';
private $libraryDir = '';
private $staticMap;
public function __construct() {
$this->rootDir = dirname(__FILE__) . '/';
$nameParts = explode('_', __CLASS__, 3);
$this->prefix = $nameParts[0] . '_' . $nameParts[1] . '_';
$this->libraryDir = realpath($this->rootDir . '../..') . '/';
$this->staticMap = array(
'PucReadmeParser' => 'vendor/readme-parser.php',
'Parsedown' => 'vendor/ParsedownLegacy.php',
);
if ( version_compare(PHP_VERSION, '5.3.0', '>=') ) {
$this->staticMap['Parsedown'] = 'vendor/Parsedown.php';
}
spl_autoload_register(array($this, 'autoload'));
}
public function autoload($className) {
if ( isset($this->staticMap[$className]) && file_exists($this->libraryDir . $this->staticMap[$className]) ) {
/** @noinspection PhpIncludeInspection */
include ($this->libraryDir . $this->staticMap[$className]);
return;
}
if (strpos($className, $this->prefix) === 0) {
$path = substr($className, strlen($this->prefix));
$path = str_replace('_', '/', $path);
$path = $this->rootDir . $path . '.php';
if (file_exists($path)) {
/** @noinspection PhpIncludeInspection */
include $path;
}
}
}
}
endif;

View File

@@ -1,177 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_DebugBar_Extension', false) ):
class Puc_v4p4_DebugBar_Extension {
const RESPONSE_BODY_LENGTH_LIMIT = 4000;
/** @var Puc_v4p4_UpdateChecker */
protected $updateChecker;
protected $panelClass = 'Puc_v4p4_DebugBar_Panel';
public function __construct($updateChecker, $panelClass = null) {
$this->updateChecker = $updateChecker;
if ( isset($panelClass) ) {
$this->panelClass = $panelClass;
}
add_filter('debug_bar_panels', array($this, 'addDebugBarPanel'));
add_action('debug_bar_enqueue_scripts', array($this, 'enqueuePanelDependencies'));
add_action('wp_ajax_puc_v4_debug_check_now', array($this, 'ajaxCheckNow'));
}
/**
* Register the PUC Debug Bar panel.
*
* @param array $panels
* @return array
*/
public function addDebugBarPanel($panels) {
if ( $this->updateChecker->userCanInstallUpdates() ) {
$panels[] = new $this->panelClass($this->updateChecker);
}
return $panels;
}
/**
* Enqueue our Debug Bar scripts and styles.
*/
public function enqueuePanelDependencies() {
wp_enqueue_style(
'puc-debug-bar-style-v4',
$this->getLibraryUrl("/css/puc-debug-bar.css"),
array('debug-bar'),
'20171124'
);
wp_enqueue_script(
'puc-debug-bar-js-v4',
$this->getLibraryUrl("/js/debug-bar.js"),
array('jquery'),
'20170516'
);
}
/**
* Run an update check and output the result. Useful for making sure that
* the update checking process works as expected.
*/
public function ajaxCheckNow() {
if ( $_POST['uid'] !== $this->updateChecker->getUniqueName('uid') ) {
return;
}
$this->preAjaxRequest();
$update = $this->updateChecker->checkForUpdates();
if ( $update !== null ) {
echo "An update is available:";
echo '<pre>', htmlentities(print_r($update, true)), '</pre>';
} else {
echo 'No updates found.';
}
$errors = $this->updateChecker->getLastRequestApiErrors();
if ( !empty($errors) ) {
printf('<p>The update checker encountered %d API error%s.</p>', count($errors), (count($errors) > 1) ? 's' : '');
foreach (array_values($errors) as $num => $item) {
$wpError = $item['error'];
/** @var WP_Error $wpError */
printf('<h4>%d) %s</h4>', $num + 1, esc_html($wpError->get_error_message()));
echo '<dl>';
printf('<dt>Error code:</dt><dd><code>%s</code></dd>', esc_html($wpError->get_error_code()));
if ( isset($item['url']) ) {
printf('<dt>Requested URL:</dt><dd><code>%s</code></dd>', esc_html($item['url']));
}
if ( isset($item['httpResponse']) ) {
if ( is_wp_error($item['httpResponse']) ) {
$httpError = $item['httpResponse'];
/** @var WP_Error $httpError */
printf(
'<dt>WordPress HTTP API error:</dt><dd>%s (<code>%s</code>)</dd>',
esc_html($httpError->get_error_message()),
esc_html($httpError->get_error_code())
);
} else {
//Status code.
printf(
'<dt>HTTP status:</dt><dd><code>%d %s</code></dd>',
wp_remote_retrieve_response_code($item['httpResponse']),
wp_remote_retrieve_response_message($item['httpResponse'])
);
//Headers.
echo '<dt>Response headers:</dt><dd><pre>';
foreach (wp_remote_retrieve_headers($item['httpResponse']) as $name => $value) {
printf("%s: %s\n", esc_html($name), esc_html($value));
}
echo '</pre></dd>';
//Body.
$body = wp_remote_retrieve_body($item['httpResponse']);
if ( $body === '' ) {
$body = '(Empty response.)';
} else if ( strlen($body) > self::RESPONSE_BODY_LENGTH_LIMIT ) {
$length = strlen($body);
$body = substr($body, 0, self::RESPONSE_BODY_LENGTH_LIMIT)
. sprintf("\n(Long string truncated. Total length: %d bytes.)", $length);
}
printf('<dt>Response body:</dt><dd><pre>%s</pre></dd>', esc_html($body));
}
}
echo '<dl>';
}
}
exit;
}
/**
* Check access permissions and enable error display (for debugging).
*/
protected function preAjaxRequest() {
if ( !$this->updateChecker->userCanInstallUpdates() ) {
die('Access denied');
}
check_ajax_referer('puc-ajax');
error_reporting(E_ALL);
@ini_set('display_errors', 'On');
}
/**
* @param string $filePath
* @return string
*/
private function getLibraryUrl($filePath) {
$absolutePath = realpath(dirname(__FILE__) . '/../../../' . ltrim($filePath, '/'));
//Where is the library located inside the WordPress directory structure?
$absolutePath = Puc_v4p4_Factory::normalizePath($absolutePath);
$pluginDir = Puc_v4p4_Factory::normalizePath(WP_PLUGIN_DIR);
$muPluginDir = Puc_v4p4_Factory::normalizePath(WPMU_PLUGIN_DIR);
$themeDir = Puc_v4p4_Factory::normalizePath(get_theme_root());
if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
//It's part of a plugin.
return plugins_url(basename($absolutePath), $absolutePath);
} else if ( strpos($absolutePath, $themeDir) === 0 ) {
//It's part of a theme.
$relativePath = substr($absolutePath, strlen($themeDir) + 1);
$template = substr($relativePath, 0, strpos($relativePath, '/'));
$baseUrl = get_theme_root_uri($template);
if ( !empty($baseUrl) && $relativePath ) {
return $baseUrl . '/' . $relativePath;
}
}
return '';
}
}
endif;

View File

@@ -1,165 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_DebugBar_Panel', false) && class_exists('Debug_Bar_Panel', false) ):
class Puc_v4p4_DebugBar_Panel extends Debug_Bar_Panel {
/** @var Puc_v4p4_UpdateChecker */
protected $updateChecker;
private $responseBox = '<div class="puc-ajax-response" style="display: none;"></div>';
public function __construct($updateChecker) {
$this->updateChecker = $updateChecker;
$title = sprintf(
'<span class="puc-debug-menu-link-%s">PUC (%s)</span>',
esc_attr($this->updateChecker->getUniqueName('uid')),
$this->updateChecker->slug
);
parent::__construct($title);
}
public function render() {
printf(
'<div class="puc-debug-bar-panel-v4" id="%1$s" data-slug="%2$s" data-uid="%3$s" data-nonce="%4$s">',
esc_attr($this->updateChecker->getUniqueName('debug-bar-panel')),
esc_attr($this->updateChecker->slug),
esc_attr($this->updateChecker->getUniqueName('uid')),
esc_attr(wp_create_nonce('puc-ajax'))
);
$this->displayConfiguration();
$this->displayStatus();
$this->displayCurrentUpdate();
echo '</div>';
}
private function displayConfiguration() {
echo '<h3>Configuration</h3>';
echo '<table class="puc-debug-data">';
$this->displayConfigHeader();
$this->row('Slug', htmlentities($this->updateChecker->slug));
$this->row('DB option', htmlentities($this->updateChecker->optionName));
$requestInfoButton = $this->getMetadataButton();
$this->row('Metadata URL', htmlentities($this->updateChecker->metadataUrl) . ' ' . $requestInfoButton . $this->responseBox);
$scheduler = $this->updateChecker->scheduler;
if ( $scheduler->checkPeriod > 0 ) {
$this->row('Automatic checks', 'Every ' . $scheduler->checkPeriod . ' hours');
} else {
$this->row('Automatic checks', 'Disabled');
}
if ( isset($scheduler->throttleRedundantChecks) ) {
if ( $scheduler->throttleRedundantChecks && ($scheduler->checkPeriod > 0) ) {
$this->row(
'Throttling',
sprintf(
'Enabled. If an update is already available, check for updates every %1$d hours instead of every %2$d hours.',
$scheduler->throttledCheckPeriod,
$scheduler->checkPeriod
)
);
} else {
$this->row('Throttling', 'Disabled');
}
}
$this->updateChecker->onDisplayConfiguration($this);
echo '</table>';
}
protected function displayConfigHeader() {
//Do nothing. This should be implemented in subclasses.
}
protected function getMetadataButton() {
return '';
}
private function displayStatus() {
echo '<h3>Status</h3>';
echo '<table class="puc-debug-data">';
$state = $this->updateChecker->getUpdateState();
$checkNowButton = '';
if ( function_exists('get_submit_button') ) {
$checkNowButton = get_submit_button(
'Check Now',
'secondary',
'puc-check-now-button',
false,
array('id' => $this->updateChecker->getUniqueName('check-now-button'))
);
}
if ( $state->getLastCheck() > 0 ) {
$this->row('Last check', $this->formatTimeWithDelta($state->getLastCheck()) . ' ' . $checkNowButton . $this->responseBox);
} else {
$this->row('Last check', 'Never');
}
$nextCheck = wp_next_scheduled($this->updateChecker->scheduler->getCronHookName());
$this->row('Next automatic check', $this->formatTimeWithDelta($nextCheck));
if ( $state->getCheckedVersion() !== '' ) {
$this->row('Checked version', htmlentities($state->getCheckedVersion()));
$this->row('Cached update', $state->getUpdate());
}
$this->row('Update checker class', htmlentities(get_class($this->updateChecker)));
echo '</table>';
}
private function displayCurrentUpdate() {
$update = $this->updateChecker->getUpdate();
if ( $update !== null ) {
echo '<h3>An Update Is Available</h3>';
echo '<table class="puc-debug-data">';
$fields = $this->getUpdateFields();
foreach($fields as $field) {
if ( property_exists($update, $field) ) {
$this->row(ucwords(str_replace('_', ' ', $field)), htmlentities($update->$field));
}
}
echo '</table>';
} else {
echo '<h3>No updates currently available</h3>';
}
}
protected function getUpdateFields() {
return array('version', 'download_url', 'slug',);
}
private function formatTimeWithDelta($unixTime) {
if ( empty($unixTime) ) {
return 'Never';
}
$delta = time() - $unixTime;
$result = human_time_diff(time(), $unixTime);
if ( $delta < 0 ) {
$result = 'after ' . $result;
} else {
$result = $result . ' ago';
}
$result .= ' (' . $this->formatTimestamp($unixTime) . ')';
return $result;
}
private function formatTimestamp($unixTime) {
return gmdate('Y-m-d H:i:s', $unixTime + (get_option('gmt_offset') * 3600));
}
public function row($name, $value) {
if ( is_object($value) || is_array($value) ) {
$value = '<pre>' . htmlentities(print_r($value, true)) . '</pre>';
} else if ($value === null) {
$value = '<code>null</code>';
}
printf('<tr><th scope="row">%1$s</th> <td>%2$s</td></tr>', $name, $value);
}
}
endif;

View File

@@ -1,33 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_DebugBar_PluginExtension', false) ):
class Puc_v4p4_DebugBar_PluginExtension extends Puc_v4p4_DebugBar_Extension {
/** @var Puc_v4p4_Plugin_UpdateChecker */
protected $updateChecker;
public function __construct($updateChecker) {
parent::__construct($updateChecker, 'Puc_v4p4_DebugBar_PluginPanel');
add_action('wp_ajax_puc_v4_debug_request_info', array($this, 'ajaxRequestInfo'));
}
/**
* Request plugin info and output it.
*/
public function ajaxRequestInfo() {
if ( $_POST['uid'] !== $this->updateChecker->getUniqueName('uid') ) {
return;
}
$this->preAjaxRequest();
$info = $this->updateChecker->requestInfo();
if ( $info !== null ) {
echo 'Successfully retrieved plugin info from the metadata URL:';
echo '<pre>', htmlentities(print_r($info, true)), '</pre>';
} else {
echo 'Failed to retrieve plugin info from the metadata URL.';
}
exit;
}
}
endif;

View File

@@ -1,38 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_DebugBar_PluginPanel', false) ):
class Puc_v4p4_DebugBar_PluginPanel extends Puc_v4p4_DebugBar_Panel {
/**
* @var Puc_v4p4_Plugin_UpdateChecker
*/
protected $updateChecker;
protected function displayConfigHeader() {
$this->row('Plugin file', htmlentities($this->updateChecker->pluginFile));
parent::displayConfigHeader();
}
protected function getMetadataButton() {
$requestInfoButton = '';
if ( function_exists('get_submit_button') ) {
$requestInfoButton = get_submit_button(
'Request Info',
'secondary',
'puc-request-info-button',
false,
array('id' => $this->updateChecker->getUniqueName('request-info-button'))
);
}
return $requestInfoButton;
}
protected function getUpdateFields() {
return array_merge(
parent::getUpdateFields(),
array('homepage', 'upgrade_notice', 'tested',)
);
}
}
endif;

View File

@@ -1,21 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_DebugBar_ThemePanel', false) ):
class Puc_v4p4_DebugBar_ThemePanel extends Puc_v4p4_DebugBar_Panel {
/**
* @var Puc_v4p4_Theme_UpdateChecker
*/
protected $updateChecker;
protected function displayConfigHeader() {
$this->row('Theme directory', htmlentities($this->updateChecker->directoryName));
parent::displayConfigHeader();
}
protected function getUpdateFields() {
return array_merge(parent::getUpdateFields(), array('details_url'));
}
}
endif;

View File

@@ -1,292 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Factory', false) ):
/**
* A factory that builds update checker instances.
*
* When multiple versions of the same class have been loaded (e.g. PluginUpdateChecker 4.0
* and 4.1), this factory will always use the latest available minor version. Register class
* versions by calling {@link PucFactory::addVersion()}.
*
* At the moment it can only build instances of the UpdateChecker class. Other classes are
* intended mainly for internal use and refer directly to specific implementations.
*/
class Puc_v4p4_Factory {
protected static $classVersions = array();
protected static $sorted = false;
protected static $myMajorVersion = '';
protected static $latestCompatibleVersion = '';
/**
* Create a new instance of the update checker.
*
* This method automatically detects if you're using it for a plugin or a theme and chooses
* the appropriate implementation for your update source (JSON file, GitHub, BitBucket, etc).
*
* @see Puc_v4p4_UpdateChecker::__construct
*
* @param string $metadataUrl The URL of the metadata file, a GitHub repository, or another supported update source.
* @param string $fullPath Full path to the main plugin file or to the theme directory.
* @param string $slug Custom slug. Defaults to the name of the main plugin file or the theme directory.
* @param int $checkPeriod How often to check for updates (in hours).
* @param string $optionName Where to store book-keeping info about update checks.
* @param string $muPluginFile The plugin filename relative to the mu-plugins directory.
* @return Puc_v4p4_Plugin_UpdateChecker|Puc_v4p4_Theme_UpdateChecker|Puc_v4p4_Vcs_BaseChecker
*/
public static function buildUpdateChecker($metadataUrl, $fullPath, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$fullPath = self::normalizePath($fullPath);
$id = null;
//Plugin or theme?
$themeDirectory = self::getThemeDirectoryName($fullPath);
if ( self::isPluginFile($fullPath) ) {
$type = 'Plugin';
$id = $fullPath;
} else if ( $themeDirectory !== null ) {
$type = 'Theme';
$id = $themeDirectory;
} else {
throw new RuntimeException(sprintf(
'The update checker cannot determine if "%s" is a plugin or a theme. ' .
'This is a bug. Please contact the PUC developer.',
htmlentities($fullPath)
));
}
//Which hosting service does the URL point to?
$service = self::getVcsService($metadataUrl);
$apiClass = null;
if ( empty($service) ) {
//The default is to get update information from a remote JSON file.
$checkerClass = $type . '_UpdateChecker';
} else {
//You can also use a VCS repository like GitHub.
$checkerClass = 'Vcs_' . $type . 'UpdateChecker';
$apiClass = $service . 'Api';
}
$checkerClass = self::getCompatibleClassVersion($checkerClass);
if ( $checkerClass === null ) {
trigger_error(
sprintf(
'PUC %s does not support updates for %ss %s',
htmlentities(self::$latestCompatibleVersion),
strtolower($type),
$service ? ('hosted on ' . htmlentities($service)) : 'using JSON metadata'
),
E_USER_ERROR
);
return null;
}
if ( !isset($apiClass) ) {
//Plain old update checker.
return new $checkerClass($metadataUrl, $id, $slug, $checkPeriod, $optionName, $muPluginFile);
} else {
//VCS checker + an API client.
$apiClass = self::getCompatibleClassVersion($apiClass);
if ( $apiClass === null ) {
trigger_error(sprintf(
'PUC %s does not support %s',
htmlentities(self::$latestCompatibleVersion),
htmlentities($service)
), E_USER_ERROR);
return null;
}
return new $checkerClass(
new $apiClass($metadataUrl),
$id,
$slug,
$checkPeriod,
$optionName,
$muPluginFile
);
}
}
/**
*
* Normalize a filesystem path. Introduced in WP 3.9.
* Copying here allows use of the class on earlier versions.
* This version adapted from WP 4.8.2 (unchanged since 4.5.0)
*
* @param string $path Path to normalize.
* @return string Normalized path.
*/
public static function normalizePath($path) {
if ( function_exists('wp_normalize_path') ) {
return wp_normalize_path($path);
}
$path = str_replace('\\', '/', $path);
$path = preg_replace('|(?<=.)/+|', '/', $path);
if ( substr($path, 1, 1) === ':' ) {
$path = ucfirst($path);
}
return $path;
}
/**
* Check if the path points to a plugin file.
*
* @param string $absolutePath Normalized path.
* @return bool
*/
protected static function isPluginFile($absolutePath) {
//Is the file inside the "plugins" or "mu-plugins" directory?
$pluginDir = self::normalizePath(WP_PLUGIN_DIR);
$muPluginDir = self::normalizePath(WPMU_PLUGIN_DIR);
if ( (strpos($absolutePath, $pluginDir) === 0) || (strpos($absolutePath, $muPluginDir) === 0) ) {
return true;
}
//Is it a file at all? Caution: is_file() can fail if the parent dir. doesn't have the +x permission set.
if ( !is_file($absolutePath) ) {
return false;
}
//Does it have a valid plugin header?
//This is a last-ditch check for plugins symlinked from outside the WP root.
if ( function_exists('get_file_data') ) {
$headers = get_file_data($absolutePath, array('Name' => 'Plugin Name'), 'plugin');
return !empty($headers['Name']);
}
return false;
}
/**
* Get the name of the theme's directory from a full path to a file inside that directory.
* E.g. "/abc/public_html/wp-content/themes/foo/whatever.php" => "foo".
*
* Note that subdirectories are currently not supported. For example,
* "/xyz/wp-content/themes/my-theme/includes/whatever.php" => NULL.
*
* @param string $absolutePath Normalized path.
* @return string|null Directory name, or NULL if the path doesn't point to a theme.
*/
protected static function getThemeDirectoryName($absolutePath) {
if ( is_file($absolutePath) ) {
$absolutePath = dirname($absolutePath);
}
if ( file_exists($absolutePath . '/style.css') ) {
return basename($absolutePath);
}
return null;
}
/**
* Get the name of the hosting service that the URL points to.
*
* @param string $metadataUrl
* @return string|null
*/
private static function getVcsService($metadataUrl) {
$service = null;
//Which hosting service does the URL point to?
$host = @parse_url($metadataUrl, PHP_URL_HOST);
$path = @parse_url($metadataUrl, PHP_URL_PATH);
//Check if the path looks like "/user-name/repository".
$usernameRepoRegex = '@^/?([^/]+?)/([^/#?&]+?)/?$@';
if ( preg_match($usernameRepoRegex, $path) ) {
$knownServices = array(
'github.com' => 'GitHub',
'bitbucket.org' => 'BitBucket',
'gitlab.com' => 'GitLab',
);
if ( isset($knownServices[$host]) ) {
$service = $knownServices[$host];
}
}
return $service;
}
/**
* Get the latest version of the specified class that has the same major version number
* as this factory class.
*
* @param string $class Partial class name.
* @return string|null Full class name.
*/
protected static function getCompatibleClassVersion($class) {
if ( isset(self::$classVersions[$class][self::$latestCompatibleVersion]) ) {
return self::$classVersions[$class][self::$latestCompatibleVersion];
}
return null;
}
/**
* Get the specific class name for the latest available version of a class.
*
* @param string $class
* @return null|string
*/
public static function getLatestClassVersion($class) {
if ( !self::$sorted ) {
self::sortVersions();
}
if ( isset(self::$classVersions[$class]) ) {
return reset(self::$classVersions[$class]);
} else {
return null;
}
}
/**
* Sort available class versions in descending order (i.e. newest first).
*/
protected static function sortVersions() {
foreach ( self::$classVersions as $class => $versions ) {
uksort($versions, array(__CLASS__, 'compareVersions'));
self::$classVersions[$class] = $versions;
}
self::$sorted = true;
}
protected static function compareVersions($a, $b) {
return -version_compare($a, $b);
}
/**
* Register a version of a class.
*
* @access private This method is only for internal use by the library.
*
* @param string $generalClass Class name without version numbers, e.g. 'PluginUpdateChecker'.
* @param string $versionedClass Actual class name, e.g. 'PluginUpdateChecker_1_2'.
* @param string $version Version number, e.g. '1.2'.
*/
public static function addVersion($generalClass, $versionedClass, $version) {
if ( empty(self::$myMajorVersion) ) {
$nameParts = explode('_', __CLASS__, 3);
self::$myMajorVersion = substr(ltrim($nameParts[1], 'v'), 0, 1);
}
//Store the greatest version number that matches our major version.
$components = explode('.', $version);
if ( $components[0] === self::$myMajorVersion ) {
if (
empty(self::$latestCompatibleVersion)
|| version_compare($version, self::$latestCompatibleVersion, '>')
) {
self::$latestCompatibleVersion = $version;
}
}
if ( !isset(self::$classVersions[$generalClass]) ) {
self::$classVersions[$generalClass] = array();
}
self::$classVersions[$generalClass][$version] = $versionedClass;
self::$sorted = false;
}
}
endif;

View File

@@ -1,132 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Metadata', false) ):
/**
* A base container for holding information about updates and plugin metadata.
*
* @author Janis Elsts
* @copyright 2016
* @access public
*/
abstract class Puc_v4p4_Metadata {
/**
* Create an instance of this class from a JSON document.
*
* @abstract
* @param string $json
* @return self
*/
public static function fromJson(/** @noinspection PhpUnusedParameterInspection */ $json) {
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
}
/**
* @param string $json
* @param self $target
* @return bool
*/
protected static function createFromJson($json, $target) {
/** @var StdClass $apiResponse */
$apiResponse = json_decode($json);
if ( empty($apiResponse) || !is_object($apiResponse) ){
$errorMessage = "Failed to parse update metadata. Try validating your .json file with http://jsonlint.com/";
do_action('puc_api_error', new WP_Error('puc-invalid-json', $errorMessage));
trigger_error($errorMessage, E_USER_NOTICE);
return false;
}
$valid = $target->validateMetadata($apiResponse);
if ( is_wp_error($valid) ){
do_action('puc_api_error', $valid);
trigger_error($valid->get_error_message(), E_USER_NOTICE);
return false;
}
foreach(get_object_vars($apiResponse) as $key => $value){
$target->$key = $value;
}
return true;
}
/**
* No validation by default! Subclasses should check that the required fields are present.
*
* @param StdClass $apiResponse
* @return bool|WP_Error
*/
protected function validateMetadata(/** @noinspection PhpUnusedParameterInspection */ $apiResponse) {
return true;
}
/**
* Create a new instance by copying the necessary fields from another object.
*
* @abstract
* @param StdClass|self $object The source object.
* @return self The new copy.
*/
public static function fromObject(/** @noinspection PhpUnusedParameterInspection */ $object) {
throw new LogicException('The ' . __METHOD__ . ' method must be implemented by subclasses');
}
/**
* Create an instance of StdClass that can later be converted back to an
* update or info container. Useful for serialization and caching, as it
* avoids the "incomplete object" problem if the cached value is loaded
* before this class.
*
* @return StdClass
*/
public function toStdClass() {
$object = new stdClass();
$this->copyFields($this, $object);
return $object;
}
/**
* Transform the metadata into the format used by WordPress core.
*
* @return object
*/
abstract public function toWpFormat();
/**
* Copy known fields from one object to another.
*
* @param StdClass|self $from
* @param StdClass|self $to
*/
protected function copyFields($from, $to) {
$fields = $this->getFieldNames();
if ( property_exists($from, 'slug') && !empty($from->slug) ) {
//Let plugins add extra fields without having to create subclasses.
$fields = apply_filters($this->getPrefixedFilter('retain_fields') . '-' . $from->slug, $fields);
}
foreach ($fields as $field) {
if ( property_exists($from, $field) ) {
$to->$field = $from->$field;
}
}
}
/**
* @return string[]
*/
protected function getFieldNames() {
return array();
}
/**
* @param string $tag
* @return string
*/
protected function getPrefixedFilter($tag) {
return 'puc_' . $tag;
}
}
endif;

View File

@@ -1,88 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_OAuthSignature', false) ):
/**
* A basic signature generator for zero-legged OAuth 1.0.
*/
class Puc_v4p4_OAuthSignature {
private $consumerKey = '';
private $consumerSecret = '';
public function __construct($consumerKey, $consumerSecret) {
$this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret;
}
/**
* Sign a URL using OAuth 1.0.
*
* @param string $url The URL to be signed. It may contain query parameters.
* @param string $method HTTP method such as "GET", "POST" and so on.
* @return string The signed URL.
*/
public function sign($url, $method = 'GET') {
$parameters = array();
//Parse query parameters.
$query = @parse_url($url, PHP_URL_QUERY);
if ( !empty($query) ) {
parse_str($query, $parsedParams);
if ( is_array($parameters) ) {
$parameters = $parsedParams;
}
//Remove the query string from the URL. We'll replace it later.
$url = substr($url, 0, strpos($url, '?'));
}
$parameters = array_merge(
$parameters,
array(
'oauth_consumer_key' => $this->consumerKey,
'oauth_nonce' => $this->nonce(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0',
)
);
unset($parameters['oauth_signature']);
//Parameters must be sorted alphabetically before signing.
ksort($parameters);
//The most complicated part of the request - generating the signature.
//The string to sign contains the HTTP method, the URL path, and all of
//our query parameters. Everything is URL encoded. Then we concatenate
//them with ampersands into a single string to hash.
$encodedVerb = urlencode($method);
$encodedUrl = urlencode($url);
$encodedParams = urlencode(http_build_query($parameters, '', '&'));
$stringToSign = $encodedVerb . '&' . $encodedUrl . '&' . $encodedParams;
//Since we only have one OAuth token (the consumer secret) we only have
//to use it as our HMAC key. However, we still have to append an & to it
//as if we were using it with additional tokens.
$secret = urlencode($this->consumerSecret) . '&';
//The signature is a hash of the consumer key and the base string. Note
//that we have to get the raw output from hash_hmac and base64 encode
//the binary data result.
$parameters['oauth_signature'] = base64_encode(hash_hmac('sha1', $stringToSign, $secret, true));
return ($url . '?' . http_build_query($parameters));
}
/**
* Generate a random nonce.
*
* @return string
*/
private function nonce() {
$mt = microtime();
$rand = mt_rand();
return md5($mt . '_' . $rand);
}
}
endif;

View File

@@ -1,130 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Plugin_Info', false) ):
/**
* A container class for holding and transforming various plugin metadata.
*
* @author Janis Elsts
* @copyright 2016
* @access public
*/
class Puc_v4p4_Plugin_Info extends Puc_v4p4_Metadata {
//Most fields map directly to the contents of the plugin's info.json file.
//See the relevant docs for a description of their meaning.
public $name;
public $slug;
public $version;
public $homepage;
public $sections = array();
public $download_url;
public $banners;
public $icons = array();
public $translations = array();
public $author;
public $author_homepage;
public $requires;
public $tested;
public $upgrade_notice;
public $rating;
public $num_ratings;
public $downloaded;
public $active_installs;
public $last_updated;
public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.
public $filename; //Plugin filename relative to the plugins directory.
/**
* Create a new instance of Plugin Info from JSON-encoded plugin info
* returned by an external update API.
*
* @param string $json Valid JSON string representing plugin info.
* @return self|null New instance of Plugin Info, or NULL on error.
*/
public static function fromJson($json){
$instance = new self();
if ( !parent::createFromJson($json, $instance) ) {
return null;
}
//json_decode decodes assoc. arrays as objects. We want them as arrays.
$instance->sections = (array)$instance->sections;
$instance->icons = (array)$instance->icons;
return $instance;
}
/**
* Very, very basic validation.
*
* @param StdClass $apiResponse
* @return bool|WP_Error
*/
protected function validateMetadata($apiResponse) {
if (
!isset($apiResponse->name, $apiResponse->version)
|| empty($apiResponse->name)
|| empty($apiResponse->version)
) {
return new WP_Error(
'puc-invalid-metadata',
"The plugin metadata file does not contain the required 'name' and/or 'version' keys."
);
}
return true;
}
/**
* Transform plugin info into the format used by the native WordPress.org API
*
* @return object
*/
public function toWpFormat(){
$info = new stdClass;
//The custom update API is built so that many fields have the same name and format
//as those returned by the native WordPress.org API. These can be assigned directly.
$sameFormat = array(
'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
);
foreach($sameFormat as $field){
if ( isset($this->$field) ) {
$info->$field = $this->$field;
} else {
$info->$field = null;
}
}
//Other fields need to be renamed and/or transformed.
$info->download_link = $this->download_url;
$info->author = $this->getFormattedAuthor();
$info->sections = array_merge(array('description' => ''), $this->sections);
if ( !empty($this->banners) ) {
//WP expects an array with two keys: "high" and "low". Both are optional.
//Docs: https://wordpress.org/plugins/about/faq/#banners
$info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
$info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
}
return $info;
}
protected function getFormattedAuthor() {
if ( !empty($this->author_homepage) ){
/** @noinspection HtmlUnknownTarget */
return sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
}
return $this->author;
}
}
endif;

View File

@@ -1,110 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Plugin_Update', false) ):
/**
* A simple container class for holding information about an available update.
*
* @author Janis Elsts
* @copyright 2016
* @access public
*/
class Puc_v4p4_Plugin_Update extends Puc_v4p4_Update {
public $id = 0;
public $homepage;
public $upgrade_notice;
public $tested;
public $icons = array();
public $filename; //Plugin filename relative to the plugins directory.
protected static $extraFields = array(
'id', 'homepage', 'tested', 'upgrade_notice', 'icons', 'filename',
);
/**
* Create a new instance of PluginUpdate from its JSON-encoded representation.
*
* @param string $json
* @return Puc_v4p4_Plugin_Update|null
*/
public static function fromJson($json){
//Since update-related information is simply a subset of the full plugin info,
//we can parse the update JSON as if it was a plugin info string, then copy over
//the parts that we care about.
$pluginInfo = Puc_v4p4_Plugin_Info::fromJson($json);
if ( $pluginInfo !== null ) {
return self::fromPluginInfo($pluginInfo);
} else {
return null;
}
}
/**
* Create a new instance of PluginUpdate based on an instance of PluginInfo.
* Basically, this just copies a subset of fields from one object to another.
*
* @param Puc_v4p4_Plugin_Info $info
* @return Puc_v4p4_Plugin_Update
*/
public static function fromPluginInfo($info){
return self::fromObject($info);
}
/**
* Create a new instance by copying the necessary fields from another object.
*
* @param StdClass|Puc_v4p4_Plugin_Info|Puc_v4p4_Plugin_Update $object The source object.
* @return Puc_v4p4_Plugin_Update The new copy.
*/
public static function fromObject($object) {
$update = new self();
$update->copyFields($object, $update);
return $update;
}
/**
* @return string[]
*/
protected function getFieldNames() {
return array_merge(parent::getFieldNames(), self::$extraFields);
}
/**
* Transform the update into the format used by WordPress native plugin API.
*
* @return object
*/
public function toWpFormat() {
$update = parent::toWpFormat();
$update->id = $this->id;
$update->url = $this->homepage;
$update->tested = $this->tested;
$update->plugin = $this->filename;
if ( !empty($this->upgrade_notice) ) {
$update->upgrade_notice = $this->upgrade_notice;
}
if ( !empty($this->icons) && is_array($this->icons) ) {
//This should be an array with up to 4 keys: 'svg', '1x', '2x' and 'default'.
//Docs: https://developer.wordpress.org/plugins/wordpress-org/plugin-assets/#plugin-icons
$icons = array_intersect_key(
$this->icons,
array('svg' => true, '1x' => true, '2x' => true, 'default' => true)
);
if ( !empty($icons) ) {
$update->icons = $icons;
//It appears that the 'default' icon isn't used anywhere in WordPress 4.9,
//but lets set it just in case a future release needs it.
if ( !isset($update->icons['default']) ) {
$update->icons['default'] = current($update->icons);
}
}
}
return $update;
}
}
endif;

View File

@@ -1,740 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Plugin_UpdateChecker', false) ):
/**
* A custom plugin update checker.
*
* @author Janis Elsts
* @copyright 2016
* @access public
*/
class Puc_v4p4_Plugin_UpdateChecker extends Puc_v4p4_UpdateChecker {
protected $updateTransient = 'update_plugins';
protected $translationType = 'plugin';
public $pluginAbsolutePath = ''; //Full path of the main plugin file.
public $pluginFile = ''; //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.
private $cachedInstalledVersion = null;
private $manualCheckErrorTransient = '';
/**
* Class constructor.
*
* @param string $metadataUrl The URL of the plugin's metadata file.
* @param string $pluginFile Fully qualified path to the main plugin file.
* @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
* @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
* @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
* @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
*/
public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
$this->pluginAbsolutePath = $pluginFile;
$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
$this->muPluginFile = $muPluginFile;
//If no slug is specified, use the name of the main plugin file as the slug.
//For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
if ( empty($slug) ){
$slug = basename($this->pluginFile, '.php');
}
//Plugin slugs must be unique.
$slugCheckFilter = 'puc_is_slug_in_use-' . $slug;
$slugUsedBy = apply_filters($slugCheckFilter, false);
if ( $slugUsedBy ) {
$this->triggerError(sprintf(
'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
htmlentities($slug),
htmlentities($slugUsedBy)
), E_USER_ERROR);
}
add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));
//Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
//it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
$this->muPluginFile = $this->pluginFile;
}
//To prevent a crash during plugin uninstallation, remove updater hooks when the user removes the plugin.
//Details: https://github.com/YahnisElsts/plugin-update-checker/issues/138#issuecomment-335590964
add_action('uninstall_' . $this->pluginFile, array($this, 'removeHooks'));
$this->manualCheckErrorTransient = $this->getUniqueName('manual_check_errors');
parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName);
}
/**
* Create an instance of the scheduler.
*
* @param int $checkPeriod
* @return Puc_v4p4_Scheduler
*/
protected function createScheduler($checkPeriod) {
$scheduler = new Puc_v4p4_Scheduler($this, $checkPeriod, array('load-plugins.php'));
register_deactivation_hook($this->pluginFile, array($scheduler, 'removeUpdaterCron'));
return $scheduler;
}
/**
* Install the hooks required to run periodic update checks and inject update info
* into WP data structures.
*
* @return void
*/
protected function installHooks(){
//Override requests for plugin information
add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
add_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10, 3);
add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
add_action('admin_init', array($this, 'handleManualCheck'));
add_action('all_admin_notices', array($this, 'displayManualCheckResult'));
//Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
parent::installHooks();
}
/**
* Remove update checker hooks.
*
* The intent is to prevent a fatal error that can happen if the plugin has an uninstall
* hook. During uninstallation, WP includes the main plugin file (which creates a PUC instance),
* the uninstall hook runs, WP deletes the plugin files and then updates some transients.
* If PUC hooks are still around at this time, they could throw an error while trying to
* autoload classes from files that no longer exist.
*
* The "site_transient_{$transient}" filter is the main problem here, but let's also remove
* most other PUC hooks to be safe.
*
* @internal
*/
public function removeHooks() {
parent::removeHooks();
remove_filter('plugins_api', array($this, 'injectInfo'), 20);
remove_filter('plugin_row_meta', array($this, 'addViewDetailsLink'), 10);
remove_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10);
remove_action('admin_init', array($this, 'handleManualCheck'));
remove_action('all_admin_notices', array($this, 'displayManualCheckResult'));
remove_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
remove_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
}
/**
* Retrieve plugin info from the configured API endpoint.
*
* @uses wp_remote_get()
*
* @param array $queryArgs Additional query arguments to append to the request. Optional.
* @return Puc_v4p4_Plugin_Info
*/
public function requestInfo($queryArgs = array()) {
list($pluginInfo, $result) = $this->requestMetadata('Puc_v4p4_Plugin_Info', 'request_info', $queryArgs);
if ( $pluginInfo !== null ) {
/** @var Puc_v4p4_Plugin_Info $pluginInfo */
$pluginInfo->filename = $this->pluginFile;
$pluginInfo->slug = $this->slug;
}
$pluginInfo = apply_filters($this->getUniqueName('request_info_result'), $pluginInfo, $result);
return $pluginInfo;
}
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @uses PluginUpdateChecker::requestInfo()
*
* @return Puc_v4p4_Update|null An instance of Plugin_Update, or NULL when no updates are available.
*/
public function requestUpdate() {
//For the sake of simplicity, this function just calls requestInfo()
//and transforms the result accordingly.
$pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
if ( $pluginInfo === null ){
return null;
}
$update = Puc_v4p4_Plugin_Update::fromPluginInfo($pluginInfo);
$update = $this->filterUpdateResult($update);
return $update;
}
/**
* Get the currently installed version of the plugin.
*
* @return string Version number.
*/
public function getInstalledVersion(){
if ( isset($this->cachedInstalledVersion) ) {
return $this->cachedInstalledVersion;
}
$pluginHeader = $this->getPluginHeader();
if ( isset($pluginHeader['Version']) ) {
$this->cachedInstalledVersion = $pluginHeader['Version'];
return $pluginHeader['Version'];
} else {
//This can happen if the filename points to something that is not a plugin.
$this->triggerError(
sprintf(
"Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
$this->pluginFile
),
E_USER_WARNING
);
return null;
}
}
/**
* Get plugin's metadata from its file header.
*
* @return array
*/
protected function getPluginHeader() {
if ( !is_file($this->pluginAbsolutePath) ) {
//This can happen if the plugin filename is wrong.
$this->triggerError(
sprintf(
"Can't to read the plugin header for '%s'. The file does not exist.",
$this->pluginFile
),
E_USER_WARNING
);
return array();
}
if ( !function_exists('get_plugin_data') ){
/** @noinspection PhpIncludeInspection */
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
return get_plugin_data($this->pluginAbsolutePath, false, false);
}
/**
* @return array
*/
protected function getHeaderNames() {
return array(
'Name' => 'Plugin Name',
'PluginURI' => 'Plugin URI',
'Version' => 'Version',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
'Network' => 'Network',
//The newest WordPress version that this plugin requires or has been tested with.
//We support several different formats for compatibility with other libraries.
'Tested WP' => 'Tested WP',
'Requires WP' => 'Requires WP',
'Tested up to' => 'Tested up to',
'Requires at least' => 'Requires at least',
);
}
/**
* Intercept plugins_api() calls that request information about our plugin and
* use the configured API endpoint to satisfy them.
*
* @see plugins_api()
*
* @param mixed $result
* @param string $action
* @param array|object $args
* @return mixed
*/
public function injectInfo($result, $action = null, $args = null){
$relevant = ($action == 'plugin_information') && isset($args->slug) && (
($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
);
if ( !$relevant ) {
return $result;
}
$pluginInfo = $this->requestInfo();
$pluginInfo = apply_filters($this->getUniqueName('pre_inject_info'), $pluginInfo);
if ( $pluginInfo ) {
return $pluginInfo->toWpFormat();
}
return $result;
}
protected function shouldShowUpdates() {
//No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
//is usually different from the main plugin file so the update wouldn't show up properly anyway.
return !$this->isUnknownMuPlugin();
}
/**
* @param stdClass|null $updates
* @param stdClass $updateToAdd
* @return stdClass
*/
protected function addUpdateToList($updates, $updateToAdd) {
if ( $this->isMuPlugin() ) {
//WP does not support automatic update installation for mu-plugins, but we can
//still display a notice.
$updateToAdd->package = null;
}
return parent::addUpdateToList($updates, $updateToAdd);
}
/**
* @param stdClass|null $updates
* @return stdClass|null
*/
protected function removeUpdateFromList($updates) {
$updates = parent::removeUpdateFromList($updates);
if ( !empty($this->muPluginFile) && isset($updates, $updates->response) ) {
unset($updates->response[$this->muPluginFile]);
}
return $updates;
}
/**
* For plugins, the update array is indexed by the plugin filename relative to the "plugins"
* directory. Example: "plugin-name/plugin.php".
*
* @return string
*/
protected function getUpdateListKey() {
if ( $this->isMuPlugin() ) {
return $this->muPluginFile;
}
return $this->pluginFile;
}
/**
* Alias for isBeingUpgraded().
*
* @deprecated
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool
*/
public function isPluginBeingUpgraded($upgrader = null) {
return $this->isBeingUpgraded($upgrader);
}
/**
* Is there an update being installed for this plugin, right now?
*
* @param WP_Upgrader|null $upgrader
* @return bool
*/
public function isBeingUpgraded($upgrader = null) {
return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader);
}
/**
* Get the details of the currently available update, if any.
*
* If no updates are available, or if the last known update version is below or equal
* to the currently installed version, this method will return NULL.
*
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return Puc_v4p4_Plugin_Update|null
*/
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) ) {
/** @var Puc_v4p4_Plugin_Update $update */
$update->filename = $this->pluginFile;
}
return $update;
}
/**
* Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
* the new link will appear after the "Visit plugin site" link if present, otherwise
* after the "View plugin details" link.
*
* You can change the link text by using the "puc_manual_check_link-$slug" filter.
* Returning an empty string from the filter will disable the link.
*
* @param array $pluginMeta Array of meta links.
* @param string $pluginFile
* @return array
*/
public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
$isRelevant = ($pluginFile == $this->pluginFile)
|| (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);
if ( $isRelevant && $this->userCanInstallUpdates() ) {
$linkUrl = wp_nonce_url(
add_query_arg(
array(
'puc_check_for_updates' => 1,
'puc_slug' => $this->slug,
),
self_admin_url('plugins.php')
),
'puc_check_for_updates'
);
$linkText = apply_filters(
$this->getUniqueName('manual_check_link'),
__('Check for updates', 'plugin-update-checker')
);
if ( !empty($linkText) ) {
/** @noinspection HtmlUnknownTarget */
$pluginMeta[] = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
}
}
return $pluginMeta;
}
/**
* Add a "View Details" link to the plugin row in the "Plugins" page. By default,
* the new link will appear before the "Visit plugin site" link (if present).
*
* You can change the link text by using the "puc_view_details_link-$slug" filter.
* Returning an empty string from the filter will disable the link.
*
* You can change the position of the link using the
* "puc_view_details_link_position-$slug" filter.
* Returning 'before' or 'after' will place the link immediately before/after the
* "Visit plugin site" link
* Returning 'append' places the link after any existing links at the time of the hook.
* Returning 'replace' replaces the "Visit plugin site" link
* Returning anything else disables the link when there is a "Visit plugin site" link.
*
* If there is no "Visit plugin site" link 'append' is always used!
*
* @param array $pluginMeta Array of meta links.
* @param string $pluginFile
* @param array $pluginData Array of plugin header data.
* @return array
*/
public function addViewDetailsLink($pluginMeta, $pluginFile, $pluginData = array()) {
$isRelevant = ($pluginFile == $this->pluginFile)
|| (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);
if ( $isRelevant && $this->userCanInstallUpdates() && !isset($pluginData['slug']) ) {
$linkText = apply_filters($this->getUniqueName('view_details_link'), __('View details'));
if ( !empty($linkText) ) {
$viewDetailsLinkPosition = 'append';
//Find the "Visit plugin site" link (if present).
$visitPluginSiteLinkIndex = count($pluginMeta) - 1;
if ( $pluginData['PluginURI'] ) {
$escapedPluginUri = esc_url($pluginData['PluginURI']);
foreach ($pluginMeta as $linkIndex => $existingLink) {
if ( strpos($existingLink, $escapedPluginUri) !== false ) {
$visitPluginSiteLinkIndex = $linkIndex;
$viewDetailsLinkPosition = apply_filters(
$this->getUniqueName('view_details_link_position'),
'before'
);
break;
}
}
}
$viewDetailsLink = sprintf('<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
esc_url(network_admin_url('plugin-install.php?tab=plugin-information&plugin=' . urlencode($this->slug) .
'&TB_iframe=true&width=600&height=550')),
esc_attr(sprintf(__('More information about %s'), $pluginData['Name'])),
esc_attr($pluginData['Name']),
$linkText
);
switch ($viewDetailsLinkPosition) {
case 'before':
array_splice($pluginMeta, $visitPluginSiteLinkIndex, 0, $viewDetailsLink);
break;
case 'after':
array_splice($pluginMeta, $visitPluginSiteLinkIndex + 1, 0, $viewDetailsLink);
break;
case 'replace':
$pluginMeta[$visitPluginSiteLinkIndex] = $viewDetailsLink;
break;
case 'append':
default:
$pluginMeta[] = $viewDetailsLink;
break;
}
}
}
return $pluginMeta;
}
/**
* Check for updates when the user clicks the "Check for updates" link.
* @see self::addCheckForUpdatesLink()
*
* @return void
*/
public function handleManualCheck() {
$shouldCheck =
isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
&& $_GET['puc_slug'] == $this->slug
&& $this->userCanInstallUpdates()
&& check_admin_referer('puc_check_for_updates');
if ( $shouldCheck ) {
$update = $this->checkForUpdates();
$status = ($update === null) ? 'no_update' : 'update_available';
if ( ($update === null) && !empty($this->lastRequestApiErrors) ) {
//Some errors are not critical. For example, if PUC tries to retrieve the readme.txt
//file from GitHub and gets a 404, that's an API error, but it doesn't prevent updates
//from working. Maybe the plugin simply doesn't have a readme.
//Let's only show important errors.
$foundCriticalErrors = false;
$questionableErrorCodes = array(
'puc-github-http-error',
'puc-gitlab-http-error',
'puc-bitbucket-http-error',
);
foreach ($this->lastRequestApiErrors as $item) {
$wpError = $item['error'];
/** @var WP_Error $wpError */
if ( !in_array($wpError->get_error_code(), $questionableErrorCodes) ) {
$foundCriticalErrors = true;
break;
}
}
if ( $foundCriticalErrors ) {
$status = 'error';
set_site_transient($this->manualCheckErrorTransient, $this->lastRequestApiErrors, 60);
}
}
wp_redirect(add_query_arg(
array(
'puc_update_check_result' => $status,
'puc_slug' => $this->slug,
),
self_admin_url('plugins.php')
));
}
}
/**
* Display the results of a manual update check.
* @see self::handleManualCheck()
*
* You can change the result message by using the "puc_manual_check_message-$slug" filter.
*/
public function displayManualCheckResult() {
if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) {
$status = strval($_GET['puc_update_check_result']);
$title = $this->getPluginTitle();
$noticeClass = 'updated notice-success';
$details = '';
if ( $status == 'no_update' ) {
$message = sprintf(_x('The %s plugin is up to date.', 'the plugin title', 'plugin-update-checker'), $title);
} else if ( $status == 'update_available' ) {
$message = sprintf(_x('A new version of the %s plugin is available.', 'the plugin title', 'plugin-update-checker'), $title);
} else if ( $status === 'error' ) {
$message = sprintf(_x('Could not determine if updates are available for %s.', 'the plugin title', 'plugin-update-checker'), $title);
$noticeClass = 'error notice-error';
$details = $this->formatManualCheckErrors(get_site_transient($this->manualCheckErrorTransient));
delete_site_transient($this->manualCheckErrorTransient);
} else {
$message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status));
$noticeClass = 'error notice-error';
}
printf(
'<div class="notice %s is-dismissible"><p>%s</p>%s</div>',
$noticeClass,
apply_filters($this->getUniqueName('manual_check_message'), $message, $status),
$details
);
}
}
/**
* Format the list of errors that were thrown during an update check.
*
* @param array $errors
* @return string
*/
protected function formatManualCheckErrors($errors) {
if ( empty($errors) ) {
return '';
}
$output = '';
$showAsList = count($errors) > 1;
if ( $showAsList ) {
$output .= '<ol>';
$formatString = '<li>%1$s <code>%2$s</code></li>';
} else {
$formatString = '<p>%1$s <code>%2$s</code></p>';
}
foreach ($errors as $item) {
$wpError = $item['error'];
/** @var WP_Error $wpError */
$output .= sprintf(
$formatString,
$wpError->get_error_message(),
$wpError->get_error_code()
);
}
if ( $showAsList ) {
$output .= '</ol>';
}
return $output;
}
/**
* Get the translated plugin title.
*
* @return string
*/
protected function getPluginTitle() {
$title = '';
$header = $this->getPluginHeader();
if ( $header && !empty($header['Name']) && isset($header['TextDomain']) ) {
$title = translate($header['Name'], $header['TextDomain']);
}
return $title;
}
/**
* Check if the current user has the required permissions to install updates.
*
* @return bool
*/
public function userCanInstallUpdates() {
return current_user_can('update_plugins');
}
/**
* Check if the plugin file is inside the mu-plugins directory.
*
* @return bool
*/
protected function isMuPlugin() {
static $cachedResult = null;
if ( $cachedResult === null ) {
//Convert both paths to the canonical form before comparison.
$muPluginDir = realpath(WPMU_PLUGIN_DIR);
$pluginPath = realpath($this->pluginAbsolutePath);
$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
}
return $cachedResult;
}
/**
* MU plugins are partially supported, but only when we know which file in mu-plugins
* corresponds to this plugin.
*
* @return bool
*/
protected function isUnknownMuPlugin() {
return empty($this->muPluginFile) && $this->isMuPlugin();
}
/**
* Clear the cached plugin version. This method can be set up as a filter (hook) and will
* return the filter argument unmodified.
*
* @param mixed $filterArgument
* @return mixed
*/
public function clearCachedVersion($filterArgument = null) {
$this->cachedInstalledVersion = null;
return $filterArgument;
}
/**
* Get absolute path to the main plugin file.
*
* @return string
*/
public function getAbsolutePath() {
return $this->pluginAbsolutePath;
}
/**
* @return string
*/
public function getAbsoluteDirectoryPath() {
return dirname($this->pluginAbsolutePath);
}
/**
* Register a callback for filtering query arguments.
*
* The callback function should take one argument - an associative array of query arguments.
* It should return a modified array of query arguments.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addQueryArgFilter($callback){
$this->addFilter('request_info_query_args', $callback);
}
/**
* Register a callback for filtering arguments passed to wp_remote_get().
*
* The callback function should take one argument - an associative array of arguments -
* and return a modified array or arguments. See the WP documentation on wp_remote_get()
* for details on what arguments are available and how they work.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addHttpRequestArgFilter($callback) {
$this->addFilter('request_info_options', $callback);
}
/**
* Register a callback for filtering the plugin info retrieved from the external API.
*
* The callback function should take two arguments. If the plugin info was retrieved
* successfully, the first argument passed will be an instance of PluginInfo. Otherwise,
* it will be NULL. The second argument will be the corresponding return value of
* wp_remote_get (see WP docs for details).
*
* The callback function should return a new or modified instance of PluginInfo or NULL.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addResultFilter($callback) {
$this->addFilter('request_info_result', $callback, 10, 2);
}
protected function createDebugBarExtension() {
return new Puc_v4p4_DebugBar_PluginExtension($this);
}
}
endif;

View File

@@ -1,177 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Scheduler', false) ):
/**
* The scheduler decides when and how often to check for updates.
* It calls @see Puc_v4p4_UpdateChecker::checkForUpdates() to perform the actual checks.
*/
class Puc_v4p4_Scheduler {
public $checkPeriod = 12; //How often to check for updates (in hours).
public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
public $throttledCheckPeriod = 72;
protected $hourlyCheckHooks = array('load-update.php');
/**
* @var Puc_v4p4_UpdateChecker
*/
protected $updateChecker;
private $cronHook = null;
/**
* Scheduler constructor.
*
* @param Puc_v4p4_UpdateChecker $updateChecker
* @param int $checkPeriod How often to check for updates (in hours).
* @param array $hourlyHooks
*/
public function __construct($updateChecker, $checkPeriod, $hourlyHooks = array('load-plugins.php')) {
$this->updateChecker = $updateChecker;
$this->checkPeriod = $checkPeriod;
//Set up the periodic update checks
$this->cronHook = $this->updateChecker->getUniqueName('cron_check_updates');
if ( $this->checkPeriod > 0 ){
//Trigger the check via Cron.
//Try to use one of the default schedules if possible as it's less likely to conflict
//with other plugins and their custom schedules.
$defaultSchedules = array(
1 => 'hourly',
12 => 'twicedaily',
24 => 'daily',
);
if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
$scheduleName = $defaultSchedules[$this->checkPeriod];
} else {
//Use a custom cron schedule.
$scheduleName = 'every' . $this->checkPeriod . 'hours';
add_filter('cron_schedules', array($this, '_addCustomSchedule'));
}
if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
wp_schedule_event(time(), $scheduleName, $this->cronHook);
}
add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
//In case Cron is disabled or unreliable, we also manually trigger
//the periodic checks while the user is browsing the Dashboard.
add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );
//Like WordPress itself, we check more often on certain pages.
/** @see wp_update_plugins */
add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
//"load-update.php" and "load-plugins.php" or "load-themes.php".
$this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks);
foreach($this->hourlyCheckHooks as $hook) {
add_action($hook, array($this, 'maybeCheckForUpdates'));
}
//This hook fires after a bulk update is complete.
add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0);
} else {
//Periodic checks are disabled.
wp_clear_scheduled_hook($this->cronHook);
}
}
/**
* Check for updates if the configured check interval has already elapsed.
* Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
*
* You can override the default behaviour by using the "puc_check_now-$slug" filter.
* The filter callback will be passed three parameters:
* - Current decision. TRUE = check updates now, FALSE = don't check now.
* - Last check time as a Unix timestamp.
* - Configured check period in hours.
* Return TRUE to check for updates immediately, or FALSE to cancel.
*
* This method is declared public because it's a hook callback. Calling it directly is not recommended.
*/
public function maybeCheckForUpdates(){
if ( empty($this->checkPeriod) ){
return;
}
$state = $this->updateChecker->getUpdateState();
$shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod());
//Let plugin authors substitute their own algorithm.
$shouldCheck = apply_filters(
$this->updateChecker->getUniqueName('check_now'),
$shouldCheck,
$state->getLastCheck(),
$this->checkPeriod
);
if ( $shouldCheck ) {
$this->updateChecker->checkForUpdates();
}
}
/**
* Calculate the actual check period based on the current status and environment.
*
* @return int Check period in seconds.
*/
protected function getEffectiveCheckPeriod() {
$currentFilter = current_filter();
if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
//Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
$period = 60;
} else if ( in_array($currentFilter, $this->hourlyCheckHooks) ) {
//Also check more often on /wp-admin/update.php and the "Plugins" or "Themes" page.
$period = 3600;
} else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
//Check less frequently if it's already known that an update is available.
$period = $this->throttledCheckPeriod * 3600;
} else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
//WordPress cron schedules are not exact, so lets do an update check even
//if slightly less than $checkPeriod hours have elapsed since the last check.
$cronFuzziness = 20 * 60;
$period = $this->checkPeriod * 3600 - $cronFuzziness;
} else {
$period = $this->checkPeriod * 3600;
}
return $period;
}
/**
* Add our custom schedule to the array of Cron schedules used by WP.
*
* @param array $schedules
* @return array
*/
public function _addCustomSchedule($schedules){
if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
$scheduleName = 'every' . $this->checkPeriod . 'hours';
$schedules[$scheduleName] = array(
'interval' => $this->checkPeriod * 3600,
'display' => sprintf('Every %d hours', $this->checkPeriod),
);
}
return $schedules;
}
/**
* Remove the scheduled cron event that the library uses to check for updates.
*
* @return void
*/
public function removeUpdaterCron(){
wp_clear_scheduled_hook($this->cronHook);
}
/**
* Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
*
* @return string
*/
public function getCronHookName() {
return $this->cronHook;
}
}
endif;

View File

@@ -1,207 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_StateStore', false) ):
class Puc_v4p4_StateStore {
/**
* @var int Last update check timestamp.
*/
protected $lastCheck = 0;
/**
* @var string Version number.
*/
protected $checkedVersion = '';
/**
* @var Puc_v4p4_Update|null Cached update.
*/
protected $update = null;
/**
* @var string Site option name.
*/
private $optionName = '';
/**
* @var bool Whether we've already tried to load the state from the database.
*/
private $isLoaded = false;
public function __construct($optionName) {
$this->optionName = $optionName;
}
/**
* Get time elapsed since the last update check.
*
* If there are no recorded update checks, this method returns a large arbitrary number
* (i.e. time since the Unix epoch).
*
* @return int Elapsed time in seconds.
*/
public function timeSinceLastCheck() {
$this->lazyLoad();
return time() - $this->lastCheck;
}
/**
* @return int
*/
public function getLastCheck() {
$this->lazyLoad();
return $this->lastCheck;
}
/**
* Set the time of the last update check to the current timestamp.
*
* @return $this
*/
public function setLastCheckToNow() {
$this->lazyLoad();
$this->lastCheck = time();
return $this;
}
/**
* @return null|Puc_v4p4_Update
*/
public function getUpdate() {
$this->lazyLoad();
return $this->update;
}
/**
* @param Puc_v4p4_Update|null $update
* @return $this
*/
public function setUpdate(Puc_v4p4_Update $update = null) {
$this->lazyLoad();
$this->update = $update;
return $this;
}
/**
* @return string
*/
public function getCheckedVersion() {
$this->lazyLoad();
return $this->checkedVersion;
}
/**
* @param string $version
* @return $this
*/
public function setCheckedVersion($version) {
$this->lazyLoad();
$this->checkedVersion = strval($version);
return $this;
}
/**
* Get translation updates.
*
* @return array
*/
public function getTranslations() {
$this->lazyLoad();
if ( isset($this->update, $this->update->translations) ) {
return $this->update->translations;
}
return array();
}
/**
* Set translation updates.
*
* @param array $translationUpdates
*/
public function setTranslations($translationUpdates) {
$this->lazyLoad();
if ( isset($this->update) ) {
$this->update->translations = $translationUpdates;
$this->save();
}
}
public function save() {
$state = new stdClass();
$state->lastCheck = $this->lastCheck;
$state->checkedVersion = $this->checkedVersion;
if ( isset($this->update)) {
$state->update = $this->update->toStdClass();
$updateClass = get_class($this->update);
$state->updateClass = $updateClass;
$prefix = $this->getLibPrefix();
if ( Puc_v4p4_Utils::startsWith($updateClass, $prefix) ) {
$state->updateBaseClass = substr($updateClass, strlen($prefix));
}
}
update_site_option($this->optionName, $state);
$this->isLoaded = true;
}
/**
* @return $this
*/
public function lazyLoad() {
if ( !$this->isLoaded ) {
$this->load();
}
return $this;
}
protected function load() {
$this->isLoaded = true;
$state = get_site_option($this->optionName, null);
if ( !is_object($state) ) {
$this->lastCheck = 0;
$this->checkedVersion = '';
$this->update = null;
return;
}
$this->lastCheck = intval(Puc_v4p4_Utils::get($state, 'lastCheck', 0));
$this->checkedVersion = Puc_v4p4_Utils::get($state, 'checkedVersion', '');
$this->update = null;
if ( isset($state->update) ) {
//This mess is due to the fact that the want the update class from this version
//of the library, not the version that saved the update.
$updateClass = null;
if ( isset($state->updateBaseClass) ) {
$updateClass = $this->getLibPrefix() . $state->updateBaseClass;
} else if ( isset($state->updateClass) && class_exists($state->updateClass) ) {
$updateClass = $state->updateClass;
}
if ( $updateClass !== null ) {
$this->update = call_user_func(array($updateClass, 'fromObject'), $state->update);
}
}
}
public function delete() {
delete_site_option($this->optionName);
$this->lastCheck = 0;
$this->checkedVersion = '';
$this->update = null;
}
private function getLibPrefix() {
$parts = explode('_', __CLASS__, 3);
return $parts[0] . '_' . $parts[1] . '_';
}
}
endif;

View File

@@ -1,84 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Theme_Update', false) ):
class Puc_v4p4_Theme_Update extends Puc_v4p4_Update {
public $details_url = '';
protected static $extraFields = array('details_url');
/**
* Transform the metadata into the format used by WordPress core.
* Note the inconsistency: WP stores plugin updates as objects and theme updates as arrays.
*
* @return array
*/
public function toWpFormat() {
$update = array(
'theme' => $this->slug,
'new_version' => $this->version,
'url' => $this->details_url,
);
if ( !empty($this->download_url) ) {
$update['package'] = $this->download_url;
}
return $update;
}
/**
* Create a new instance of Theme_Update from its JSON-encoded representation.
*
* @param string $json Valid JSON string representing a theme information object.
* @return self New instance of ThemeUpdate, or NULL on error.
*/
public static function fromJson($json) {
$instance = new self();
if ( !parent::createFromJson($json, $instance) ) {
return null;
}
return $instance;
}
/**
* Create a new instance by copying the necessary fields from another object.
*
* @param StdClass|Puc_v4p4_Theme_Update $object The source object.
* @return Puc_v4p4_Theme_Update The new copy.
*/
public static function fromObject($object) {
$update = new self();
$update->copyFields($object, $update);
return $update;
}
/**
* Basic validation.
*
* @param StdClass $apiResponse
* @return bool|WP_Error
*/
protected function validateMetadata($apiResponse) {
$required = array('version', 'details_url');
foreach($required as $key) {
if ( !isset($apiResponse->$key) || empty($apiResponse->$key) ) {
return new WP_Error(
'tuc-invalid-metadata',
sprintf('The theme metadata is missing the required "%s" key.', $key)
);
}
}
return true;
}
protected function getFieldNames() {
return array_merge(parent::getFieldNames(), self::$extraFields);
}
protected function getPrefixedFilter($tag) {
return parent::getPrefixedFilter($tag) . '_theme';
}
}
endif;

View File

@@ -1,177 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Theme_UpdateChecker', false) ):
class Puc_v4p4_Theme_UpdateChecker extends Puc_v4p4_UpdateChecker {
protected $filterSuffix = 'theme';
protected $updateTransient = 'update_themes';
protected $translationType = 'theme';
/**
* @var string Theme directory name.
*/
protected $stylesheet;
/**
* @var WP_Theme Theme object.
*/
protected $theme;
public function __construct($metadataUrl, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
if ( $stylesheet === null ) {
$stylesheet = get_stylesheet();
}
$this->stylesheet = $stylesheet;
$this->theme = wp_get_theme($this->stylesheet);
parent::__construct(
$metadataUrl,
$stylesheet,
$customSlug ? $customSlug : $stylesheet,
$checkPeriod,
$optionName
);
}
/**
* For themes, the update array is indexed by theme directory name.
*
* @return string
*/
protected function getUpdateListKey() {
return $this->directoryName;
}
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* @return Puc_v4p4_Update|null An instance of Update, or NULL when no updates are available.
*/
public function requestUpdate() {
list($themeUpdate, $result) = $this->requestMetadata('Puc_v4p4_Theme_Update', 'request_update');
if ( $themeUpdate !== null ) {
/** @var Puc_v4p4_Theme_Update $themeUpdate */
$themeUpdate->slug = $this->slug;
}
$themeUpdate = $this->filterUpdateResult($themeUpdate, $result);
return $themeUpdate;
}
public function userCanInstallUpdates() {
return current_user_can('update_themes');
}
/**
* Get the currently installed version of the plugin or theme.
*
* @return string Version number.
*/
public function getInstalledVersion() {
return $this->theme->get('Version');
}
/**
* @return string
*/
public function getAbsoluteDirectoryPath() {
if ( method_exists($this->theme, 'get_stylesheet_directory') ) {
return $this->theme->get_stylesheet_directory(); //Available since WP 3.4.
}
return get_theme_root($this->stylesheet) . '/' . $this->stylesheet;
}
/**
* Create an instance of the scheduler.
*
* @param int $checkPeriod
* @return Puc_v4p4_Scheduler
*/
protected function createScheduler($checkPeriod) {
return new Puc_v4p4_Scheduler($this, $checkPeriod, array('load-themes.php'));
}
/**
* Is there an update being installed right now for this theme?
*
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool
*/
public function isBeingUpgraded($upgrader = null) {
return $this->upgraderStatus->isThemeBeingUpgraded($this->stylesheet, $upgrader);
}
protected function createDebugBarExtension() {
return new Puc_v4p4_DebugBar_Extension($this, 'Puc_v4p4_DebugBar_ThemePanel');
}
/**
* Register a callback for filtering query arguments.
*
* The callback function should take one argument - an associative array of query arguments.
* It should return a modified array of query arguments.
*
* @param callable $callback
* @return void
*/
public function addQueryArgFilter($callback){
$this->addFilter('request_update_query_args', $callback);
}
/**
* Register a callback for filtering arguments passed to wp_remote_get().
*
* The callback function should take one argument - an associative array of arguments -
* and return a modified array or arguments. See the WP documentation on wp_remote_get()
* for details on what arguments are available and how they work.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addHttpRequestArgFilter($callback) {
$this->addFilter('request_update_options', $callback);
}
/**
* Register a callback for filtering theme updates retrieved from the external API.
*
* The callback function should take two arguments. If the theme update was retrieved
* successfully, the first argument passed will be an instance of Theme_Update. Otherwise,
* it will be NULL. The second argument will be the corresponding return value of
* wp_remote_get (see WP docs for details).
*
* The callback function should return a new or modified instance of Theme_Update or NULL.
*
* @uses add_filter() This method is a convenience wrapper for add_filter().
*
* @param callable $callback
* @return void
*/
public function addResultFilter($callback) {
$this->addFilter('request_update_result', $callback, 10, 2);
}
/**
* @return array
*/
protected function getHeaderNames() {
return array(
'Name' => 'Theme Name',
'ThemeURI' => 'Theme URI',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'Version' => 'Version',
'Template' => 'Template',
'Status' => 'Status',
'Tags' => 'Tags',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
);
}
}
endif;

View File

@@ -1,34 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Update', false) ):
/**
* A simple container class for holding information about an available update.
*
* @author Janis Elsts
* @access public
*/
abstract class Puc_v4p4_Update extends Puc_v4p4_Metadata {
public $slug;
public $version;
public $download_url;
public $translations = array();
/**
* @return string[]
*/
protected function getFieldNames() {
return array('slug', 'version', 'download_url', 'translations');
}
public function toWpFormat() {
$update = new stdClass();
$update->slug = $this->slug;
$update->new_version = $this->version;
$update->package = $this->download_url;
return $update;
}
}
endif;

View File

@@ -1,906 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_UpdateChecker', false) ):
abstract class Puc_v4p4_UpdateChecker {
protected $filterSuffix = '';
protected $updateTransient = '';
protected $translationType = ''; //"plugin" or "theme".
/**
* Set to TRUE to enable error reporting. Errors are raised using trigger_error()
* and should be logged to the standard PHP error log.
* @var bool
*/
public $debugMode = null;
/**
* @var string Where to store the update info.
*/
public $optionName = '';
/**
* @var string The URL of the metadata file.
*/
public $metadataUrl = '';
/**
* @var string Plugin or theme directory name.
*/
public $directoryName = '';
/**
* @var string The slug that will be used in update checker hooks and remote API requests.
* Usually matches the directory name unless the plugin/theme directory has been renamed.
*/
public $slug = '';
/**
* @var Puc_v4p4_Scheduler
*/
public $scheduler;
/**
* @var Puc_v4p4_UpgraderStatus
*/
protected $upgraderStatus;
/**
* @var Puc_v4p4_StateStore
*/
protected $updateState;
/**
* @var array List of API errors triggered during the last checkForUpdates() call.
*/
protected $lastRequestApiErrors = array();
public function __construct($metadataUrl, $directoryName, $slug = null, $checkPeriod = 12, $optionName = '') {
$this->debugMode = (bool)(constant('WP_DEBUG'));
$this->metadataUrl = $metadataUrl;
$this->directoryName = $directoryName;
$this->slug = !empty($slug) ? $slug : $this->directoryName;
$this->optionName = $optionName;
if ( empty($this->optionName) ) {
//BC: Initially the library only supported plugin updates and didn't use type prefixes
//in the option name. Lets use the same prefix-less name when possible.
if ( $this->filterSuffix === '' ) {
$this->optionName = 'external_updates-' . $this->slug;
} else {
$this->optionName = $this->getUniqueName('external_updates');
}
}
$this->scheduler = $this->createScheduler($checkPeriod);
$this->upgraderStatus = new Puc_v4p4_UpgraderStatus();
$this->updateState = new Puc_v4p4_StateStore($this->optionName);
if ( did_action('init') ) {
$this->loadTextDomain();
} else {
add_action('init', array($this, 'loadTextDomain'));
}
$this->installHooks();
}
/**
* @internal
*/
public function loadTextDomain() {
//We're not using load_plugin_textdomain() or its siblings because figuring out where
//the library is located (plugin, mu-plugin, theme, custom wp-content paths) is messy.
$domain = 'plugin-update-checker';
$locale = apply_filters(
'plugin_locale',
(is_admin() && function_exists('get_user_locale')) ? get_user_locale() : get_locale(),
$domain
);
$moFile = $domain . '-' . $locale . '.mo';
$path = realpath(dirname(__FILE__) . '/../../languages');
if ($path && file_exists($path)) {
load_textdomain($domain, $path . '/' . $moFile);
}
}
protected function installHooks() {
//Insert our update info into the update array maintained by WP.
add_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate'));
//Insert translation updates into the update list.
add_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates'));
//Clear translation updates when WP clears the update cache.
//This needs to be done directly because the library doesn't actually remove obsolete plugin updates,
//it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O.
add_action(
'delete_site_transient_' . $this->updateTransient,
array($this, 'clearCachedTranslationUpdates')
);
//Rename the update directory to be the same as the existing directory.
if ( $this->directoryName !== '.' ) {
add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);
}
//Allow HTTP requests to the metadata URL even if it's on a local host.
add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2);
//DebugBar integration.
if ( did_action('plugins_loaded') ) {
$this->maybeInitDebugBar();
} else {
add_action('plugins_loaded', array($this, 'maybeInitDebugBar'));
}
}
/**
* Remove hooks that were added by this update checker instance.
*/
protected function removeHooks() {
remove_filter('site_transient_' . $this->updateTransient, array($this,'injectUpdate'));
remove_filter('site_transient_' . $this->updateTransient, array($this, 'injectTranslationUpdates'));
remove_action(
'delete_site_transient_' . $this->updateTransient,
array($this, 'clearCachedTranslationUpdates')
);
remove_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10);
remove_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10);
remove_action('plugins_loaded', array($this, 'maybeInitDebugBar'));
remove_action('init', array($this, 'loadTextDomain'));
}
/**
* Check if the current user has the required permissions to install updates.
*
* @return bool
*/
abstract public function userCanInstallUpdates();
/**
* Explicitly allow HTTP requests to the metadata URL.
*
* WordPress has a security feature where the HTTP API will reject all requests that are sent to
* another site hosted on the same server as the current site (IP match), a local host, or a local
* IP, unless the host exactly matches the current site.
*
* This feature is opt-in (at least in WP 4.4). Apparently some people enable it.
*
* That can be a problem when you're developing your plugin and you decide to host the update information
* on the same server as your test site. Update requests will mysteriously fail.
*
* We fix that by adding an exception for the metadata host.
*
* @param bool $allow
* @param string $host
* @return bool
*/
public function allowMetadataHost($allow, $host) {
static $metadataHost = 0; //Using 0 instead of NULL because parse_url can return NULL.
if ( $metadataHost === 0 ) {
$metadataHost = @parse_url($this->metadataUrl, PHP_URL_HOST);
}
if ( is_string($metadataHost) && (strtolower($host) === strtolower($metadataHost)) ) {
return true;
}
return $allow;
}
/**
* Create an instance of the scheduler.
*
* This is implemented as a method to make it possible for plugins to subclass the update checker
* and substitute their own scheduler.
*
* @param int $checkPeriod
* @return Puc_v4p4_Scheduler
*/
abstract protected function createScheduler($checkPeriod);
/**
* Check for updates. The results are stored in the DB option specified in $optionName.
*
* @return Puc_v4p4_Update|null
*/
public function checkForUpdates() {
$installedVersion = $this->getInstalledVersion();
//Fail silently if we can't find the plugin/theme or read its header.
if ( $installedVersion === null ) {
$this->triggerError(
sprintf('Skipping update check for %s - installed version unknown.', $this->slug),
E_USER_WARNING
);
return null;
}
//Start collecting API errors.
$this->lastRequestApiErrors = array();
add_action('puc_api_error', array($this, 'collectApiErrors'), 10, 4);
$state = $this->updateState;
$state->setLastCheckToNow()
->setCheckedVersion($installedVersion)
->save(); //Save before checking in case something goes wrong
$state->setUpdate($this->requestUpdate());
$state->save();
//Stop collecting API errors.
remove_action('puc_api_error', array($this, 'collectApiErrors'), 10);
return $this->getUpdate();
}
/**
* Load the update checker state from the DB.
*
* @return Puc_v4p4_StateStore
*/
public function getUpdateState() {
return $this->updateState->lazyLoad();
}
/**
* Reset update checker state - i.e. last check time, cached update data and so on.
*
* Call this when your plugin is being uninstalled, or if you want to
* clear the update cache.
*/
public function resetUpdateState() {
$this->updateState->delete();
}
/**
* Get the details of the currently available update, if any.
*
* If no updates are available, or if the last known update version is below or equal
* to the currently installed version, this method will return NULL.
*
* Uses cached update data. To retrieve update information straight from
* the metadata URL, call requestUpdate() instead.
*
* @return Puc_v4p4_Update|null
*/
public function getUpdate() {
$update = $this->updateState->getUpdate();
//Is there an update available?
if ( isset($update) ) {
//Check if the update is actually newer than the currently installed version.
$installedVersion = $this->getInstalledVersion();
if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
return $update;
}
}
return null;
}
/**
* Retrieve the latest update (if any) from the configured API endpoint.
*
* Subclasses should run the update through filterUpdateResult before returning it.
*
* @return Puc_v4p4_Update An instance of Update, or NULL when no updates are available.
*/
abstract public function requestUpdate();
/**
* Filter the result of a requestUpdate() call.
*
* @param Puc_v4p4_Update|null $update
* @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any.
* @return Puc_v4p4_Update
*/
protected function filterUpdateResult($update, $httpResult = null) {
//Let plugins/themes modify the update.
$update = apply_filters($this->getUniqueName('request_update_result'), $update, $httpResult);
if ( isset($update, $update->translations) ) {
//Keep only those translation updates that apply to this site.
$update->translations = $this->filterApplicableTranslations($update->translations);
}
return $update;
}
/**
* Get the currently installed version of the plugin or theme.
*
* @return string|null Version number.
*/
abstract public function getInstalledVersion();
/**
* Get the full path of the plugin or theme directory.
*
* @return string
*/
abstract public function getAbsoluteDirectoryPath();
/**
* Trigger a PHP error, but only when $debugMode is enabled.
*
* @param string $message
* @param int $errorType
*/
protected function triggerError($message, $errorType) {
if ($this->isDebugModeEnabled()) {
trigger_error($message, $errorType);
}
}
/**
* @return bool
*/
protected function isDebugModeEnabled() {
if ($this->debugMode === null) {
$this->debugMode = (bool)(constant('WP_DEBUG'));
}
return $this->debugMode;
}
/**
* Get the full name of an update checker filter, action or DB entry.
*
* This method adds the "puc_" prefix and the "-$slug" suffix to the filter name.
* For example, "pre_inject_update" becomes "puc_pre_inject_update-plugin-slug".
*
* @param string $baseTag
* @return string
*/
public function getUniqueName($baseTag) {
$name = 'puc_' . $baseTag;
if ($this->filterSuffix !== '') {
$name .= '_' . $this->filterSuffix;
}
return $name . '-' . $this->slug;
}
/**
* Store API errors that are generated when checking for updates.
*
* @internal
* @param WP_Error $error
* @param array|null $httpResponse
* @param string|null $url
* @param string|null $slug
*/
public function collectApiErrors($error, $httpResponse = null, $url = null, $slug = null) {
if ( isset($slug) && ($slug !== $this->slug) ) {
return;
}
$this->lastRequestApiErrors[] = array(
'error' => $error,
'httpResponse' => $httpResponse,
'url' => $url,
);
}
/**
* @return array
*/
public function getLastRequestApiErrors() {
return $this->lastRequestApiErrors;
}
/* -------------------------------------------------------------------
* PUC filters and filter utilities
* -------------------------------------------------------------------
*/
/**
* Register a callback for one of the update checker filters.
*
* Identical to add_filter(), except it automatically adds the "puc_" prefix
* and the "-$slug" suffix to the filter name. For example, "request_info_result"
* becomes "puc_request_info_result-your_plugin_slug".
*
* @param string $tag
* @param callable $callback
* @param int $priority
* @param int $acceptedArgs
*/
public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
add_filter($this->getUniqueName($tag), $callback, $priority, $acceptedArgs);
}
/* -------------------------------------------------------------------
* Inject updates
* -------------------------------------------------------------------
*/
/**
* Insert the latest update (if any) into the update list maintained by WP.
*
* @param stdClass $updates Update list.
* @return stdClass Modified update list.
*/
public function injectUpdate($updates) {
//Is there an update to insert?
$update = $this->getUpdate();
if ( !$this->shouldShowUpdates() ) {
$update = null;
}
if ( !empty($update) ) {
//Let plugins filter the update info before it's passed on to WordPress.
$update = apply_filters($this->getUniqueName('pre_inject_update'), $update);
$updates = $this->addUpdateToList($updates, $update->toWpFormat());
} else {
//Clean up any stale update info.
$updates = $this->removeUpdateFromList($updates);
}
return $updates;
}
/**
* @param stdClass|null $updates
* @param stdClass|array $updateToAdd
* @return stdClass
*/
protected function addUpdateToList($updates, $updateToAdd) {
if ( !is_object($updates) ) {
$updates = new stdClass();
$updates->response = array();
}
$updates->response[$this->getUpdateListKey()] = $updateToAdd;
return $updates;
}
/**
* @param stdClass|null $updates
* @return stdClass|null
*/
protected function removeUpdateFromList($updates) {
if ( isset($updates, $updates->response) ) {
unset($updates->response[$this->getUpdateListKey()]);
}
return $updates;
}
/**
* Get the key that will be used when adding updates to the update list that's maintained
* by the WordPress core. The list is always an associative array, but the key is different
* for plugins and themes.
*
* @return string
*/
abstract protected function getUpdateListKey();
/**
* Should we show available updates?
*
* Usually the answer is "yes", but there are exceptions. For example, WordPress doesn't
* support automatic updates installation for mu-plugins, so PUC usually won't show update
* notifications in that case. See the plugin-specific subclass for details.
*
* Note: This method only applies to updates that are displayed (or not) in the WordPress
* admin. It doesn't affect APIs like requestUpdate and getUpdate.
*
* @return bool
*/
protected function shouldShowUpdates() {
return true;
}
/* -------------------------------------------------------------------
* JSON-based update API
* -------------------------------------------------------------------
*/
/**
* Retrieve plugin or theme metadata from the JSON document at $this->metadataUrl.
*
* @param string $metaClass Parse the JSON as an instance of this class. It must have a static fromJson method.
* @param string $filterRoot
* @param array $queryArgs Additional query arguments.
* @return array [Puc_v4p4_Metadata|null, array|WP_Error] A metadata instance and the value returned by wp_remote_get().
*/
protected function requestMetadata($metaClass, $filterRoot, $queryArgs = array()) {
//Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
$queryArgs = array_merge(
array(
'installed_version' => strval($this->getInstalledVersion()),
'php' => phpversion(),
'locale' => get_locale(),
),
$queryArgs
);
$queryArgs = apply_filters($this->getUniqueName($filterRoot . '_query_args'), $queryArgs);
//Various options for the wp_remote_get() call. Plugins can filter these, too.
$options = array(
'timeout' => 10, //seconds
'headers' => array(
'Accept' => 'application/json',
),
);
$options = apply_filters($this->getUniqueName($filterRoot . '_options'), $options);
//The metadata file should be at 'http://your-api.com/url/here/$slug/info.json'
$url = $this->metadataUrl;
if ( !empty($queryArgs) ){
$url = add_query_arg($queryArgs, $url);
}
$result = wp_remote_get($url, $options);
$result = apply_filters($this->getUniqueName('request_metadata_http_result'), $result, $url, $options);
//Try to parse the response
$status = $this->validateApiResponse($result);
$metadata = null;
if ( !is_wp_error($status) ){
$metadata = call_user_func(array($metaClass, 'fromJson'), $result['body']);
} else {
do_action('puc_api_error', $status, $result, $url, $this->slug);
$this->triggerError(
sprintf('The URL %s does not point to a valid metadata file. ', $url)
. $status->get_error_message(),
E_USER_WARNING
);
}
return array($metadata, $result);
}
/**
* Check if $result is a successful update API response.
*
* @param array|WP_Error $result
* @return true|WP_Error
*/
protected function validateApiResponse($result) {
if ( is_wp_error($result) ) { /** @var WP_Error $result */
return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
}
if ( !isset($result['response']['code']) ) {
return new WP_Error(
'puc_no_response_code',
'wp_remote_get() returned an unexpected result.'
);
}
if ( $result['response']['code'] !== 200 ) {
return new WP_Error(
'puc_unexpected_response_code',
'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
);
}
if ( empty($result['body']) ) {
return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
}
return true;
}
/* -------------------------------------------------------------------
* Language packs / Translation updates
* -------------------------------------------------------------------
*/
/**
* Filter a list of translation updates and return a new list that contains only updates
* that apply to the current site.
*
* @param array $translations
* @return array
*/
protected function filterApplicableTranslations($translations) {
$languages = array_flip(array_values(get_available_languages()));
$installedTranslations = $this->getInstalledTranslations();
$applicableTranslations = array();
foreach($translations as $translation) {
//Does it match one of the available core languages?
$isApplicable = array_key_exists($translation->language, $languages);
//Is it more recent than an already-installed translation?
if ( isset($installedTranslations[$translation->language]) ) {
$updateTimestamp = strtotime($translation->updated);
$installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']);
$isApplicable = $updateTimestamp > $installedTimestamp;
}
if ( $isApplicable ) {
$applicableTranslations[] = $translation;
}
}
return $applicableTranslations;
}
/**
* Get a list of installed translations for this plugin or theme.
*
* @return array
*/
protected function getInstalledTranslations() {
if ( !function_exists('wp_get_installed_translations') ) {
return array();
}
$installedTranslations = wp_get_installed_translations($this->translationType . 's');
if ( isset($installedTranslations[$this->directoryName]) ) {
$installedTranslations = $installedTranslations[$this->directoryName];
} else {
$installedTranslations = array();
}
return $installedTranslations;
}
/**
* Insert translation updates into the list maintained by WordPress.
*
* @param stdClass $updates
* @return stdClass
*/
public function injectTranslationUpdates($updates) {
$translationUpdates = $this->getTranslationUpdates();
if ( empty($translationUpdates) ) {
return $updates;
}
//Being defensive.
if ( !is_object($updates) ) {
$updates = new stdClass();
}
if ( !isset($updates->translations) ) {
$updates->translations = array();
}
//In case there's a name collision with a plugin or theme hosted on wordpress.org,
//remove any preexisting updates that match our thing.
$updates->translations = array_values(array_filter(
$updates->translations,
array($this, 'isNotMyTranslation')
));
//Add our updates to the list.
foreach($translationUpdates as $update) {
$convertedUpdate = array_merge(
array(
'type' => $this->translationType,
'slug' => $this->directoryName,
'autoupdate' => 0,
//AFAICT, WordPress doesn't actually use the "version" field for anything.
//But lets make sure it's there, just in case.
'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)),
),
(array)$update
);
$updates->translations[] = $convertedUpdate;
}
return $updates;
}
/**
* Get a list of available translation updates.
*
* This method will return an empty array if there are no updates.
* Uses cached update data.
*
* @return array
*/
public function getTranslationUpdates() {
return $this->updateState->getTranslations();
}
/**
* Remove all cached translation updates.
*
* @see wp_clean_update_cache
*/
public function clearCachedTranslationUpdates() {
$this->updateState->setTranslations(array());
}
/**
* Filter callback. Keeps only translations that *don't* match this plugin or theme.
*
* @param array $translation
* @return bool
*/
protected function isNotMyTranslation($translation) {
$isMatch = isset($translation['type'], $translation['slug'])
&& ($translation['type'] === $this->translationType)
&& ($translation['slug'] === $this->directoryName);
return !$isMatch;
}
/* -------------------------------------------------------------------
* Fix directory name when installing updates
* -------------------------------------------------------------------
*/
/**
* Rename the update directory to match the existing plugin/theme directory.
*
* When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
* exactly one directory, and that the directory name will be the same as the directory where
* the plugin or theme is currently installed.
*
* GitHub and other repositories provide ZIP downloads, but they often use directory names like
* "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
*
* This is a hook callback. Don't call it from a plugin.
*
* @access protected
*
* @param string $source The directory to copy to /wp-content/plugins or /wp-content/themes. Usually a subdirectory of $remoteSource.
* @param string $remoteSource WordPress has extracted the update to this directory.
* @param WP_Upgrader $upgrader
* @return string|WP_Error
*/
public function fixDirectoryName($source, $remoteSource, $upgrader) {
global $wp_filesystem;
/** @var WP_Filesystem_Base $wp_filesystem */
//Basic sanity checks.
if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
return $source;
}
//If WordPress is upgrading anything other than our plugin/theme, leave the directory name unchanged.
if ( !$this->isBeingUpgraded($upgrader) ) {
return $source;
}
//Rename the source to match the existing directory.
$correctedSource = trailingslashit($remoteSource) . $this->directoryName . '/';
if ( $source !== $correctedSource ) {
//The update archive should contain a single directory that contains the rest of plugin/theme files.
//Otherwise, WordPress will try to copy the entire working directory ($source == $remoteSource).
//We can't rename $remoteSource because that would break WordPress code that cleans up temporary files
//after update.
if ( $this->isBadDirectoryStructure($remoteSource) ) {
return new WP_Error(
'puc-incorrect-directory-structure',
sprintf(
'The directory structure of the update is incorrect. All files should be inside ' .
'a directory named <span class="code">%s</span>, not at the root of the ZIP archive.',
htmlentities($this->slug)
)
);
}
/** @var WP_Upgrader_Skin $upgrader ->skin */
$upgrader->skin->feedback(sprintf(
'Renaming %s to %s&#8230;',
'<span class="code">' . basename($source) . '</span>',
'<span class="code">' . $this->directoryName . '</span>'
));
if ( $wp_filesystem->move($source, $correctedSource, true) ) {
$upgrader->skin->feedback('Directory successfully renamed.');
return $correctedSource;
} else {
return new WP_Error(
'puc-rename-failed',
'Unable to rename the update to match the existing directory.'
);
}
}
return $source;
}
/**
* Is there an update being installed right now, for this plugin or theme?
*
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool
*/
abstract public function isBeingUpgraded($upgrader = null);
/**
* Check for incorrect update directory structure. An update must contain a single directory,
* all other files should be inside that directory.
*
* @param string $remoteSource Directory path.
* @return bool
*/
protected function isBadDirectoryStructure($remoteSource) {
global $wp_filesystem;
/** @var WP_Filesystem_Base $wp_filesystem */
$sourceFiles = $wp_filesystem->dirlist($remoteSource);
if ( is_array($sourceFiles) ) {
$sourceFiles = array_keys($sourceFiles);
$firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath));
}
//Assume it's fine.
return false;
}
/* -------------------------------------------------------------------
* File header parsing
* -------------------------------------------------------------------
*/
/**
* Parse plugin or theme metadata from the header comment.
*
* This is basically a simplified version of the get_file_data() function from /wp-includes/functions.php.
* It's intended as a utility for subclasses that detect updates by parsing files in a VCS.
*
* @param string|null $content File contents.
* @return string[]
*/
public function getFileHeader($content) {
$content = (string) $content;
//WordPress only looks at the first 8 KiB of the file, so we do the same.
$content = substr($content, 0, 8192);
//Normalize line endings.
$content = str_replace("\r", "\n", $content);
$headers = $this->getHeaderNames();
$results = array();
foreach ($headers as $field => $name) {
$success = preg_match('/^[ \t\/*#@]*' . preg_quote($name, '/') . ':(.*)$/mi', $content, $matches);
if ( ($success === 1) && $matches[1] ) {
$value = $matches[1];
if ( function_exists('_cleanup_header_comment') ) {
$value = _cleanup_header_comment($value);
}
$results[$field] = $value;
} else {
$results[$field] = '';
}
}
return $results;
}
/**
* @return array Format: ['HeaderKey' => 'Header Name']
*/
abstract protected function getHeaderNames();
/* -------------------------------------------------------------------
* DebugBar integration
* -------------------------------------------------------------------
*/
/**
* Initialize the update checker Debug Bar plugin/add-on thingy.
*/
public function maybeInitDebugBar() {
if ( class_exists('Debug_Bar', false) && file_exists(dirname(__FILE__ . '/DebugBar')) ) {
$this->createDebugBarExtension();
}
}
protected function createDebugBarExtension() {
return new Puc_v4p4_DebugBar_Extension($this);
}
/**
* Display additional configuration details in the Debug Bar panel.
*
* @param Puc_v4p4_DebugBar_Panel $panel
*/
public function onDisplayConfiguration($panel) {
//Do nothing. Subclasses can use this to add additional info to the panel.
}
}
endif;

View File

@@ -1,199 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_UpgraderStatus', false) ):
/**
* A utility class that helps figure out which plugin or theme WordPress is upgrading.
*
* It may seem strange to have a separate class just for that, but the task is surprisingly complicated.
* Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
* This class uses a few workarounds and heuristics to get the file name.
*/
class Puc_v4p4_UpgraderStatus {
private $currentType = null; //"plugin" or "theme".
private $currentId = null; //Plugin basename or theme directory name.
public function __construct() {
//Keep track of which plugin/theme WordPress is currently upgrading.
add_filter('upgrader_pre_install', array($this, 'setUpgradedThing'), 10, 2);
add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
add_filter('upgrader_post_install', array($this, 'clearUpgradedThing'), 10, 1);
add_action('upgrader_process_complete', array($this, 'clearUpgradedThing'), 10, 1);
}
/**
* Is there and update being installed RIGHT NOW, for a specific plugin?
*
* Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
* and upgrader implementations are liable to change without notice.
*
* @param string $pluginFile The plugin to check.
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool True if the plugin identified by $pluginFile is being upgraded.
*/
public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
return $this->isBeingUpgraded('plugin', $pluginFile, $upgrader);
}
/**
* Is there an update being installed for a specific theme?
*
* @param string $stylesheet Theme directory name.
* @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
* @return bool
*/
public function isThemeBeingUpgraded($stylesheet, $upgrader = null) {
return $this->isBeingUpgraded('theme', $stylesheet, $upgrader);
}
/**
* Check if a specific theme or plugin is being upgraded.
*
* @param string $type
* @param string $id
* @param Plugin_Upgrader|WP_Upgrader|null $upgrader
* @return bool
*/
protected function isBeingUpgraded($type, $id, $upgrader = null) {
if ( isset($upgrader) ) {
list($currentType, $currentId) = $this->getThingBeingUpgradedBy($upgrader);
if ( $currentType !== null ) {
$this->currentType = $currentType;
$this->currentId = $currentId;
}
}
return ($this->currentType === $type) && ($this->currentId === $id);
}
/**
* Figure out which theme or plugin is being upgraded by a WP_Upgrader instance.
*
* Returns an array with two items. The first item is the type of the thing that's being
* upgraded: "plugin" or "theme". The second item is either the plugin basename or
* the theme directory name. If we can't determine what the upgrader is doing, both items
* will be NULL.
*
* Examples:
* ['plugin', 'plugin-dir-name/plugin.php']
* ['theme', 'theme-dir-name']
*
* @param Plugin_Upgrader|WP_Upgrader $upgrader
* @return array
*/
private function getThingBeingUpgradedBy($upgrader) {
if ( !isset($upgrader, $upgrader->skin) ) {
return array(null, null);
}
//Figure out which plugin or theme is being upgraded.
$pluginFile = null;
$themeDirectoryName = null;
$skin = $upgrader->skin;
if ( isset($skin->theme_info) && ($skin->theme_info instanceof WP_Theme) ) {
$themeDirectoryName = $skin->theme_info->get_stylesheet();
} elseif ( $skin instanceof Plugin_Upgrader_Skin ) {
if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
$pluginFile = $skin->plugin;
}
} elseif ( $skin instanceof Theme_Upgrader_Skin ) {
if ( isset($skin->theme) && is_string($skin->theme) && ($skin->theme !== '') ) {
$themeDirectoryName = $skin->theme;
}
} elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
//This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
//filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
//do is compare those headers to the headers of installed plugins.
$pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
}
if ( $pluginFile !== null ) {
return array('plugin', $pluginFile);
} elseif ( $themeDirectoryName !== null ) {
return array('theme', $themeDirectoryName);
}
return array(null, null);
}
/**
* Identify an installed plugin based on its headers.
*
* @param array $searchHeaders The plugin file header to look for.
* @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
*/
private function identifyPluginByHeaders($searchHeaders) {
if ( !function_exists('get_plugins') ){
/** @noinspection PhpIncludeInspection */
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
$installedPlugins = get_plugins();
$matches = array();
foreach($installedPlugins as $pluginBasename => $headers) {
$diff1 = array_diff_assoc($headers, $searchHeaders);
$diff2 = array_diff_assoc($searchHeaders, $headers);
if ( empty($diff1) && empty($diff2) ) {
$matches[] = $pluginBasename;
}
}
//It's possible (though very unlikely) that there could be two plugins with identical
//headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
if ( count($matches) !== 1 ) {
return null;
}
return reset($matches);
}
/**
* @access private
*
* @param mixed $input
* @param array $hookExtra
* @return mixed Returns $input unaltered.
*/
public function setUpgradedThing($input, $hookExtra) {
if ( !empty($hookExtra['plugin']) && is_string($hookExtra['plugin']) ) {
$this->currentId = $hookExtra['plugin'];
$this->currentType = 'plugin';
} elseif ( !empty($hookExtra['theme']) && is_string($hookExtra['theme']) ) {
$this->currentId = $hookExtra['theme'];
$this->currentType = 'theme';
} else {
$this->currentType = null;
$this->currentId = null;
}
return $input;
}
/**
* @access private
*
* @param array $options
* @return array
*/
public function setUpgradedPluginFromOptions($options) {
if ( isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin']) ) {
$this->currentType = 'plugin';
$this->currentId = $options['hook_extra']['plugin'];
} else {
$this->currentType = null;
$this->currentId = null;
}
return $options;
}
/**
* @access private
*
* @param mixed $input
* @return mixed Returns $input unaltered.
*/
public function clearUpgradedThing($input = null) {
$this->currentId = null;
$this->currentType = null;
return $input;
}
}
endif;

View File

@@ -1,69 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Utils', false) ):
class Puc_v4p4_Utils {
/**
* Get a value from a nested array or object based on a path.
*
* @param array|object|null $collection Get an entry from this array.
* @param array|string $path A list of array keys in hierarchy order, or a string path like "foo.bar.baz".
* @param mixed $default The value to return if the specified path is not found.
* @param string $separator Path element separator. Only applies to string paths.
* @return mixed
*/
public static function get($collection, $path, $default = null, $separator = '.') {
if ( is_string($path) ) {
$path = explode($separator, $path);
}
//Follow the $path into $input as far as possible.
$currentValue = $collection;
foreach ($path as $node) {
if ( is_array($currentValue) && isset($currentValue[$node]) ) {
$currentValue = $currentValue[$node];
} else if ( is_object($currentValue) && isset($currentValue->$node) ) {
$currentValue = $currentValue->$node;
} else {
return $default;
}
}
return $currentValue;
}
/**
* Get the first array element that is not empty.
*
* @param array $values
* @param mixed|null $default Returns this value if there are no non-empty elements.
* @return mixed|null
*/
public static function findNotEmpty($values, $default = null) {
if ( empty($values) ) {
return $default;
}
foreach ($values as $value) {
if ( !empty($value) ) {
return $value;
}
}
return $default;
}
/**
* Check if the input string starts with the specified prefix.
*
* @param string $input
* @param string $prefix
* @return bool
*/
public static function startsWith($input, $prefix) {
$length = strlen($prefix);
return (substr($input, 0, $length) === $prefix);
}
}
endif;

View File

@@ -1,302 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Vcs_Api') ):
abstract class Puc_v4p4_Vcs_Api {
protected $tagNameProperty = 'name';
protected $slug = '';
/**
* @var string
*/
protected $repositoryUrl = '';
/**
* @var mixed Authentication details for private repositories. Format depends on service.
*/
protected $credentials = null;
/**
* @var string The filter tag that's used to filter options passed to wp_remote_get.
* For example, "puc_request_info_options-slug" or "puc_request_update_options_theme-slug".
*/
protected $httpFilterName = '';
/**
* @var string|null
*/
protected $localDirectory = null;
/**
* Puc_v4p4_Vcs_Api constructor.
*
* @param string $repositoryUrl
* @param array|string|null $credentials
*/
public function __construct($repositoryUrl, $credentials = null) {
$this->repositoryUrl = $repositoryUrl;
$this->setAuthentication($credentials);
}
/**
* @return string
*/
public function getRepositoryUrl() {
return $this->repositoryUrl;
}
/**
* Figure out which reference (i.e tag or branch) contains the latest version.
*
* @param string $configBranch Start looking in this branch.
* @return null|Puc_v4p4_Vcs_Reference
*/
abstract public function chooseReference($configBranch);
/**
* Get the readme.txt file from the remote repository and parse it
* according to the plugin readme standard.
*
* @param string $ref Tag or branch name.
* @return array Parsed readme.
*/
public function getRemoteReadme($ref = 'master') {
$fileContents = $this->getRemoteFile($this->getLocalReadmeName(), $ref);
if ( empty($fileContents) ) {
return array();
}
$parser = new PucReadmeParser();
return $parser->parse_readme_contents($fileContents);
}
/**
* Get the case-sensitive name of the local readme.txt file.
*
* In most cases it should just be called "readme.txt", but some plugins call it "README.txt",
* "README.TXT", or even "Readme.txt". Most VCS are case-sensitive so we need to know the correct
* capitalization.
*
* Defaults to "readme.txt" (all lowercase).
*
* @return string
*/
public function getLocalReadmeName() {
static $fileName = null;
if ( $fileName !== null ) {
return $fileName;
}
$fileName = 'readme.txt';
if ( isset($this->localDirectory) ) {
$files = scandir($this->localDirectory);
if ( !empty($files) ) {
foreach ($files as $possibleFileName) {
if ( strcasecmp($possibleFileName, 'readme.txt') === 0 ) {
$fileName = $possibleFileName;
break;
}
}
}
}
return $fileName;
}
/**
* Get a branch.
*
* @param string $branchName
* @return Puc_v4p4_Vcs_Reference|null
*/
abstract public function getBranch($branchName);
/**
* Get a specific tag.
*
* @param string $tagName
* @return Puc_v4p4_Vcs_Reference|null
*/
abstract public function getTag($tagName);
/**
* Get the tag that looks like the highest version number.
* (Implementations should skip pre-release versions if possible.)
*
* @return Puc_v4p4_Vcs_Reference|null
*/
abstract public function getLatestTag();
/**
* Check if a tag name string looks like a version number.
*
* @param string $name
* @return bool
*/
protected function looksLikeVersion($name) {
//Tag names may be prefixed with "v", e.g. "v1.2.3".
$name = ltrim($name, 'v');
//The version string must start with a number.
if ( !is_numeric(substr($name, 0, 1)) ) {
return false;
}
//The goal is to accept any SemVer-compatible or "PHP-standardized" version number.
return (preg_match('@^(\d{1,5}?)(\.\d{1,10}?){0,4}?($|[abrdp+_\-]|\s)@i', $name) === 1);
}
/**
* Check if a tag appears to be named like a version number.
*
* @param stdClass $tag
* @return bool
*/
protected function isVersionTag($tag) {
$property = $this->tagNameProperty;
return isset($tag->$property) && $this->looksLikeVersion($tag->$property);
}
/**
* Sort a list of tags as if they were version numbers.
* Tags that don't look like version number will be removed.
*
* @param stdClass[] $tags Array of tag objects.
* @return stdClass[] Filtered array of tags sorted in descending order.
*/
protected function sortTagsByVersion($tags) {
//Keep only those tags that look like version numbers.
$versionTags = array_filter($tags, array($this, 'isVersionTag'));
//Sort them in descending order.
usort($versionTags, array($this, 'compareTagNames'));
return $versionTags;
}
/**
* Compare two tags as if they were version number.
*
* @param stdClass $tag1 Tag object.
* @param stdClass $tag2 Another tag object.
* @return int
*/
protected function compareTagNames($tag1, $tag2) {
$property = $this->tagNameProperty;
if ( !isset($tag1->$property) ) {
return 1;
}
if ( !isset($tag2->$property) ) {
return -1;
}
return -version_compare(ltrim($tag1->$property, 'v'), ltrim($tag2->$property, 'v'));
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
abstract public function getRemoteFile($path, $ref = 'master');
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
abstract public function getLatestCommitTime($ref);
/**
* Get the contents of the changelog file from the repository.
*
* @param string $ref
* @param string $localDirectory Full path to the local plugin or theme directory.
* @return null|string The HTML contents of the changelog.
*/
public function getRemoteChangelog($ref, $localDirectory) {
$filename = $this->findChangelogName($localDirectory);
if ( empty($filename) ) {
return null;
}
$changelog = $this->getRemoteFile($filename, $ref);
if ( $changelog === null ) {
return null;
}
/** @noinspection PhpUndefinedClassInspection */
return Parsedown::instance()->text($changelog);
}
/**
* Guess the name of the changelog file.
*
* @param string $directory
* @return string|null
*/
protected function findChangelogName($directory = null) {
if ( !isset($directory) ) {
$directory = $this->localDirectory;
}
if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
return null;
}
$possibleNames = array('CHANGES.md', 'CHANGELOG.md', 'changes.md', 'changelog.md');
$files = scandir($directory);
$foundNames = array_intersect($possibleNames, $files);
if ( !empty($foundNames) ) {
return reset($foundNames);
}
return null;
}
/**
* Set authentication credentials.
*
* @param $credentials
*/
public function setAuthentication($credentials) {
$this->credentials = $credentials;
}
public function isAuthenticationEnabled() {
return !empty($this->credentials);
}
/**
* @param string $url
* @return string
*/
public function signDownloadUrl($url) {
return $url;
}
/**
* @param string $filterName
*/
public function setHttpFilterName($filterName) {
$this->httpFilterName = $filterName;
}
/**
* @param string $directory
*/
public function setLocalDirectory($directory) {
if ( empty($directory) || !is_dir($directory) || ($directory === '.') ) {
$this->localDirectory = null;
} else {
$this->localDirectory = $directory;
}
}
/**
* @param string $slug
*/
public function setSlug($slug) {
$this->slug = $slug;
}
}
endif;

View File

@@ -1,27 +0,0 @@
<?php
if ( !interface_exists('Puc_v4p4_Vcs_BaseChecker', false) ):
interface Puc_v4p4_Vcs_BaseChecker {
/**
* Set the repository branch to use for updates. Defaults to 'master'.
*
* @param string $branch
* @return $this
*/
public function setBranch($branch);
/**
* Set authentication credentials.
*
* @param array|string $credentials
* @return $this
*/
public function setAuthentication($credentials);
/**
* @return Puc_v4p4_Vcs_Api
*/
public function getVcsApi();
}
endif;

View File

@@ -1,256 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Vcs_BitBucketApi', false) ):
class Puc_v4p4_Vcs_BitBucketApi extends Puc_v4p4_Vcs_Api {
/**
* @var Puc_v4p4_OAuthSignature
*/
private $oauth = null;
/**
* @var string
*/
private $username;
/**
* @var string
*/
private $repository;
public function __construct($repositoryUrl, $credentials = array()) {
$path = @parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->username = $matches['username'];
$this->repository = $matches['repository'];
} else {
throw new InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"');
}
parent::__construct($repositoryUrl, $credentials);
}
/**
* Figure out which reference (i.e tag or branch) contains the latest version.
*
* @param string $configBranch Start looking in this branch.
* @return null|Puc_v4p4_Vcs_Reference
*/
public function chooseReference($configBranch) {
$updateSource = null;
//Check if there's a "Stable tag: 1.2.3" header that points to a valid tag.
$updateSource = $this->getStableTag($configBranch);
//Look for version-like tags.
if ( !$updateSource && ($configBranch === 'master') ) {
$updateSource = $this->getLatestTag();
}
//If all else fails, use the specified branch itself.
if ( !$updateSource ) {
$updateSource = $this->getBranch($configBranch);
}
return $updateSource;
}
public function getBranch($branchName) {
$branch = $this->api('/refs/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
return new Puc_v4p4_Vcs_Reference(array(
'name' => $branch->name,
'updated' => $branch->target->date,
'downloadUrl' => $this->getDownloadUrl($branch->name),
));
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return Puc_v4p4_Vcs_Reference|null
*/
public function getTag($tagName) {
$tag = $this->api('/refs/tags/' . $tagName);
if ( is_wp_error($tag) || empty($tag) ) {
return null;
}
return new Puc_v4p4_Vcs_Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date,
'downloadUrl' => $this->getDownloadUrl($tag->name),
));
}
/**
* Get the tag that looks like the highest version number.
*
* @return Puc_v4p4_Vcs_Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/refs/tags?sort=-target.date');
if ( !isset($tags, $tags->values) || !is_array($tags->values) ) {
return null;
}
//Filter and sort the list of tags.
$versionTags = $this->sortTagsByVersion($tags->values);
//Return the first result.
if ( !empty($versionTags) ) {
$tag = $versionTags[0];
return new Puc_v4p4_Vcs_Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'updated' => $tag->target->date,
'downloadUrl' => $this->getDownloadUrl($tag->name),
));
}
return null;
}
/**
* Get the tag/ref specified by the "Stable tag" header in the readme.txt of a given branch.
*
* @param string $branch
* @return null|Puc_v4p4_Vcs_Reference
*/
protected function getStableTag($branch) {
$remoteReadme = $this->getRemoteReadme($branch);
if ( !empty($remoteReadme['stable_tag']) ) {
$tag = $remoteReadme['stable_tag'];
//You can explicitly opt out of using tags by setting "Stable tag" to
//"trunk" or the name of the current branch.
if ( ($tag === $branch) || ($tag === 'trunk') ) {
return $this->getBranch($branch);
}
return $this->getTag($tag);
}
return null;
}
/**
* @param string $ref
* @return string
*/
protected function getDownloadUrl($ref) {
return sprintf(
'https://bitbucket.org/%s/%s/get/%s.zip',
$this->username,
$this->repository,
$ref
);
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$response = $this->api('src/' . $ref . '/' . ltrim($path), '1.0');
if ( is_wp_error($response) || !isset($response, $response->data) ) {
return null;
}
return $response->data;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$response = $this->api('commits/' . $ref);
if ( isset($response->values, $response->values[0], $response->values[0]->date) ) {
return $response->values[0]->date;
}
return null;
}
/**
* Perform a BitBucket API 2.0 request.
*
* @param string $url
* @param string $version
* @return mixed|WP_Error
*/
public function api($url, $version = '2.0') {
$url = implode('/', array(
'https://api.bitbucket.org',
$version,
'repositories',
$this->username,
$this->repository,
ltrim($url, '/')
));
$baseUrl = $url;
if ( $this->oauth ) {
$url = $this->oauth->sign($url,'GET');
}
$options = array('timeout' => 10);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
$document = json_decode($body);
return $document;
}
$error = new WP_Error(
'puc-bitbucket-http-error',
sprintf('BitBucket API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
* @param array $credentials
*/
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
$this->oauth = new Puc_v4p4_OAuthSignature(
$credentials['consumer_key'],
$credentials['consumer_secret']
);
} else {
$this->oauth = null;
}
}
public function signDownloadUrl($url) {
//Add authentication data to download URLs. Since OAuth signatures incorporate
//timestamps, we have to do this immediately before inserting the update. Otherwise
//authentication could fail due to a stale timestamp.
if ( $this->oauth ) {
$url = $this->oauth->sign($url);
}
return $url;
}
}
endif;

View File

@@ -1,413 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Vcs_GitHubApi', false) ):
class Puc_v4p4_Vcs_GitHubApi extends Puc_v4p4_Vcs_Api {
/**
* @var string GitHub username.
*/
protected $userName;
/**
* @var string GitHub repository name.
*/
protected $repositoryName;
/**
* @var string Either a fully qualified repository URL, or just "user/repo-name".
*/
protected $repositoryUrl;
/**
* @var string GitHub authentication token. Optional.
*/
protected $accessToken;
/**
* @var bool Whether to download release assets instead of the auto-generated source code archives.
*/
protected $releaseAssetsEnabled = false;
/**
* @var string|null Regular expression that's used to filter release assets by name. Optional.
*/
protected $assetFilterRegex = null;
/**
* @var string|null The unchanging part of a release asset URL. Used to identify download attempts.
*/
protected $assetApiBaseUrl = null;
public function __construct($repositoryUrl, $accessToken = null) {
$path = @parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username'];
$this->repositoryName = $matches['repository'];
} else {
throw new InvalidArgumentException('Invalid GitHub repository URL: "' . $repositoryUrl . '"');
}
parent::__construct($repositoryUrl, $accessToken);
}
/**
* Get the latest release from GitHub.
*
* @return Puc_v4p4_Vcs_Reference|null
*/
public function getLatestRelease() {
$release = $this->api('/repos/:user/:repo/releases/latest');
if ( is_wp_error($release) || !is_object($release) || !isset($release->tag_name) ) {
return null;
}
$reference = new Puc_v4p4_Vcs_Reference(array(
'name' => $release->tag_name,
'version' => ltrim($release->tag_name, 'v'), //Remove the "v" prefix from "v1.2.3".
'downloadUrl' => $this->signDownloadUrl($release->zipball_url),
'updated' => $release->created_at,
'apiResponse' => $release,
));
if ( isset($release->assets[0]) ) {
$reference->downloadCount = $release->assets[0]->download_count;
}
if ( $this->releaseAssetsEnabled && isset($release->assets, $release->assets[0]) ) {
//Use the first release asset that matches the specified regular expression.
$matchingAssets = array_filter($release->assets, array($this, 'matchesAssetFilter'));
if ( !empty($matchingAssets) ) {
if ( $this->isAuthenticationEnabled() ) {
/**
* Keep in mind that we'll need to add an "Accept" header to download this asset.
* @see setReleaseDownloadHeader()
*/
$reference->downloadUrl = $this->signDownloadUrl($matchingAssets[0]->url);
} else {
//It seems that browser_download_url only works for public repositories.
//Using an access_token doesn't help. Maybe OAuth would work?
$reference->downloadUrl = $matchingAssets[0]->browser_download_url;
}
$reference->downloadCount = $matchingAssets[0]->download_count;
}
}
if ( !empty($release->body) ) {
/** @noinspection PhpUndefinedClassInspection */
$reference->changelog = Parsedown::instance()->text($release->body);
}
return $reference;
}
/**
* Get the tag that looks like the highest version number.
*
* @return Puc_v4p4_Vcs_Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/repos/:user/:repo/tags');
if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
return null;
}
$versionTags = $this->sortTagsByVersion($tags);
if ( empty($versionTags) ) {
return null;
}
$tag = $versionTags[0];
return new Puc_v4p4_Vcs_Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $this->signDownloadUrl($tag->zipball_url),
'apiResponse' => $tag,
));
}
/**
* Get a branch by name.
*
* @param string $branchName
* @return null|Puc_v4p4_Vcs_Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/repos/:user/:repo/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
$reference = new Puc_v4p4_Vcs_Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
));
if ( isset($branch->commit, $branch->commit->commit, $branch->commit->commit->author->date) ) {
$reference->updated = $branch->commit->commit->author->date;
}
return $reference;
}
/**
* Get the latest commit that changed the specified file.
*
* @param string $filename
* @param string $ref Reference name (e.g. branch or tag).
* @return StdClass|null
*/
public function getLatestCommit($filename, $ref = 'master') {
$commits = $this->api(
'/repos/:user/:repo/commits',
array(
'path' => $filename,
'sha' => $ref,
)
);
if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) {
return $commits[0];
}
return null;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$commits = $this->api('/repos/:user/:repo/commits', array('sha' => $ref));
if ( !is_wp_error($commits) && is_array($commits) && isset($commits[0]) ) {
return $commits[0]->commit->author->date;
}
return null;
}
/**
* Perform a GitHub API request.
*
* @param string $url
* @param array $queryParams
* @return mixed|WP_Error
*/
protected function api($url, $queryParams = array()) {
$baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams);
$options = array('timeout' => 10);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
$document = json_decode($body);
return $document;
}
$error = new WP_Error(
'puc-github-http-error',
sprintf('GitHub API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
* Build a fully qualified URL for an API request.
*
* @param string $url
* @param array $queryParams
* @return string
*/
protected function buildApiUrl($url, $queryParams) {
$variables = array(
'user' => $this->userName,
'repo' => $this->repositoryName,
);
foreach ($variables as $name => $value) {
$url = str_replace('/:' . $name, '/' . urlencode($value), $url);
}
$url = 'https://api.github.com' . $url;
if ( !empty($this->accessToken) ) {
$queryParams['access_token'] = $this->accessToken;
}
if ( !empty($queryParams) ) {
$url = add_query_arg($queryParams, $url);
}
return $url;
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$apiUrl = '/repos/:user/:repo/contents/' . $path;
$response = $this->api($apiUrl, array('ref' => $ref));
if ( is_wp_error($response) || !isset($response->content) || ($response->encoding !== 'base64') ) {
return null;
}
return base64_decode($response->content);
}
/**
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
*
* @param string $ref
* @return string
*/
public function buildArchiveDownloadUrl($ref = 'master') {
$url = sprintf(
'https://api.github.com/repos/%1$s/%2$s/zipball/%3$s',
urlencode($this->userName),
urlencode($this->repositoryName),
urlencode($ref)
);
if ( !empty($this->accessToken) ) {
$url = $this->signDownloadUrl($url);
}
return $url;
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return Puc_v4p4_Vcs_Reference|null
*/
public function getTag($tagName) {
//The current GitHub update checker doesn't use getTag, so I didn't bother to implement it.
throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
}
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
$this->accessToken = is_string($credentials) ? $credentials : null;
}
/**
* Figure out which reference (i.e tag or branch) contains the latest version.
*
* @param string $configBranch Start looking in this branch.
* @return null|Puc_v4p4_Vcs_Reference
*/
public function chooseReference($configBranch) {
$updateSource = null;
if ( $configBranch === 'master' ) {
//Use the latest release.
$updateSource = $this->getLatestRelease();
if ( $updateSource === null ) {
//Failing that, use the tag with the highest version number.
$updateSource = $this->getLatestTag();
}
}
//Alternatively, just use the branch itself.
if ( empty($updateSource) ) {
$updateSource = $this->getBranch($configBranch);
}
return $updateSource;
}
/**
* @param string $url
* @return string
*/
public function signDownloadUrl($url) {
if ( empty($this->credentials) ) {
return $url;
}
return add_query_arg('access_token', $this->credentials, $url);
}
/**
* Enable updating via release assets.
*
* If the latest release contains no usable assets, the update checker
* will fall back to using the automatically generated ZIP archive.
*
* Private repositories will only work with WordPress 3.7 or later.
*
* @param string|null $fileNameRegex Optional. Use only those assets where the file name matches this regex.
*/
public function enableReleaseAssets($fileNameRegex = null) {
$this->releaseAssetsEnabled = true;
$this->assetFilterRegex = $fileNameRegex;
$this->assetApiBaseUrl = sprintf(
'//api.github.com/repos/%1$s/%2$s/releases/assets/',
$this->userName,
$this->repositoryName
);
//Optimization: Instead of filtering all HTTP requests, let's do it only when
//WordPress is about to download an update.
add_filter('upgrader_pre_download', array($this, 'addHttpRequestFilter'), 10, 1); //WP 3.7+
}
/**
* Does this asset match the file name regex?
*
* @param stdClass $releaseAsset
* @return bool
*/
protected function matchesAssetFilter($releaseAsset) {
if ( $this->assetFilterRegex === null ) {
//The default is to accept all assets.
return true;
}
return isset($releaseAsset->name) && preg_match($this->assetFilterRegex, $releaseAsset->name);
}
/**
* @internal
* @param bool $result
* @return bool
*/
public function addHttpRequestFilter($result) {
static $filterAdded = false;
if ( $this->releaseAssetsEnabled && !$filterAdded && $this->isAuthenticationEnabled() ) {
add_filter('http_request_args', array($this, 'setReleaseDownloadHeader'), 10, 2);
$filterAdded = true;
}
return $result;
}
/**
* Set the HTTP header that's necessary to download private release assets.
*
* See GitHub docs:
* @link https://developer.github.com/v3/repos/releases/#get-a-single-release-asset
*
* @internal
* @param array $requestArgs
* @param string $url
* @return array
*/
public function setReleaseDownloadHeader($requestArgs, $url = '') {
//Is WordPress trying to download one of our assets?
if ( strpos($url, $this->assetApiBaseUrl) !== false ) {
$requestArgs['headers']['accept'] = 'application/octet-stream';
}
return $requestArgs;
}
}
endif;

View File

@@ -1,277 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Vcs_GitLabApi', false) ):
class Puc_v4p4_Vcs_GitLabApi extends Puc_v4p4_Vcs_Api {
/**
* @var string GitLab username.
*/
protected $userName;
/**
* @var string GitLab server host.
*/
private $repositoryHost;
/**
* @var string GitLab repository name.
*/
protected $repositoryName;
/**
* @var string GitLab authentication token. Optional.
*/
protected $accessToken;
public function __construct($repositoryUrl, $accessToken = null) {
//Parse the repository host to support custom hosts.
$port = @parse_url($repositoryUrl, PHP_URL_PORT);
if ( !empty($port) ){
$port = ':' . $port;
}
$this->repositoryHost = @parse_url($repositoryUrl, PHP_URL_HOST) . $port;
//Find the repository information
$path = @parse_url($repositoryUrl, PHP_URL_PATH);
if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
$this->userName = $matches['username'];
$this->repositoryName = $matches['repository'];
} else {
//This is not a traditional url, it could be gitlab is in a deeper subdirectory.
//Get the path segments.
$segments = explode('/', untrailingslashit(ltrim($path, '/')));
//We need at least /user-name/repository-name/
if ( count($segments) < 2 ) {
throw new InvalidArgumentException('Invalid GitLab repository URL: "' . $repositoryUrl . '"');
}
//Get the username and repository name.
$usernameRepo = array_splice($segments, -2, 2);
$this->userName = $usernameRepo[0];
$this->repositoryName = $usernameRepo[1];
//Append the remaining segments to the host.
$this->repositoryHost = trailingslashit($this->repositoryHost) . implode('/', $segments);
}
parent::__construct($repositoryUrl, $accessToken);
}
/**
* Get the latest release from GitLab.
*
* @return Puc_v4p4_Vcs_Reference|null
*/
public function getLatestRelease() {
return $this->getLatestTag();
}
/**
* Get the tag that looks like the highest version number.
*
* @return Puc_v4p4_Vcs_Reference|null
*/
public function getLatestTag() {
$tags = $this->api('/:id/repository/tags');
if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
return null;
}
$versionTags = $this->sortTagsByVersion($tags);
if ( empty($versionTags) ) {
return null;
}
$tag = $versionTags[0];
return new Puc_v4p4_Vcs_Reference(array(
'name' => $tag->name,
'version' => ltrim($tag->name, 'v'),
'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name),
'apiResponse' => $tag
));
}
/**
* Get a branch by name.
*
* @param string $branchName
* @return null|Puc_v4p4_Vcs_Reference
*/
public function getBranch($branchName) {
$branch = $this->api('/:id/repository/branches/' . $branchName);
if ( is_wp_error($branch) || empty($branch) ) {
return null;
}
$reference = new Puc_v4p4_Vcs_Reference(array(
'name' => $branch->name,
'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
'apiResponse' => $branch,
));
if ( isset($branch->commit, $branch->commit->committed_date) ) {
$reference->updated = $branch->commit->committed_date;
}
return $reference;
}
/**
* Get the timestamp of the latest commit that changed the specified branch or tag.
*
* @param string $ref Reference name (e.g. branch or tag).
* @return string|null
*/
public function getLatestCommitTime($ref) {
$commits = $this->api('/:id/repository/commits/', array('ref_name' => $ref));
if ( is_wp_error($commits) || !is_array($commits) || !isset($commits[0]) ) {
return null;
}
return $commits[0]->committed_date;
}
/**
* Perform a GitLab API request.
*
* @param string $url
* @param array $queryParams
* @return mixed|WP_Error
*/
protected function api($url, $queryParams = array()) {
$baseUrl = $url;
$url = $this->buildApiUrl($url, $queryParams);
$options = array('timeout' => 10);
if ( !empty($this->httpFilterName) ) {
$options = apply_filters($this->httpFilterName, $options);
}
$response = wp_remote_get($url, $options);
if ( is_wp_error($response) ) {
do_action('puc_api_error', $response, null, $url, $this->slug);
return $response;
}
$code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
if ( $code === 200 ) {
return json_decode($body);
}
$error = new WP_Error(
'puc-gitlab-http-error',
sprintf('GitLab API error. URL: "%s", HTTP status code: %d.', $baseUrl, $code)
);
do_action('puc_api_error', $error, $response, $url, $this->slug);
return $error;
}
/**
* Build a fully qualified URL for an API request.
*
* @param string $url
* @param array $queryParams
* @return string
*/
protected function buildApiUrl($url, $queryParams) {
$variables = array(
'id' => $this->userName . '/' . $this->repositoryName,
);
foreach ($variables as $name => $value) {
$url = str_replace("/:{$name}", urlencode('/' . $value), $url);
}
$url = substr($url, 3);
$url = sprintf('https://%1$s/api/v4/projects/%2$s', $this->repositoryHost, $url);
if ( !empty($this->accessToken) ) {
$queryParams['private_token'] = $this->accessToken;
}
if ( !empty($queryParams) ) {
$url = add_query_arg($queryParams, $url);
}
return $url;
}
/**
* Get the contents of a file from a specific branch or tag.
*
* @param string $path File name.
* @param string $ref
* @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
*/
public function getRemoteFile($path, $ref = 'master') {
$response = $this->api('/:id/repository/files/' . $path, array('ref' => $ref));
if ( is_wp_error($response) || !isset($response->content) || $response->encoding !== 'base64' ) {
return null;
}
return base64_decode($response->content);
}
/**
* Generate a URL to download a ZIP archive of the specified branch/tag/etc.
*
* @param string $ref
* @return string
*/
public function buildArchiveDownloadUrl($ref = 'master') {
$url = sprintf(
'https://%1$s/api/v4/projects/%2$s/repository/archive.zip',
$this->repositoryHost,
urlencode($this->userName . '/' . $this->repositoryName)
);
$url = add_query_arg('sha', urlencode($ref), $url);
if ( !empty($this->accessToken) ) {
$url = add_query_arg('private_token', $this->accessToken, $url);
}
return $url;
}
/**
* Get a specific tag.
*
* @param string $tagName
* @return Puc_v4p4_Vcs_Reference|null
*/
public function getTag($tagName) {
throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
}
/**
* Figure out which reference (i.e tag or branch) contains the latest version.
*
* @param string $configBranch Start looking in this branch.
* @return null|Puc_v4p4_Vcs_Reference
*/
public function chooseReference($configBranch) {
$updateSource = null;
// GitLab doesn't handle releases the same as GitHub so just use the latest tag
if ( $configBranch === 'master' ) {
$updateSource = $this->getLatestTag();
}
if ( empty($updateSource) ) {
$updateSource = $this->getBranch($configBranch);
}
return $updateSource;
}
public function setAuthentication($credentials) {
parent::setAuthentication($credentials);
$this->accessToken = is_string($credentials) ? $credentials : null;
}
}
endif;

View File

@@ -1,217 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Vcs_PluginUpdateChecker') ):
class Puc_v4p4_Vcs_PluginUpdateChecker extends Puc_v4p4_Plugin_UpdateChecker implements Puc_v4p4_Vcs_BaseChecker {
/**
* @var string The branch where to look for updates. Defaults to "master".
*/
protected $branch = 'master';
/**
* @var Puc_v4p4_Vcs_Api Repository API client.
*/
protected $api = null;
/**
* Puc_v4p4_Vcs_PluginUpdateChecker constructor.
*
* @param Puc_v4p4_Vcs_Api $api
* @param string $pluginFile
* @param string $slug
* @param int $checkPeriod
* @param string $optionName
* @param string $muPluginFile
*/
public function __construct($api, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
$this->api = $api;
$this->api->setHttpFilterName($this->getUniqueName('request_info_options'));
parent::__construct($api->getRepositoryUrl(), $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
$this->api->setSlug($this->slug);
}
public function requestInfo($unusedParameter = null) {
//We have to make several remote API requests to gather all the necessary info
//which can take a while on slow networks.
if ( function_exists('set_time_limit') ) {
@set_time_limit(60);
}
$api = $this->api;
$api->setLocalDirectory($this->getAbsoluteDirectoryPath());
$info = new Puc_v4p4_Plugin_Info();
$info->filename = $this->pluginFile;
$info->slug = $this->slug;
$this->setInfoFromHeader($this->getPluginHeader(), $info);
//Pick a branch or tag.
$updateSource = $api->chooseReference($this->branch);
if ( $updateSource ) {
$ref = $updateSource->name;
$info->version = $updateSource->version;
$info->last_updated = $updateSource->updated;
$info->download_url = $updateSource->downloadUrl;
if ( !empty($updateSource->changelog) ) {
$info->sections['changelog'] = $updateSource->changelog;
}
if ( isset($updateSource->downloadCount) ) {
$info->downloaded = $updateSource->downloadCount;
}
} else {
//There's probably a network problem or an authentication error.
do_action(
'puc_api_error',
new WP_Error(
'puc-no-update-source',
'Could not retrieve version information from the repository. '
. 'This usually means that the update checker either can\'t connect '
. 'to the repository or it\'s configured incorrectly.'
),
null, null, $this->slug
);
return null;
}
//Get headers from the main plugin file in this branch/tag. Its "Version" header and other metadata
//are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
$mainPluginFile = basename($this->pluginFile);
$remotePlugin = $api->getRemoteFile($mainPluginFile, $ref);
if ( !empty($remotePlugin) ) {
$remoteHeader = $this->getFileHeader($remotePlugin);
$this->setInfoFromHeader($remoteHeader, $info);
}
//Try parsing readme.txt. If it's formatted according to WordPress.org standards, it will contain
//a lot of useful information like the required/tested WP version, changelog, and so on.
if ( $this->readmeTxtExistsLocally() ) {
$this->setInfoFromRemoteReadme($ref, $info);
}
//The changelog might be in a separate file.
if ( empty($info->sections['changelog']) ) {
$info->sections['changelog'] = $api->getRemoteChangelog($ref, dirname($this->getAbsolutePath()));
if ( empty($info->sections['changelog']) ) {
$info->sections['changelog'] = __('There is no changelog available.', 'plugin-update-checker');
}
}
if ( empty($info->last_updated) ) {
//Fetch the latest commit that changed the tag or branch and use it as the "last_updated" date.
$latestCommitTime = $api->getLatestCommitTime($ref);
if ( $latestCommitTime !== null ) {
$info->last_updated = $latestCommitTime;
}
}
$info = apply_filters($this->getUniqueName('request_info_result'), $info, null);
return $info;
}
/**
* Check if the currently installed version has a readme.txt file.
*
* @return bool
*/
protected function readmeTxtExistsLocally() {
$pluginDirectory = $this->getAbsoluteDirectoryPath();
if ( empty($pluginDirectory) || !is_dir($pluginDirectory) || ($pluginDirectory === '.') ) {
return false;
}
return is_file($pluginDirectory . '/' . $this->api->getLocalReadmeName());
}
/**
* Copy plugin metadata from a file header to a Plugin Info object.
*
* @param array $fileHeader
* @param Puc_v4p4_Plugin_Info $pluginInfo
*/
protected function setInfoFromHeader($fileHeader, $pluginInfo) {
$headerToPropertyMap = array(
'Version' => 'version',
'Name' => 'name',
'PluginURI' => 'homepage',
'Author' => 'author',
'AuthorName' => 'author',
'AuthorURI' => 'author_homepage',
'Requires WP' => 'requires',
'Tested WP' => 'tested',
'Requires at least' => 'requires',
'Tested up to' => 'tested',
);
foreach ($headerToPropertyMap as $headerName => $property) {
if ( isset($fileHeader[$headerName]) && !empty($fileHeader[$headerName]) ) {
$pluginInfo->$property = $fileHeader[$headerName];
}
}
if ( !empty($fileHeader['Description']) ) {
$pluginInfo->sections['description'] = $fileHeader['Description'];
}
}
/**
* Copy plugin metadata from the remote readme.txt file.
*
* @param string $ref GitHub tag or branch where to look for the readme.
* @param Puc_v4p4_Plugin_Info $pluginInfo
*/
protected function setInfoFromRemoteReadme($ref, $pluginInfo) {
$readme = $this->api->getRemoteReadme($ref);
if ( empty($readme) ) {
return;
}
if ( isset($readme['sections']) ) {
$pluginInfo->sections = array_merge($pluginInfo->sections, $readme['sections']);
}
if ( !empty($readme['tested_up_to']) ) {
$pluginInfo->tested = $readme['tested_up_to'];
}
if ( !empty($readme['requires_at_least']) ) {
$pluginInfo->requires = $readme['requires_at_least'];
}
if ( isset($readme['upgrade_notice'], $readme['upgrade_notice'][$pluginInfo->version]) ) {
$pluginInfo->upgrade_notice = $readme['upgrade_notice'][$pluginInfo->version];
}
}
public function setBranch($branch) {
$this->branch = $branch;
return $this;
}
public function setAuthentication($credentials) {
$this->api->setAuthentication($credentials);
return $this;
}
public function getVcsApi() {
return $this->api;
}
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) && !empty($update->download_url) ) {
$update->download_url = $this->api->signDownloadUrl($update->download_url);
}
return $update;
}
public function onDisplayConfiguration($panel) {
parent::onDisplayConfiguration($panel);
$panel->row('Branch', $this->branch);
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
$panel->row('API client', get_class($this->api));
}
}
endif;

View File

@@ -1,49 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Vcs_Reference', false) ):
/**
* This class represents a VCS branch or tag. It's intended as a read only, short-lived container
* that only exists to provide a limited degree of type checking.
*
* @property string $name
* @property string|null version
* @property string $downloadUrl
* @property string $updated
*
* @property string|null $changelog
* @property int|null $downloadCount
*/
class Puc_v4p4_Vcs_Reference {
private $properties = array();
public function __construct($properties = array()) {
$this->properties = $properties;
}
/**
* @param string $name
* @return mixed|null
*/
public function __get($name) {
return array_key_exists($name, $this->properties) ? $this->properties[$name] : null;
}
/**
* @param string $name
* @param mixed $value
*/
public function __set($name, $value) {
$this->properties[$name] = $value;
}
/**
* @param string $name
* @return bool
*/
public function __isset($name) {
return isset($this->properties[$name]);
}
}
endif;

View File

@@ -1,118 +0,0 @@
<?php
if ( !class_exists('Puc_v4p4_Vcs_ThemeUpdateChecker', false) ):
class Puc_v4p4_Vcs_ThemeUpdateChecker extends Puc_v4p4_Theme_UpdateChecker implements Puc_v4p4_Vcs_BaseChecker {
/**
* @var string The branch where to look for updates. Defaults to "master".
*/
protected $branch = 'master';
/**
* @var Puc_v4p4_Vcs_Api Repository API client.
*/
protected $api = null;
/**
* Puc_v4p4_Vcs_ThemeUpdateChecker constructor.
*
* @param Puc_v4p4_Vcs_Api $api
* @param null $stylesheet
* @param null $customSlug
* @param int $checkPeriod
* @param string $optionName
*/
public function __construct($api, $stylesheet = null, $customSlug = null, $checkPeriod = 12, $optionName = '') {
$this->api = $api;
$this->api->setHttpFilterName($this->getUniqueName('request_update_options'));
parent::__construct($api->getRepositoryUrl(), $stylesheet, $customSlug, $checkPeriod, $optionName);
$this->api->setSlug($this->slug);
}
public function requestUpdate() {
$api = $this->api;
$api->setLocalDirectory($this->getAbsoluteDirectoryPath());
$update = new Puc_v4p4_Theme_Update();
$update->slug = $this->slug;
//Figure out which reference (tag or branch) we'll use to get the latest version of the theme.
$updateSource = $api->chooseReference($this->branch);
if ( $updateSource ) {
$ref = $updateSource->name;
$update->download_url = $updateSource->downloadUrl;
} else {
do_action(
'puc_api_error',
new WP_Error(
'puc-no-update-source',
'Could not retrieve version information from the repository. '
. 'This usually means that the update checker either can\'t connect '
. 'to the repository or it\'s configured incorrectly.'
),
null, null, $this->slug
);
$ref = $this->branch;
}
//Get headers from the main stylesheet in this branch/tag. Its "Version" header and other metadata
//are what the WordPress install will actually see after upgrading, so they take precedence over releases/tags.
$remoteHeader = $this->getFileHeader($api->getRemoteFile('style.css', $ref));
$update->version = Puc_v4p4_Utils::findNotEmpty(array(
$remoteHeader['Version'],
Puc_v4p4_Utils::get($updateSource, 'version'),
));
//The details URL defaults to the Theme URI header or the repository URL.
$update->details_url = Puc_v4p4_Utils::findNotEmpty(array(
$remoteHeader['ThemeURI'],
$this->theme->get('ThemeURI'),
$this->metadataUrl,
));
if ( empty($update->version) ) {
//It looks like we didn't find a valid update after all.
$update = null;
}
$update = $this->filterUpdateResult($update);
return $update;
}
//FIXME: This is duplicated code. Both theme and plugin subclasses that use VCS share these methods.
public function setBranch($branch) {
$this->branch = $branch;
return $this;
}
public function setAuthentication($credentials) {
$this->api->setAuthentication($credentials);
return $this;
}
public function getVcsApi() {
return $this->api;
}
public function getUpdate() {
$update = parent::getUpdate();
if ( isset($update) && !empty($update->download_url) ) {
$update->download_url = $this->api->signDownloadUrl($update->download_url);
}
return $update;
}
public function onDisplayConfiguration($panel) {
parent::onDisplayConfiguration($panel);
$panel->row('Branch', $this->branch);
$panel->row('Authentication enabled', $this->api->isAuthenticationEnabled() ? 'Yes' : 'No');
$panel->row('API client', get_class($this->api));
}
}
endif;

View File

@@ -1,274 +0,0 @@
Plugin Update Checker
=====================
This is a custom update checker library for WordPress plugins and themes. It lets you add automatic update notifications and one-click upgrades to your commercial plugins, private themes, and so on. All you need to do is put your plugin/theme details in a JSON file, place the file on your server, and pass the URL to the library. The library periodically checks the URL to see if there's a new version available and displays an update notification to the user if necessary.
From the users' perspective, it works just like with plugins and themes hosted on WordPress.org. The update checker uses the default upgrade UI that is familiar to most WordPress users.
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**
- [Getting Started](#getting-started)
- [Self-hosted Plugins and Themes](#self-hosted-plugins-and-themes)
- [How to Release an Update](#how-to-release-an-update)
- [Notes](#notes)
- [GitHub Integration](#github-integration)
- [How to Release an Update](#how-to-release-an-update-1)
- [Notes](#notes-1)
- [BitBucket Integration](#bitbucket-integration)
- [How to Release an Update](#how-to-release-an-update-2)
- [GitLab Integration](#gitlab-integration)
- [How to Release an Update](#how-to-release-an-update-3)
- [Resources](#resources)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
Getting Started
---------------
### Self-hosted Plugins and Themes
1. Download [the latest release](https://github.com/YahnisElsts/plugin-update-checker/releases/latest) and copy the `plugin-update-checker` directory to your plugin or theme.
2. Go to the `examples` subdirectory and open the .json file that fits your project type. Replace the placeholder data with your plugin/theme details.
- Plugin example:
```json
{
"name" : "Plugin Name",
"version" : "2.0",
"download_url" : "http://example.com/plugin-name-2.0.zip",
"sections" : {
"description" : "Plugin description here. You can use HTML."
}
}
```
This is a minimal example that leaves out optional fields. See [this table](https://docs.google.com/spreadsheets/d/1eOBbW7Go2qEQXReOOCdidMTf_tDYRq4JfegcO1CBPIs/edit?usp=sharing&authkey=CK7h9toK&output=html) for a full list of supported fields and their descriptions.
- Theme example:
```json
{
"version": "2.0",
"details_url": "http://example.com/version-2.0-details.html",
"download_url": "http://example.com/example-theme-2.0.zip"
}
```
This is actually a complete example that shows all theme-related fields. `version` and `download_url` should be self-explanatory. The `details_url` key specifies the page that the user will see if they click the "View version 1.2.3 details" link in an update notification.
3. Upload the JSON file to a publicly accessible location.
4. Add the following code to the main plugin file or to the `functions.php` file:
```php
require 'path/to/plugin-update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
'http://example.com/path/to/details.json',
__FILE__, //Full path to the main plugin file or functions.php.
'unique-plugin-or-theme-slug'
);
```
Note: If you're using the Composer autoloader, you don't need to explicitly `require` the library.
#### How to Release an Update
Change the `version` number in the JSON file and make sure that `download_url` points to the latest version. Update the other fields if necessary. Tip: You can use [wp-update-server](https://github.com/YahnisElsts/wp-update-server) to automate this process.
By default, the library will check the specified URL for changes every 12 hours. You can force it to check immediately by clicking the "Check for updates" link on the "Plugins" page (it's next to the "Visit plugin site" link). Themes don't have that link, but you can also trigger an update check like this:
1. Install [Debug Bar](https://srd.wordpress.org/plugins/debug-bar/).
2. Click the "Debug" menu in the Admin Bar (a.k.a Toolbar).
3. Open the "PUC (your-slug)" panel.
4. Click the "Check Now" button.
#### Notes
- The second argument passed to `buildUpdateChecker` must be the absolute path to the main plugin file or any file in the theme directory. If you followed the "getting started" instructions, you can just use the `__FILE__` constant.
- The third argument - i.e. the slug - is optional but recommended. In most cases, the slug should be the same as the name of your plugin directory. For example, if your plugin lives in `/wp-content/plugins/my-plugin`, set the slug to `my-plugin`. If the slug is omitted, the update checker will use the name of the main plugin file as the slug (e.g. `my-cool-plugin.php` &rarr; `my-cool-plugin`). This can lead to conflicts if your plugin has a generic file name like `plugin.php`.
This doesn't affect themes because PUC uses the theme directory name as the default slug. Still, if you're planning to use the slug in your own code - e.g. to filter updates or override update checker behaviour - it can be a good idea to set it explicitly.
### GitHub Integration
1. Download [the latest release](https://github.com/YahnisElsts/plugin-update-checker/releases/latest) and copy the `plugin-update-checker` directory to your plugin or theme.
2. Add the following code to the main plugin file or `functions.php`:
```php
require 'plugin-update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
'https://github.com/user-name/repo-name/',
__FILE__,
'unique-plugin-or-theme-slug'
);
//Optional: If you're using a private repository, specify the access token like this:
$myUpdateChecker->setAuthentication('your-token-here');
//Optional: Set the branch that contains the stable release.
$myUpdateChecker->setBranch('stable-branch-name');
```
3. Plugins only: Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/about/readme.txt) to your repository. The contents of this file will be shown when the user clicks the "View version 1.2.3 details" link.
#### How to Release an Update
This library supports a couple of different ways to release updates on GitHub. Pick the one that best fits your workflow.
- **GitHub releases**
Create a new release using the "Releases" feature on GitHub. The tag name and release title don't matter. The description is optional, but if you do provide one, it will be displayed when the user clicks the "View version x.y.z details" link on the "Plugins" page. Note that PUC ignores releases marked as "This is a pre-release".
- **Tags**
To release version 1.2.3, create a new Git tag named `v1.2.3` or `1.2.3`. That's it.
PUC doesn't require strict adherence to [SemVer](http://semver.org/). These are all valid tag names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5`. However, be warned that it's not smart enough to filter out alpha/beta/RC versions. If that's a problem, you might want to use GitHub releases or branches instead.
- **Stable branch**
Point the update checker at a stable, production-ready branch:
```php
$updateChecker->setBranch('branch-name');
```
PUC will periodically check the `Version` header in the main plugin file or `style.css` and display a notification if it's greater than the installed version.
Caveat: If you set the branch to `master` (the default), the update checker will look for recent releases and tags first. It'll only use the `master` branch if it doesn't find anything else suitable.
#### Notes
The library will pull update details from the following parts of a release/tag/branch:
- Version number
- The "Version" plugin header.
- The latest GitHub release or tag name.
- Changelog
- The "Changelog" section of `readme.txt`.
- One of the following files:
CHANGES.md, CHANGELOG.md, changes.md, changelog.md
- GitHub release notes.
- Required and tested WordPress versions
- The "Requires at least" and "Tested up to" fields in `readme.txt`.
- The following plugin headers:
`Required WP`, `Tested WP`, `Requires at least`, `Tested up to`
- "Last updated" timestamp
- The creation timestamp of the latest GitHub release.
- The latest commit in the selected tag or branch.
- Number of downloads
- The `download_count` statistic of the latest release.
- If you're not using GitHub releases, there will be no download stats.
- Other plugin details - author, homepage URL, description
- The "Description" section of `readme.txt`.
- Remote plugin headers (i.e. the latest version on GitHub).
- Local plugin headers (i.e. the currently installed version).
- Ratings, banners, screenshots
- Not supported.
### BitBucket Integration
1. Download [the latest release](https://github.com/YahnisElsts/plugin-update-checker/releases/latest) and copy the `plugin-update-checker` directory to your plugin or theme.
2. Add the following code to the main plugin file or `functions.php`:
```php
require 'plugin-update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
'https://bitbucket.org/user-name/repo-name',
__FILE__,
'unique-plugin-or-theme-slug'
);
//Optional: If you're using a private repository, create an OAuth consumer
//and set the authentication credentials like this:
//Note: For now you need to check "This is a private consumer" when
//creating the consumer to work around #134:
// https://github.com/YahnisElsts/plugin-update-checker/issues/134
$myUpdateChecker->setAuthentication(array(
'consumer_key' => '...',
'consumer_secret' => '...',
));
//Optional: Set the branch that contains the stable release.
$myUpdateChecker->setBranch('stable-branch-name');
```
3. Optional: Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/about/readme.txt) to your repository. For plugins, the contents of this file will be shown when the user clicks the "View version 1.2.3 details" link.
#### How to Release an Update
BitBucket doesn't have an equivalent to GitHub's releases, so the process is slightly different. You can use any of the following approaches:
- **`Stable tag` header**
This is the recommended approach if you're using tags to mark each version. Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/about/readme.txt) to your repository. Set the "stable tag" header to the tag that represents the latest release. Example:
```text
Stable tag: v1.2.3
```
The tag doesn't have to start with a "v" or follow any particular format. You can use any name you like as long as it's a valid Git tag.
Tip: If you explicitly set a stable branch, the update checker will look for a `readme.txt` in that branch. Otherwise it will only look at the `master` branch.
- **Tags**
You can skip the "stable tag" bit and just create a new Git tag named `v1.2.3` or `1.2.3`. The update checker will look at the most recent tags and pick the one that looks like the highest version number.
PUC doesn't require strict adherence to [SemVer](http://semver.org/). These are all valid tag names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5`. However, be warned that it's not smart enough to filter out alpha/beta/RC versions.
- **Stable branch**
Point the update checker at a stable, production-ready branch:
```php
$updateChecker->setBranch('branch-name');
```
PUC will periodically check the `Version` header in the main plugin file or `style.css` and display a notification if it's greater than the installed version. Caveat: If you set the branch to `master`, the update checker will still look for tags first.
### GitLab Integration
1. Download [the latest release](https://github.com/YahnisElsts/plugin-update-checker/releases/latest) and copy the `plugin-update-checker` directory to your plugin or theme.
2. Add the following code to the main plugin file or `functions.php`:
```php
require 'plugin-update-checker/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
'https://gitlab.com/user-name/repo-name/',
__FILE__,
'unique-plugin-or-theme-slug'
);
//Note: Self-hosted instances of GitLab must be initialized like this:
$myUpdateChecker = new Puc_v4p4_Vcs_PluginUpdateChecker(
new Puc_v4p4_Vcs_GitLabApi('https://myserver.com/user-name/repo-name/'),
__FILE__,
'unique-plugin-or-theme-slug'
);
//Optional: If you're using a private repository, specify the access token like this:
$myUpdateChecker->setAuthentication('your-token-here');
//Optional: Set the branch that contains the stable release.
$myUpdateChecker->setBranch('stable-branch-name');
```
3. Plugins only: Add a `readme.txt` file formatted according to the [WordPress.org plugin readme standard](https://wordpress.org/plugins/about/readme.txt) to your repository. The contents of this file will be shown when the user clicks the "View version 1.2.3 details" link.
#### How to Release an Update
GitLab doesn't have an equivalent to GitHub's releases, so the process is slightly different. You can use any of the following approaches:
- **Tags**
To release version 1.2.3, create a new Git tag named `v1.2.3` or `1.2.3`. That's it.
PUC doesn't require strict adherence to [SemVer](http://semver.org/). These are all valid tag names: `v1.2.3`, `v1.2-foo`, `1.2.3_rc1-ABC`, `1.2.3.4.5`. However, be warned that it's not smart enough to filter out alpha/beta/RC versions. If that's a problem, you might want to use GitLab branches instead.
- **Stable branch**
Point the update checker at a stable, production-ready branch:
```php
$updateChecker->setBranch('branch-name');
```
PUC will periodically check the `Version` header in the main plugin file or `style.css` and display a notification if it's greater than the installed version.
Caveat: If you set the branch to `master` (the default), the update checker will look for recent releases and tags first. It'll only use the `master` branch if it doesn't find anything else suitable.
Resources
---------
- [This blog post](http://w-shadow.com/blog/2010/09/02/automatic-updates-for-any-plugin/) has more information about the update checker API. *Slightly out of date.*
- [Debug Bar](https://wordpress.org/plugins/debug-bar/) - useful for testing and debugging the update checker.
- [Securing download links](http://w-shadow.com/blog/2013/03/19/plugin-updates-securing-download-links/) - a general overview.
- [A GUI for entering download credentials](http://open-tools.net/documentation/tutorial-automatic-updates.html#wordpress)
- [Theme Update Checker](http://w-shadow.com/blog/2011/06/02/automatic-updates-for-commercial-themes/) - an older, theme-only variant of this update checker.

View File

@@ -1,70 +0,0 @@
.puc-debug-bar-panel-v4 pre {
margin-top: 0;
}
/* Style the debug data table to match "widefat" table style used by WordPress. */
table.puc-debug-data {
width: 100%;
clear: both;
margin: 0;
border-spacing: 0;
background-color: #f9f9f9;
border-radius: 3px;
border: 1px solid #dfdfdf;
border-collapse: separate;
}
table.puc-debug-data * {
word-wrap: break-word;
}
table.puc-debug-data th {
width: 11em;
padding: 7px 7px 8px;
text-align: left;
font-family: "Georgia", "Times New Roman", "Bitstream Charter", "Times", serif;
font-weight: 400;
font-size: 14px;
line-height: 1.3em;
text-shadow: rgba(255, 255, 255, 0.804) 0 1px 0;
}
table.puc-debug-data td, table.puc-debug-data th {
border-width: 1px 0;
border-style: solid;
border-top-color: #fff;
border-bottom-color: #dfdfdf;
text-transform: none;
}
table.puc-debug-data td {
color: #555;
font-size: 12px;
padding: 4px 7px 2px;
vertical-align: top;
}
.puc-ajax-response {
border: 1px solid #dfdfdf;
border-radius: 3px;
padding: 0.5em;
margin: 5px 0;
background-color: white;
}
.puc-ajax-nonce {
display: none;
}
.puc-ajax-response dt {
margin: 0;
}
.puc-ajax-response dd {
margin: 0 0 1em;
}

View File

@@ -1,52 +0,0 @@
jQuery(function($) {
function runAjaxAction(button, action) {
button = $(button);
var panel = button.closest('.puc-debug-bar-panel-v4');
var responseBox = button.closest('td').find('.puc-ajax-response');
responseBox.text('Processing...').show();
$.post(
ajaxurl,
{
action : action,
uid : panel.data('uid'),
_wpnonce: panel.data('nonce')
},
function(data) {
responseBox.html(data);
},
'html'
);
}
$('.puc-debug-bar-panel-v4 input[name="puc-check-now-button"]').click(function() {
runAjaxAction(this, 'puc_v4_debug_check_now');
return false;
});
$('.puc-debug-bar-panel-v4 input[name="puc-request-info-button"]').click(function() {
runAjaxAction(this, 'puc_v4_debug_request_info');
return false;
});
// Debug Bar uses the panel class name as part of its link and container IDs. This means we can
// end up with multiple identical IDs if more than one plugin uses the update checker library.
// Fix it by replacing the class name with the plugin slug.
var panels = $('#debug-menu-targets').find('.puc-debug-bar-panel-v4');
panels.each(function() {
var panel = $(this);
var uid = panel.data('uid');
var target = panel.closest('.debug-menu-target');
//Change the panel wrapper ID.
target.attr('id', 'debug-menu-target-puc-' + uid);
//Change the menu link ID as well and point it at the new target ID.
$('#debug-bar-menu').find('.puc-debug-menu-link-' + uid)
.closest('.debug-menu-link')
.attr('id', 'debug-menu-link-puc-' + uid)
.attr('href', '#' + target.attr('id'));
});
});

View File

@@ -1,45 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-05-20 10:53+0300\n"
"PO-Revision-Date: 2017-07-05 15:39+0000\n"
"Last-Translator: Vojtěch Sajdl <vojtech@sajdl.com>\n"
"Language-Team: Czech (Czech Republic)\n"
"Language: cs-CZ\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Loco-Source-Locale: cs_CZ\n"
"X-Generator: Loco - https://localise.biz/\n"
"X-Poedit-Basepath: ..\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"X-Poedit-SearchPath-0: .\n"
"X-Loco-Parser: loco_parse_po"
#: Puc/v4p1/Plugin/UpdateChecker.php:358
msgid "Check for updates"
msgstr "Zkontrolovat aktualizace"
#: Puc/v4p1/Plugin/UpdateChecker.php:405
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Plugin %s je aktuální."
#: Puc/v4p1/Plugin/UpdateChecker.php:407
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Nová verze pluginu %s je dostupná."
#: Puc/v4p1/Plugin/UpdateChecker.php:409
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Neznámý status kontroly aktualizací \"%s\""
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83
msgid "There is no changelog available."
msgstr "Changelog není dostupný."

View File

@@ -1,42 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-05-20 10:53+0300\n"
"PO-Revision-Date: 2017-10-17 11:07+0200\n"
"Last-Translator: Mikk3lRo\n"
"Language-Team: Mikk3lRo\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.4\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Language: da_DK\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p1/Plugin/UpdateChecker.php:358
msgid "Check for updates"
msgstr "Undersøg for opdateringer"
#: Puc/v4p1/Plugin/UpdateChecker.php:405
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Plugin'et %s er allerede opdateret."
#: Puc/v4p1/Plugin/UpdateChecker.php:407
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "En ny version af plugin'et %s er tilgængelig."
#: Puc/v4p1/Plugin/UpdateChecker.php:409
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Ukendt opdateringsstatus: \"%s\""
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83
msgid "There is no changelog available."
msgstr "Der er ingen ændringslog tilgængelig."

View File

@@ -1,38 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2016-06-29 20:21+0100\n"
"PO-Revision-Date: 2016-06-29 20:23+0100\n"
"Last-Translator: Igor Lückel <info@igorlueckel.de>\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.8.1\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e\n"
"Language: de_DE\n"
"X-Poedit-SearchPath-0: .\n"
#: github-checker.php:137
msgid "There is no changelog available."
msgstr "Es ist keine Liste von Programmänderungen verfügbar."
#: plugin-update-checker.php:852
msgid "Check for updates"
msgstr "Nach Update suchen"
#: plugin-update-checker.php:896
msgid "This plugin is up to date."
msgstr "Das Plugin ist aktuell."
#: plugin-update-checker.php:898
msgid "A new version of this plugin is available."
msgstr "Es ist eine neue Version für das Plugin verfügbar."
#: plugin-update-checker.php:900
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Unbekannter Update Status \"%s\""

View File

@@ -1,38 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2016-02-17 14:21+0100\n"
"PO-Revision-Date: 2016-10-28 14:30+0330\n"
"Last-Translator: studio RVOLA <hello@rvola.com>\n"
"Language-Team: Pro Style <info@prostyle.ir>\n"
"Language: fa_IR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.8.8\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e\n"
"X-Poedit-SearchPath-0: .\n"
#: github-checker.php:120
msgid "There is no changelog available."
msgstr "شرحی برای تغییرات یافت نشد"
#: plugin-update-checker.php:637
msgid "Check for updates"
msgstr "بررسی برای بروزرسانی "
#: plugin-update-checker.php:681
msgid "This plugin is up to date."
msgstr "شما از آخرین نسخه استفاده میکنید . به‌روز باشید"
#: plugin-update-checker.php:683
msgid "A new version of this plugin is available."
msgstr "نسخه جدیدی برای افزونه ارائه شده است ."
#: plugin-update-checker.php:685
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "وضعیت ناشناخته برای بروزرسانی \"%s\""

View File

@@ -1,48 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2018-02-12 10:32-0500\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.4\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: Eric Gagnon <eric.gagnon@banq.qc.ca>\n"
"Language: fr_CA\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Vérifier les mises à jour"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Lextension %s est à jour."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Une nouvelle version de lextension %s est disponible."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "Impossible de déterminer si une mise à jour est disponible pour \"%s\""
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Un problème inconnu est survenu \"%s\""
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "Il ny a aucun journal de mise à jour disponible."

View File

@@ -1,42 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-07-07 14:53+0200\n"
"PO-Revision-Date: 2017-07-07 14:54+0200\n"
"Language-Team: studio RVOLA <http://www.rvola.com>\n"
"Language: fr_FR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.2\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: Nicolas GEHIN\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p1/Plugin/UpdateChecker.php:358
msgid "Check for updates"
msgstr "Vérifier les mises à jour"
#: Puc/v4p1/Plugin/UpdateChecker.php:405
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Lextension %s est à jour."
#: Puc/v4p1/Plugin/UpdateChecker.php:407
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Une nouvelle version de lextension %s est disponible."
#: Puc/v4p1/Plugin/UpdateChecker.php:409
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Un problème inconnu est survenu \"%s\""
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:85
msgid "There is no changelog available."
msgstr "Il ny a aucun journal de mise à jour disponible."

View File

@@ -1,41 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2016-01-11 21:23+0100\n"
"PO-Revision-Date: 2016-01-11 21:25+0100\n"
"Last-Translator: Tamás András Horváth <htomy92@gmail.com>\n"
"Language-Team: \n"
"Language: hu_HU\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.8.6\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e\n"
"X-Poedit-SearchPath-0: .\n"
#: github-checker.php:137
msgid "There is no changelog available."
msgstr "Nem érhető el a changelog."
#: plugin-update-checker.php:852
msgid "Check for updates"
msgstr "Frissítés ellenőrzése"
#: plugin-update-checker.php:896
msgid "This plugin is up to date."
msgstr "Ez a plugin naprakész."
#: plugin-update-checker.php:898
msgid "A new version of this plugin is available."
msgstr "Új verzió érhető el a kiegészítőhöz"
#: plugin-update-checker.php:900
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Ismeretlen a frissítés ellenőrző státusza \"%s\""
#~ msgid "Every %d hours"
#~ msgstr "Minden %d órában"

View File

@@ -1,38 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2016-06-29 20:21+0100\n"
"PO-Revision-Date: 2017-01-15 12:24+0100\n"
"Last-Translator: Igor Lückel <info@igorlueckel.de>\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.5.5\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e\n"
"Language: de_DE\n"
"X-Poedit-SearchPath-0: .\n"
#: github-checker.php:137
msgid "There is no changelog available."
msgstr "Non c'è alcuna sezione di aggiornamento disponibile"
#: plugin-update-checker.php:852
msgid "Check for updates"
msgstr "Verifica aggiornamenti"
#: plugin-update-checker.php:896
msgid "This plugin is up to date."
msgstr "Il plugin è aggiornato"
#: plugin-update-checker.php:898
msgid "A new version of this plugin is available."
msgstr "Una nuova versione del plugin è disponibile"
#: plugin-update-checker.php:900
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Si è verificato un problema sconosciuto \"%s\""

View File

@@ -1,42 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-06-02 18:31+0900\n"
"PO-Revision-Date: 2017-06-02 18:32+0900\n"
"Last-Translator: tak <tak7725@gmail.com>\n"
"Language-Team: \n"
"Language: ja_JP\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.2\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x;_x:1,2c\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p1/Plugin/UpdateChecker.php:362
msgid "Check for updates"
msgstr "アップデートを確認"
#: Puc/v4p1/Plugin/UpdateChecker.php:409
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "%s プラグインは、最新バージョンです。"
#: Puc/v4p1/Plugin/UpdateChecker.php:411
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "%s プラグインの最新バージョンがあります。"
#: Puc/v4p1/Plugin/UpdateChecker.php:413
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "バージョンアップの確認で想定外の状態になりました。ステータス:\"%s\""
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83
msgid "There is no changelog available."
msgstr "更新履歴はありません。"

View File

@@ -1,48 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2018-03-25 18:15+0200\n"
"PO-Revision-Date: 2018-03-25 18:32+0200\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.8.7.1\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: Frank Goossens <frank@optimizingmatters.com>\n"
"Language: nl_BE\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Controleer op nieuwe versies"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "De meest recente %s versie is geïnstalleerd."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Er is een nieuwe versie van %s beschikbaar."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "Kon niet bepalen of er nieuwe versie van %s beschikbaar is."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Ongekende status bij controle op nieuwe versie: \"%s\""
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "Er is geen changelog beschikbaar."

View File

@@ -1,48 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2018-03-25 18:15+0200\n"
"PO-Revision-Date: 2018-03-25 18:32+0200\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.8.7.1\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: Frank Goossens <frank@optimizingmatters.com>\n"
"Language: nl_NL\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr "Controleer op nieuwe versies"
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "De meest recente %s versie is geïnstalleerd."
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Er is een nieuwe versie van %s beschikbaar."
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr "Kon niet bepalen of er nieuwe versie van %s beschikbaar is."
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Ongekende status bij controle op nieuwe versie: \"%s\""
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr "Er is geen changelog beschikbaar."

View File

@@ -1,48 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-05-19 15:41-0300\n"
"PO-Revision-Date: 2017-05-19 15:42-0300\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: pt_BR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 1.8.8\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x;_x:1,2c\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p1/Plugin/UpdateChecker.php:358
msgid "Check for updates"
msgstr "Verificar Atualizações"
#: Puc/v4p1/Plugin/UpdateChecker.php:401 Puc/v4p1/Plugin/UpdateChecker.php:406
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "O plugin %s já está na sua versão mais recente."
#: Puc/v4p1/Plugin/UpdateChecker.php:408
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Há uma nova versão para o plugin %s disponível para download."
#: Puc/v4p1/Plugin/UpdateChecker.php:410
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Status \"%s\" desconhecido."
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83
msgid "There is no changelog available."
msgstr "Não há um changelog disponível."
#~ msgid "The %s plugin is up to date."
#~ msgstr "O plugin %s já está na sua versão mais recente."
#~ msgid "A new version of the %s plugin is available."
#~ msgstr "Há uma nova versão para o plugin %s disponível para download."

View File

@@ -1,42 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-05-20 10:53+0300\n"
"PO-Revision-Date: 2017-10-16 15:02+0200\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.4\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"Last-Translator: \n"
"Language: sv_SE\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p1/Plugin/UpdateChecker.php:358
msgid "Check for updates"
msgstr "Sök efter uppdateringar"
#: Puc/v4p1/Plugin/UpdateChecker.php:405
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr "Tillägget %s är uppdaterat."
#: Puc/v4p1/Plugin/UpdateChecker.php:407
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr "Det finns en ny version av tillägget %s."
#: Puc/v4p1/Plugin/UpdateChecker.php:409
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr "Okänd status för kontroll av uppdatering “%s”"
#: Puc/v4p1/Vcs/PluginUpdateChecker.php:83
msgid "There is no changelog available."
msgstr "Det finns ingen ändringslogg tillgänglig."

View File

@@ -1,49 +0,0 @@
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: plugin-update-checker\n"
"POT-Creation-Date: 2017-11-24 17:02+0200\n"
"PO-Revision-Date: 2016-01-10 20:59+0100\n"
"Last-Translator: Tamás András Horváth <htomy92@gmail.com>\n"
"Language-Team: \n"
"Language: en_US\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.4\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n"
"X-Poedit-SearchPath-0: .\n"
#: Puc/v4p3/Plugin/UpdateChecker.php:395
msgid "Check for updates"
msgstr ""
#: Puc/v4p3/Plugin/UpdateChecker.php:548
#, php-format
msgctxt "the plugin title"
msgid "The %s plugin is up to date."
msgstr ""
#: Puc/v4p3/Plugin/UpdateChecker.php:550
#, php-format
msgctxt "the plugin title"
msgid "A new version of the %s plugin is available."
msgstr ""
#: Puc/v4p3/Plugin/UpdateChecker.php:552
#, php-format
msgctxt "the plugin title"
msgid "Could not determine if updates are available for %s."
msgstr ""
#: Puc/v4p3/Plugin/UpdateChecker.php:558
#, php-format
msgid "Unknown update checker status \"%s\""
msgstr ""
#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
msgid "There is no changelog available."
msgstr ""

View File

@@ -1,7 +0,0 @@
Copyright (c) 2017 Jānis Elsts
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,24 +0,0 @@
<?php
/**
* Plugin Update Checker Library 4.4
* http://w-shadow.com/
*
* Copyright 2017 Janis Elsts
* Released under the MIT license. See license.txt for details.
*/
require dirname(__FILE__) . '/Puc/v4p4/Factory.php';
require dirname(__FILE__) . '/Puc/v4/Factory.php';
require dirname(__FILE__) . '/Puc/v4p4/Autoloader.php';
new Puc_v4p4_Autoloader();
//Register classes defined in this file with the factory.
Puc_v4_Factory::addVersion('Plugin_UpdateChecker', 'Puc_v4p4_Plugin_UpdateChecker', '4.4');
Puc_v4_Factory::addVersion('Theme_UpdateChecker', 'Puc_v4p4_Theme_UpdateChecker', '4.4');
Puc_v4_Factory::addVersion('Vcs_PluginUpdateChecker', 'Puc_v4p4_Vcs_PluginUpdateChecker', '4.4');
Puc_v4_Factory::addVersion('Vcs_ThemeUpdateChecker', 'Puc_v4p4_Vcs_ThemeUpdateChecker', '4.4');
Puc_v4_Factory::addVersion('GitHubApi', 'Puc_v4p4_Vcs_GitHubApi', '4.4');
Puc_v4_Factory::addVersion('BitBucketApi', 'Puc_v4p4_Vcs_BitBucketApi', '4.4');
Puc_v4_Factory::addVersion('GitLabApi', 'Puc_v4p4_Vcs_GitLabApi', '4.4');

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,337 +0,0 @@
<?php
if ( !class_exists('PucReadmeParser', false) ):
/**
* This is a slightly modified version of github.com/markjaquith/WordPress-Plugin-Readme-Parser
* It uses Parsedown instead of the "Markdown Extra" parser.
*/
class PucReadmeParser {
function __construct() {
// This space intentionally blank
}
function parse_readme( $file ) {
$file_contents = @implode('', @file($file));
return $this->parse_readme_contents( $file_contents );
}
function parse_readme_contents( $file_contents ) {
$file_contents = str_replace(array("\r\n", "\r"), "\n", $file_contents);
$file_contents = trim($file_contents);
if ( 0 === strpos( $file_contents, "\xEF\xBB\xBF" ) )
$file_contents = substr( $file_contents, 3 );
// Markdown transformations
$file_contents = preg_replace( "|^###([^#]+)#*?\s*?\n|im", '=$1='."\n", $file_contents );
$file_contents = preg_replace( "|^##([^#]+)#*?\s*?\n|im", '==$1=='."\n", $file_contents );
$file_contents = preg_replace( "|^#([^#]+)#*?\s*?\n|im", '===$1==='."\n", $file_contents );
// === Plugin Name ===
// Must be the very first thing.
if ( !preg_match('|^===(.*)===|', $file_contents, $_name) )
return array(); // require a name
$name = trim($_name[1], '=');
$name = $this->sanitize_text( $name );
$file_contents = $this->chop_string( $file_contents, $_name[0] );
// Requires at least: 1.5
if ( preg_match('|Requires at least:(.*)|i', $file_contents, $_requires_at_least) )
$requires_at_least = $this->sanitize_text($_requires_at_least[1]);
else
$requires_at_least = NULL;
// Tested up to: 2.1
if ( preg_match('|Tested up to:(.*)|i', $file_contents, $_tested_up_to) )
$tested_up_to = $this->sanitize_text( $_tested_up_to[1] );
else
$tested_up_to = NULL;
// Stable tag: 10.4-ride-the-fire-eagle-danger-day
if ( preg_match('|Stable tag:(.*)|i', $file_contents, $_stable_tag) )
$stable_tag = $this->sanitize_text( $_stable_tag[1] );
else
$stable_tag = NULL; // we assume trunk, but don't set it here to tell the difference between specified trunk and default trunk
// Tags: some tag, another tag, we like tags
if ( preg_match('|Tags:(.*)|i', $file_contents, $_tags) ) {
$tags = preg_split('|,[\s]*?|', trim($_tags[1]));
foreach ( array_keys($tags) as $t )
$tags[$t] = $this->sanitize_text( $tags[$t] );
} else {
$tags = array();
}
// Contributors: markjaquith, mdawaffe, zefrank
$contributors = array();
if ( preg_match('|Contributors:(.*)|i', $file_contents, $_contributors) ) {
$temp_contributors = preg_split('|,[\s]*|', trim($_contributors[1]));
foreach ( array_keys($temp_contributors) as $c ) {
$tmp_sanitized = $this->user_sanitize( $temp_contributors[$c] );
if ( strlen(trim($tmp_sanitized)) > 0 )
$contributors[$c] = $tmp_sanitized;
unset($tmp_sanitized);
}
}
// Donate Link: URL
if ( preg_match('|Donate link:(.*)|i', $file_contents, $_donate_link) )
$donate_link = esc_url( $_donate_link[1] );
else
$donate_link = NULL;
// togs, conts, etc are optional and order shouldn't matter. So we chop them only after we've grabbed their values.
foreach ( array('tags', 'contributors', 'requires_at_least', 'tested_up_to', 'stable_tag', 'donate_link') as $chop ) {
if ( $$chop ) {
$_chop = '_' . $chop;
$file_contents = $this->chop_string( $file_contents, ${$_chop}[0] );
}
}
$file_contents = trim($file_contents);
// short-description fu
if ( !preg_match('/(^(.*?))^[\s]*=+?[\s]*.+?[\s]*=+?/ms', $file_contents, $_short_description) )
$_short_description = array( 1 => &$file_contents, 2 => &$file_contents );
$short_desc_filtered = $this->sanitize_text( $_short_description[2] );
$short_desc_length = strlen($short_desc_filtered);
$short_description = substr($short_desc_filtered, 0, 150);
if ( $short_desc_length > strlen($short_description) )
$truncated = true;
else
$truncated = false;
if ( $_short_description[1] )
$file_contents = $this->chop_string( $file_contents, $_short_description[1] ); // yes, the [1] is intentional
// == Section ==
// Break into sections
// $_sections[0] will be the title of the first section, $_sections[1] will be the content of the first section
// the array alternates from there: title2, content2, title3, content3... and so forth
$_sections = preg_split('/^[\s]*==[\s]*(.+?)[\s]*==/m', $file_contents, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
$sections = array();
for ( $i=1; $i <= count($_sections); $i +=2 ) {
$_sections[$i] = preg_replace('/(^[\s]*)=[\s]+(.+?)[\s]+=/m', '$1<h4>$2</h4>', $_sections[$i]);
$_sections[$i] = $this->filter_text( $_sections[$i], true );
$title = $this->sanitize_text( $_sections[$i-1] );
$sections[str_replace(' ', '_', strtolower($title))] = array('title' => $title, 'content' => $_sections[$i]);
}
// Special sections
// This is where we nab our special sections, so we can enforce their order and treat them differently, if needed
// upgrade_notice is not a section, but parse it like it is for now
$final_sections = array();
foreach ( array('description', 'installation', 'frequently_asked_questions', 'screenshots', 'changelog', 'change_log', 'upgrade_notice') as $special_section ) {
if ( isset($sections[$special_section]) ) {
$final_sections[$special_section] = $sections[$special_section]['content'];
unset($sections[$special_section]);
}
}
if ( isset($final_sections['change_log']) && empty($final_sections['changelog']) )
$final_sections['changelog'] = $final_sections['change_log'];
$final_screenshots = array();
if ( isset($final_sections['screenshots']) ) {
preg_match_all('|<li>(.*?)</li>|s', $final_sections['screenshots'], $screenshots, PREG_SET_ORDER);
if ( $screenshots ) {
foreach ( (array) $screenshots as $ss )
$final_screenshots[] = $ss[1];
}
}
// Parse the upgrade_notice section specially:
// 1.0 => blah, 1.1 => fnord
$upgrade_notice = array();
if ( isset($final_sections['upgrade_notice']) ) {
$split = preg_split( '#<h4>(.*?)</h4>#', $final_sections['upgrade_notice'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
if ( count($split) >= 2 ) {
for ( $i = 0; $i < count( $split ); $i += 2 ) {
$upgrade_notice[$this->sanitize_text( $split[$i] )] = substr( $this->sanitize_text( $split[$i + 1] ), 0, 300 );
}
}
unset( $final_sections['upgrade_notice'] );
}
// No description?
// No problem... we'll just fall back to the old style of description
// We'll even let you use markup this time!
$excerpt = false;
if ( !isset($final_sections['description']) ) {
$final_sections = array_merge(array('description' => $this->filter_text( $_short_description[2], true )), $final_sections);
$excerpt = true;
}
// dump the non-special sections into $remaining_content
// their order will be determined by their original order in the readme.txt
$remaining_content = '';
foreach ( $sections as $s_name => $s_data ) {
$remaining_content .= "\n<h3>{$s_data['title']}</h3>\n{$s_data['content']}";
}
$remaining_content = trim($remaining_content);
// All done!
// $r['tags'] and $r['contributors'] are simple arrays
// $r['sections'] is an array with named elements
$r = array(
'name' => $name,
'tags' => $tags,
'requires_at_least' => $requires_at_least,
'tested_up_to' => $tested_up_to,
'stable_tag' => $stable_tag,
'contributors' => $contributors,
'donate_link' => $donate_link,
'short_description' => $short_description,
'screenshots' => $final_screenshots,
'is_excerpt' => $excerpt,
'is_truncated' => $truncated,
'sections' => $final_sections,
'remaining_content' => $remaining_content,
'upgrade_notice' => $upgrade_notice
);
return $r;
}
function chop_string( $string, $chop ) { // chop a "prefix" from a string: Agressive! uses strstr not 0 === strpos
if ( $_string = strstr($string, $chop) ) {
$_string = substr($_string, strlen($chop));
return trim($_string);
} else {
return trim($string);
}
}
function user_sanitize( $text, $strict = false ) { // whitelisted chars
if ( function_exists('user_sanitize') ) // bbPress native
return user_sanitize( $text, $strict );
if ( $strict ) {
$text = preg_replace('/[^a-z0-9-]/i', '', $text);
$text = preg_replace('|-+|', '-', $text);
} else {
$text = preg_replace('/[^a-z0-9_-]/i', '', $text);
}
return $text;
}
function sanitize_text( $text ) { // not fancy
$text = strip_tags($text);
$text = esc_html($text);
$text = trim($text);
return $text;
}
function filter_text( $text, $markdown = false ) { // fancy, Markdown
$text = trim($text);
$text = call_user_func( array( __CLASS__, 'code_trick' ), $text, $markdown ); // A better parser than Markdown's for: backticks -> CODE
if ( $markdown ) { // Parse markdown.
if ( !class_exists('Parsedown', false) ) {
/** @noinspection PhpIncludeInspection */
require_once(dirname(__FILE__) . '/Parsedown' . (version_compare(PHP_VERSION, '5.3.0', '>=') ? '' : 'Legacy') . '.php');
}
$instance = Parsedown::instance();
$text = $instance->text($text);
}
$allowed = array(
'a' => array(
'href' => array(),
'title' => array(),
'rel' => array()),
'blockquote' => array('cite' => array()),
'br' => array(),
'p' => array(),
'code' => array(),
'pre' => array(),
'em' => array(),
'strong' => array(),
'ul' => array(),
'ol' => array(),
'li' => array(),
'h3' => array(),
'h4' => array()
);
$text = balanceTags($text);
$text = wp_kses( $text, $allowed );
$text = trim($text);
return $text;
}
function code_trick( $text, $markdown ) { // Don't use bbPress native function - it's incompatible with Markdown
// If doing markdown, first take any user formatted code blocks and turn them into backticks so that
// markdown will preserve things like underscores in code blocks
if ( $markdown )
$text = preg_replace_callback("!(<pre><code>|<code>)(.*?)(</code></pre>|</code>)!s", array( __CLASS__,'decodeit'), $text);
$text = str_replace(array("\r\n", "\r"), "\n", $text);
if ( !$markdown ) {
// This gets the "inline" code blocks, but can't be used with Markdown.
$text = preg_replace_callback("|(`)(.*?)`|", array( __CLASS__, 'encodeit'), $text);
// This gets the "block level" code blocks and converts them to PRE CODE
$text = preg_replace_callback("!(^|\n)`(.*?)`!s", array( __CLASS__, 'encodeit'), $text);
} else {
// Markdown can do inline code, we convert bbPress style block level code to Markdown style
$text = preg_replace_callback("!(^|\n)([ \t]*?)`(.*?)`!s", array( __CLASS__, 'indent'), $text);
}
return $text;
}
function indent( $matches ) {
$text = $matches[3];
$text = preg_replace('|^|m', $matches[2] . ' ', $text);
return $matches[1] . $text;
}
function encodeit( $matches ) {
if ( function_exists('encodeit') ) // bbPress native
return encodeit( $matches );
$text = trim($matches[2]);
$text = htmlspecialchars($text, ENT_QUOTES);
$text = str_replace(array("\r\n", "\r"), "\n", $text);
$text = preg_replace("|\n\n\n+|", "\n\n", $text);
$text = str_replace('&amp;lt;', '&lt;', $text);
$text = str_replace('&amp;gt;', '&gt;', $text);
$text = "<code>$text</code>";
if ( "`" != $matches[1] )
$text = "<pre>$text</pre>";
return $text;
}
function decodeit( $matches ) {
if ( function_exists('decodeit') ) // bbPress native
return decodeit( $matches );
$text = $matches[2];
$trans_table = array_flip(get_html_translation_table(HTML_ENTITIES));
$text = strtr($text, $trans_table);
$text = str_replace('<br />', '', $text);
$text = str_replace('&#38;', '&', $text);
$text = str_replace('&#39;', "'", $text);
if ( '<pre><code>' == $matches[1] )
$text = "\n$text\n";
return "`$text`";
}
} // end class
endif;

View File

@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -1,67 +0,0 @@
# WP Package Updater - Plugins and themes update library
### Description
Used to enable updates for plugins and themes distributed via WP Plugin Update Server.
### Requirements
The library must sit in a `lib` folder at the root of the plugin or theme directory.
Before deploying the plugin or theme, make sure to change the following value:
- `https://your-update-server.com` => The URL of the server where WP Plugin Update Server is installed.
- `$prefix_updater` => Change this variable's name with your plugin or theme prefix
### Code to include in main plugin file
#### Simple update
```php
require_once plugin_dir_path( __FILE__ ) . 'lib/wp-package-updater/class-wp-package-updater.php';
$prefix_updater = new WP_Package_Updater(
'https://your-update-server.com',
wp_normalize_path( __FILE__ ),
wp_normalize_path( plugin_dir_path( __FILE__ ) ),
);
```
#### Update with license check
```php
require_once plugin_dir_path( __FILE__ ) . 'lib/wp-package-updater/class-wp-package-updater.php';
$prefix_updater = new WP_Package_Updater(
'https://your-update-server.com',
wp_normalize_path( __FILE__ ),
wp_normalize_path( plugin_dir_path( __FILE__ ) ),
true
);
```
### Code to include in functions.php
#### Simple update
```php
require_once get_stylesheet_directory() . '/lib/wp-package-updater/class-wp-package-updater.php';
$prefix_updater = new WP_Package_Updater(
'https://your-update-server.com',
wp_normalize_path( __FILE__ ),
get_stylesheet_directory(),
);
```
#### Update with license check
```php
require_once get_stylesheet_directory() . '/lib/wp-package-updater/class-wp-package-updater.php';
$prefix_updater = new WP_Package_Updater(
'https://your-update-server.com',
wp_normalize_path( __FILE__ ),
get_stylesheet_directory(),
true
);
```

View File

@@ -1,563 +0,0 @@
<?php
/**
* WP Package Updater
* Plugins and themes update library to enable with WP Plugin Update Server
*
* @author Alexandre Froger
* @version 1.4.0
* @see https://github.com/froger-me/wp-package-updater
* @copyright Alexandre Froger - https://www.froger.me
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/* ================================================================================================ */
/* WP Package Updater */
/* ================================================================================================ */
/**
* Copy/paste this section to your main plugin file or theme's functions.php and uncomment the sections below
* where appropriate to enable updates with WP Plugin Update Server.
*
* WARNING - READ FIRST:
* Before deploying the plugin or theme, make sure to change the following value
* - https://your-update-server.com => The URL of the server where WP Plugin Update Server is installed.
* - $prefix_updater => Change this variable's name with your plugin or theme prefix
**/
/** Uncomment for plugin updates **/
// require_once plugin_dir_path( __FILE__ ) . 'lib/wp-package-updater/class-wp-package-updater.php';
/** Enable plugin updates with license check **/
// $prefix_updater = new WP_Package_Updater(
// 'https://your-update-server.com',
// wp_normalize_path( __FILE__ ),
// wp_normalize_path( plugin_dir_path( __FILE__ ) ),
// true
// );
/** Enable plugin updates without license check **/
// $prefix_updater = new WP_Package_Updater(
// 'https://your-update-server.com',
// wp_normalize_path( __FILE__ ),
// wp_normalize_path( plugin_dir_path( __FILE__ ) ),
// false // Can be omitted, false by default
// );
/** Uncomment for theme updates **/
// require_once get_stylesheet_directory() . '/lib/wp-package-updater/class-wp-package-updater.php';
/** Enable theme updates with license check **/
// $prefix_updater = new WP_Package_Updater(
// 'https://your-update-server.com',
// wp_normalize_path( __FILE__ ),
// get_stylesheet_directory(),
// true
// );
/** Enable theme updates without license check **/
// $prefix_updater = new WP_Package_Updater(
// 'https://your-update-server.com',
// wp_normalize_path( __FILE__ ),
// get_stylesheet_directory(),
// false // Can be omitted, false by default
// );
/* ================================================================================================ */
if ( ! class_exists( 'WP_Package_Updater' ) ) {
class WP_Package_Updater {
const VERSION = '1.0.2';
private $license_server_url;
private $package_slug;
private $update_server_url;
private $package_path;
private $package_url;
private $update_checker;
private $type;
private $use_license;
public function __construct(
$update_server_url,
$package_file_path,
$package_path,
$use_license = false
) {
$this->package_path = trailingslashit( $package_path );
$this->set_type();
$package_path_parts = explode( '/', $package_path );
if ( 'Plugin' === $this->type ) {
$package_slug = $package_path_parts[ count( $package_path_parts ) - 2 ];
} elseif ( 'Theme' === $this->type ) {
$package_slug = $package_path_parts[ count( $package_path_parts ) - 1 ];
}
$package_file_path_parts = explode( '/', $package_file_path );
$package_id_parts = array_slice( $package_file_path_parts, -2, 2 );
$package_id = implode( '/', $package_id_parts );
$this->package_id = $package_id;
$this->update_server_url = trailingslashit( $update_server_url ) . 'wppus-update-api/';
$this->package_slug = $package_slug;
$this->use_license = $use_license;
if ( ! class_exists( 'Puc_v4_Factory' ) ) {
require $this->package_path . 'lib/plugin-update-checker/plugin-update-checker.php';
}
$metadata_url = trailingslashit( $this->update_server_url ) . '?action=get_metadata&package_id=';
$metadata_url .= rawurlencode( $this->package_slug );
$this->update_checker = Puc_v4_Factory::buildUpdateChecker( $metadata_url, $package_file_path );
$this->set_type();
if ( 'Plugin' === $this->type ) {
$this->package_url = plugin_dir_url( $package_file_path );
} elseif ( 'Theme' === $this->type ) {
$this->package_url = trailingslashit( get_theme_root_uri() ) . $package_slug;
}
$this->update_checker->addQueryArgFilter( array( $this, 'filter_update_checks' ) );
if ( $this->use_license ) {
$this->license_server_url = trailingslashit( $update_server_url ) . 'wppus-license-api/';
$this->update_checker->addResultFilter( array( $this, 'set_license_error_notice_content' ) );
if ( 'Plugin' === $this->type ) {
add_action( 'after_plugin_row_' . $this->package_id, array( $this, 'print_license_under_plugin' ), 10, 3 );
} elseif ( 'Theme' === $this->type ) {
add_action( 'admin_menu', array( $this, 'setup_theme_admin_menus' ), 10, 0 );
add_filter( 'custom_menu_order', array( $this, 'alter_admin_appearence_submenu_order' ), 10, 1 );
}
add_action( 'wp_ajax_wppu_' . $this->package_id . '_activate_license', array( $this, 'activate_license' ), 10, 0 );
add_action( 'wp_ajax_wppu_' . $this->package_id . '_deactivate_license', array( $this, 'deactivate_license' ), 10, 0 );
add_action( 'admin_enqueue_scripts', array( $this, 'add_admin_scripts' ), 99, 1 );
add_action( 'admin_notices', array( $this, 'show_license_error_notice' ), 10, 0 );
add_action( 'init', array( $this, 'load_textdomain' ), 10, 0 );
}
}
public function load_textdomain() {
$i10n_path = trailingslashit( basename( $this->package_path ) ) . 'lib/wp-update-migrate/languages';
if ( 'Plugin' === $this->type ) {
load_plugin_textdomain( 'wp-package-updater', false, $i10n_path );
} else {
load_theme_textdomain( 'wp-update-migrate', $i10n_path );
}
}
public function setup_theme_admin_menus() {
add_submenu_page(
'themes.php',
'Theme License',
'Theme License',
'manage_options',
'theme-license',
array( $this, 'theme_license_settings' )
);
}
public function alter_admin_appearence_submenu_order( $menu_ord ) {
global $submenu;
$theme_menu = $submenu['themes.php'];
$reordered_menu = array();
$first_key = 0;
$license_menu = null;
foreach ( $theme_menu as $key => $menu ) {
if ( 'themes.php' === $menu[2] ) {
$reordered_menu[ $key ] = $menu;
$first_key = $key;
} elseif ( 'theme-license' === $menu[2] ) {
$license_menu = $menu;
} else {
$reordered_menu[ $key + 1 ] = $menu;
}
}
$reordered_menu[ $first_key + 1 ] = $license_menu;
ksort( $reordered_menu );
$submenu['themes.php'] = $reordered_menu; // @codingStandardsIgnoreLine
return $menu_ord;
}
public function theme_license_settings() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'Sorry, you are not allowed to access this page.' ) ); // @codingStandardsIgnoreLine
}
$this->print_license_form_theme_page();
}
public function add_admin_scripts( $hook ) {
$debug = (bool) ( constant( 'WP_DEBUG' ) );
$condition = 'plugins.php' === $hook;
$condition = $condition || 'appearance_page_theme-license' === $hook;
$condition = $condition || 'appearance_page_parent-theme-license' === $hook;
$condition = $condition && ! wp_script_is( 'wp-package-updater-script' );
if ( $condition ) {
$js_ext = ( $debug ) ? '.js' : '.min.js';
$ver_js = filemtime( $this->package_path . 'lib/wp-package-updater/js/main' . $js_ext );
$params = array(
'action_prefix' => 'wppu_' . $this->package_id,
'ajax_url' => admin_url( 'admin-ajax.php' ),
);
wp_enqueue_script( 'wp-package-updater-script', $this->package_url . '/lib/wp-package-updater/js/main' . $js_ext, array( 'jquery' ), $ver_js, true );
wp_localize_script( 'wp-package-updater-script', 'WP_PackageUpdater', $params );
}
}
public function filter_update_checks( $query_args ) {
if ( $this->use_license ) {
$license = get_option( 'license_key_' . $this->package_slug );
$license_signature = get_option( 'license_signature_' . $this->package_slug );
if ( $license ) {
$query_args['update_license_key'] = rawurlencode( $license );
$query_args['update_license_signature'] = rawurlencode( $license_signature );
}
}
$query_args['update_type'] = $this->type;
return $query_args;
}
public function print_license_form_theme_page() {
$theme = wp_get_theme();
$title = __( 'Theme License - ', 'wp-package-updater' ) . $theme->get( 'Name' );
$form = $this->get_license_form();
ob_start();
require_once $this->package_path . 'lib/wp-package-updater/templates/theme-page-license.php';
echo ob_get_clean(); // @codingStandardsIgnoreLine
}
public function print_license_under_plugin( $plugin_file = null, $plugin_data = null, $status = null ) {
$form = $this->get_license_form();
ob_start();
require_once $this->package_path . 'lib/wp-package-updater/templates/plugin-page-license-row.php';
echo ob_get_clean(); // @codingStandardsIgnoreLine
}
public function activate_license() {
$license_data = $this->do_query_license( 'activate' );
if ( isset( $license_data->package_slug, $license_data->license_key ) ) {
update_option( 'license_key_' . $license_data->package_slug, $license_data->license_key );
if ( isset( $license_data->license_signature ) ) {
update_option( 'license_signature_' . $license_data->package_slug, $license_data->license_signature );
} else {
delete_option( 'license_signature_' . $license_data->package_slug );
}
} else {
$error = new WP_Error( 'License', $license_data->message );
if ( $license_data->clear_key ) {
delete_option( 'license_signature_' . $this->package_slug );
delete_option( 'license_key_' . $this->package_slug );
}
wp_send_json_error( $error );
}
// @todo remove in 2.0
if ( 'Theme' === $this->type ) {
delete_option( 'license_signature_' . $license_data->package_slug . '/functions.php' );
delete_option( 'license_key_' . $license_data->package_slug . '/functions.php' );
} else {
delete_option( 'license_signature_' . $license_data->package_slug . '/' . $license_data->package_slug . '.php' );
delete_option( 'license_key_' . $license_data->package_slug . '/' . $license_data->package_slug . '.php' );
}
delete_option( 'wppu_' . $this->package_slug . '_license_error' );
wp_send_json_success( $license_data );
}
public function deactivate_license() {
$license_data = $this->do_query_license( 'deactivate' );
if ( isset( $license_data->package_slug, $license_data->license_key ) ) {
update_option( 'license_key_' . $license_data->package_slug, '' );
if ( isset( $license_data->license_signature ) ) {
update_option( 'license_signature_' . $license_data->package_slug, '' );
} else {
delete_option( 'license_signature_' . $license_data->package_slug );
}
} else {
$error = new WP_Error( 'License', $license_data->message );
if ( $license_data->clear_key ) {
delete_option( 'license_signature_' . $this->package_slug );
delete_option( 'license_key_' . $this->package_slug );
}
wp_send_json_error( $error );
}
// @todo remove in 2.0
if ( 'Theme' === $this->type ) {
delete_option( 'license_signature_' . $license_data->package_slug . '/functions.php' );
delete_option( 'license_key_' . $license_data->package_slug . '/functions.php' );
} else {
delete_option( 'license_signature_' . $license_data->package_slug . '/' . $license_data->package_slug . '.php' );
delete_option( 'license_key_' . $license_data->package_slug . '/' . $license_data->package_slug . '.php' );
}
wp_send_json_success( $license_data );
}
public function set_license_error_notice_content( $package_info, $result ) {
if ( isset( $package_info->license_error ) && ! empty( $package_info->license_error ) ) {
$license_data = $this->handle_license_errors( $package_info->license_error );
update_option( 'wppu_' . $this->package_slug . '_license_error', $package_info->name . ': ' . $license_data->message );
} else {
delete_option( 'wppu_' . $this->package_slug . '_license_error' );
}
return $package_info;
}
public function show_license_error_notice() {
$error = get_option( 'wppu_' . $this->package_slug . '_license_error' );
if ( $error ) {
$class = 'license-error-' . $this->package_slug . ' notice notice-error is-dismissible';
printf( '<div class="%1$s"><p>%2$s</p></div>', $class, $error ); // @codingStandardsIgnoreLine
}
}
protected function do_query_license( $query_type ) {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], 'license_nonce' ) ) {
$error = new WP_Error( 'License', 'Unauthorised access.' );
wp_send_json_error( $error );
}
$license_key = $_REQUEST['license_key'];
$this->package_slug = $_REQUEST['package_slug'];
if ( empty( $license_key ) ) {
$error = new WP_Error( 'License', 'A license key is required.' );
wp_send_json_error( $error );
}
$api_params = array(
'action' => $query_type,
'license_key' => $license_key,
'allowed_domains' => $_SERVER['SERVER_NAME'],
'package_slug' => rawurlencode( $this->package_slug ),
);
$query = esc_url_raw( add_query_arg( $api_params, $this->license_server_url ) );
$response = wp_remote_get( $query, array(
'timeout' => 20,
'sslverify' => true,
) );
if ( is_wp_error( $response ) ) {
$license_data = new stdClass();
$license_data->clear_key = true;
$license_data->message = $response->get_error_message();
return $license_data;
}
$license_data = json_decode( wp_remote_retrieve_body( $response ) );
if ( JSON_ERROR_NONE !== json_last_error() ) {
$license_data = new stdClass();
$license_data->message = __( 'Unexpected Error! The query to retrieve the license data returned a malformed response.', 'wp-package-updater' );
return $license_data;
}
if ( ! isset( $license_data->id ) ) {
$license_data = $this->handle_license_errors( $license_data, $query_type );
}
return $license_data;
}
protected function handle_license_errors( $license_data, $query_type = null ) {
$license_data->clear_key = false;
if ( 'activate' === $query_type ) {
if ( isset( $license_data->allowed_domains ) ) {
$license_data->message = __( 'The license is already in use for this domain.', 'wp-package-updater' );
} elseif ( isset( $license_data->max_allowed_domains ) ) {
$license_data->clear_key = true;
$license_data->message = __( 'The license has reached the maximum number of activations and cannot be activated for this domain.', 'wp-package-updater' );
}
} elseif ( 'deactivate' === $query_type ) {
if ( isset( $license_data->allowed_domains ) ) {
$license_data->clear_key = true;
$license_data->message = __( 'The license is already inactive for this domain.', 'wp-package-updater' );
}
}
if (
isset( $license_data->status ) &&
'expired' === $license_data->status
) {
if ( isset( $license_data->date_expiry ) ) {
$license_data->message = sprintf(
// translators: the license expiry date
__( 'The license expired on %s and needs to be renewed to be updated.', 'wp-package-updater' ),
date_i18n( get_option( 'date_format' ), $license_data->date_expiry )
);
} else {
$license_data->message = __( 'The license expired and needs to be renewed to be updated.', 'wp-package-updater' );
}
} elseif (
isset( $license_data->status ) &&
'blocked' === $license_data->status
) {
$license_data->message = __( 'The license is blocked and cannot be updated anymore. Please use another license key.', 'wp-package-updater' );
} elseif (
isset( $license_data->status ) &&
'pending' === $license_data->status
) {
$license_data->clear_key = true;
$license_data->message = __( 'The license has not been activated and its status is stil pending. Please try again or use another license key.', 'wp-package-updater' );
} elseif (
isset( $license_data->status ) &&
'invalid' === $license_data->status
) {
$license_data->clear_key = true;
$license_data->message = __( 'The provided license key is invalid. Please use another license key.', 'wp-package-updater' );
} elseif ( isset( $license_data->license_key ) ) {
$license_data->clear_key = true;
$license_data->message = __( 'The provided license key does not appear to be valid. Please use another license key.', 'wp-package-updater' );
} elseif ( 1 === count( (array) $license_data ) ) {
if ( 'Plugin' === $this->type ) {
$license_data->message = __( 'An active license is required to update the plugin. Please provide a valid license key in Plugins > Installed Plugins.', 'wp-package-updater' );
} else {
$license_data->message = __( 'An active license is required to update the theme. Please provide a valid license key in Appearence > Theme License.', 'wp-package-updater' );
}
} elseif ( ! isset( $license_data->message ) || empty( $license_data->message ) ) {
$license_data->clear_key = true;
if ( 'Plugin' === $this->type ) {
$license_data->message = __( 'An unexpected error has occured. Please try again. If the problem persists, please contact the author of the plugin.', 'wp-package-updater' );
} else {
$license_data->message = __( 'An unexpected error has occured. Please try again. If the problem persists, please contact the author of the theme.', 'wp-package-updater' );
}
}
return $license_data;
}
protected function get_license_form() {
// @todo remove in 2.0
if ( get_option( 'license_key_' . $this->package_id ) ) {
update_option( 'license_key_' . $this->package_slug, get_option( 'license_key_' . $this->package_id ), true );
delete_option( 'license_key_' . $this->package_id );
}
$license = get_option( 'license_key_' . $this->package_slug );
$package_id = $this->package_id;
$package_slug = $this->package_slug;
$show_license = ( ! empty( $license ) );
ob_start();
require_once $this->package_path . 'lib/wp-package-updater/templates/license-form.php';
return ob_get_clean();
}
protected static function is_plugin_file( $absolute_path ) {
$plugin_dir = wp_normalize_path( WP_PLUGIN_DIR );
$mu_plugin_dir = wp_normalize_path( WPMU_PLUGIN_DIR );
if ( ( 0 === strpos( $absolute_path, $plugin_dir ) ) || ( 0 === strpos( $absolute_path, $mu_plugin_dir ) ) ) {
return true;
}
if ( ! is_file( $absolute_path ) ) {
return false;
}
if ( function_exists( 'get_file_data' ) ) {
$headers = get_file_data( $absolute_path, array( 'Name' => 'Plugin Name' ), 'plugin' );
return ! empty( $headers['Name'] );
}
return false;
}
protected static function get_theme_directory_name( $absolute_path ) {
if ( is_file( $absolute_path ) ) {
$absolute_path = dirname( $absolute_path );
}
if ( file_exists( $absolute_path . '/style.css' ) ) {
return basename( $absolute_path );
}
return null;
}
protected function set_type() {
$theme_directory = self::get_theme_directory_name( $this->package_path );
if ( self::is_plugin_file( $this->package_path ) ) {
$this->type = 'Plugin';
} elseif ( null !== $theme_directory ) {
$this->type = 'Theme';
} else {
throw new RuntimeException(
sprintf(
'The package updater cannot determine if "%s" is a plugin or a theme. ',
htmlentities( $this->package_path )
)
);
}
}
}
}

View File

@@ -1,92 +0,0 @@
/* version 1.4.0 */
/* global WP_PackageUpdater */
jQuery(document).ready(function($) {
var labelTheme = $('.appearance_page_theme-license .wrap-license label');
labelTheme.css('display', 'block');
labelTheme.css('margin-bottom', '10px');
$('.appearance_page_theme-license .wrap-license input[type="text"]').css('width', '50%');
$('.appearance_page_theme-license .postbox').show();
$('.wrap-license .activate-license').on('click', function(e) {
e.preventDefault();
var licenseContainer = $(this).parent().parent(),
data = {
'nonce' : licenseContainer.data('nonce'),
'license_key' : licenseContainer.find('.license').val(),
'package_slug' : licenseContainer.data('package_slug'),
'action' : WP_PackageUpdater.action_prefix + '_activate_license'
};
$.ajax({
url: WP_PackageUpdater.ajax_url,
data: data,
type: 'POST',
success: function(response) {
if (response.success) {
licenseContainer.find('.current-license').html(licenseContainer.find('.license').val());
licenseContainer.find('.current-license-error').hide();
licenseContainer.find('.license-message').show();
$( '.license-error-' + licenseContainer.data('package_slug') + '.notice' ).hide();
} else {
var errorContainer = licenseContainer.find('.current-license-error');
errorContainer.html(response.data[0].message + '<br/>');
errorContainer.show();
licenseContainer.find('.license-message').show();
}
if ('' === licenseContainer.find('.current-license').html()) {
licenseContainer.find('.current-license-label').hide();
licenseContainer.find('.current-license').hide();
} else {
licenseContainer.find('.current-license-label').show();
licenseContainer.find('.current-license').show();
}
}
});
});
$('.wrap-license .deactivate-license').on('click', function(e) {
e.preventDefault();
var licenseContainer = $(this).parent().parent(),
data = {
'nonce' : licenseContainer.data('nonce'),
'license_key' : licenseContainer.find('.license').val(),
'package_slug' : licenseContainer.data('package_slug'),
'action' : WP_PackageUpdater.action_prefix + '_deactivate_license'
};
$.ajax({
url: WP_PackageUpdater.ajax_url,
data: data,
type: 'POST',
success: function(response) {
if (response.success) {
licenseContainer.find('.current-license').html('');
licenseContainer.find('.current-license-error').hide();
licenseContainer.find('.license-message').hide();
} else {
var errorContainer = licenseContainer.find('.current-license-error');
errorContainer.html(response.data[0].message + '<br/>');
errorContainer.show();
licenseContainer.find('.license-message').show();
}
if ('' === licenseContainer.find('.current-license').html()) {
licenseContainer.find('.current-license-label').hide();
licenseContainer.find('.current-license').hide();
} else {
licenseContainer.find('.current-license-label').show();
licenseContainer.find('.current-license').show();
}
}
});
});
});

View File

@@ -1 +0,0 @@
jQuery(document).ready(function(c){var e=c(".appearance_page_theme-license .wrap-license label");e.css("display","block"),e.css("margin-bottom","10px"),c('.appearance_page_theme-license .wrap-license input[type="text"]').css("width","50%"),c(".appearance_page_theme-license .postbox").show(),c(".wrap-license .activate-license").on("click",function(e){e.preventDefault();var a=c(this).parent().parent(),n={nonce:a.data("nonce"),license_key:a.find(".license").val(),package_slug:a.data("package_slug"),action:WP_PackageUpdater.action_prefix+"_activate_license"};c.ajax({url:WP_PackageUpdater.ajax_url,data:n,type:"POST",success:function(e){if(e.success)a.find(".current-license").html(a.find(".license").val()),a.find(".current-license-error").hide(),a.find(".license-message").show(),c(".license-error-"+a.data("package_slug")+".notice").hide();else{var n=a.find(".current-license-error");n.html(e.data[0].message+"<br/>"),n.show(),a.find(".license-message").show()}""===a.find(".current-license").html()?(a.find(".current-license-label").hide(),a.find(".current-license").hide()):(a.find(".current-license-label").show(),a.find(".current-license").show())}})}),c(".wrap-license .deactivate-license").on("click",function(e){e.preventDefault();var a=c(this).parent().parent(),n={nonce:a.data("nonce"),license_key:a.find(".license").val(),package_slug:a.data("package_slug"),action:WP_PackageUpdater.action_prefix+"_deactivate_license"};c.ajax({url:WP_PackageUpdater.ajax_url,data:n,type:"POST",success:function(e){if(e.success)a.find(".current-license").html(""),a.find(".current-license-error").hide(),a.find(".license-message").hide();else{var n=a.find(".current-license-error");n.html(e.data[0].message+"<br/>"),n.show(),a.find(".license-message").show()}""===a.find(".current-license").html()?(a.find(".current-license-label").hide(),a.find(".current-license").hide()):(a.find(".current-license-label").show(),a.find(".current-license").show())}})})});

View File

@@ -1,13 +0,0 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
} ?>
<div class="wrap-license" data-package_slug="<?php echo esc_attr( $package_slug ); ?>" id="<?php echo esc_attr( 'wrap_license_' . $package_id ); ?>" data-nonce="<?php echo esc_attr( wp_create_nonce( 'license_nonce' ) ); ?>">
<p class="license-message<?php echo ( ! $show_license ) ? esc_attr( ' hidden' ) : ''; ?>" style="font-weight:bold;"><?php // @codingStandardsIgnoreLine ?>
<span class="current-license-error hidden"></span> <span class="current-license-label"><?php esc_html_e( 'Current license key:', 'wp-package-updater' ); ?></span> <span class="current-license"><?php echo esc_html( $license ); ?></span>
</p>
<p>
<label style="vertical-align: initial;"><?php esc_html_e( 'License key to change:', 'wp-package-updater' ); ?></label> <input class="regular-text license" type="text" id="<?php echo esc_attr( 'license_key_' . $package_id ); ?>" value="" >
<input type="button" value="Activate" class="button-primary activate-license" />
<input type="button" value="Deactivate" class="button deactivate-license" />
</p>
</div>

View File

@@ -1,10 +0,0 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
} ?>
<tr class="plugin-update-tr active installer-plugin-update-tr">
<td colspan="3" class="plugin-update colspanchange">
<div class="notice inline notice-warning notice-alt">
<?php echo $form; ?><?php // @codingStandardsIgnoreLine ?>
</div>
</td>
</tr>

View File

@@ -1,11 +0,0 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
} ?>
<div class="wrap">
<div class="postbox hidden" style="min-width: 500px; position: absolute; top: 150px; left: 50%; transform: translate(-50%, 0);">
<div class="inside" style="margin: 50px;">
<h2><?php echo esc_html( $title ); ?></h2>
<?php echo $form; ?><?php // @codingStandardsIgnoreLine ?>
</div>
</div>
</div>

View File

@@ -3,7 +3,7 @@
Plugin Name: OgreAlert
Plugin URI: https://plugins.cleverogre.com/plugin/ogrealert/
Description: OgreAlert is a plugin developed by CleverOgre in Pensacola, Florida.
Version: 0.1.8
Version: 0.2.0
Author: CleverOgre
Author URI: https://cleverogre.com/
Icon1x: https://plugins.cleverogre.com/plugin/ogrealert/?asset=icon-sm
@@ -45,20 +45,20 @@ class Plugin {
// Default Settings
\OgreAlert\Settings::set('name', 'OgreAlert');
\OgreAlert\Settings::set('version', '0.1.8');
\OgreAlert\Settings::set('version', '0.2.0');
\OgreAlert\Settings::set('capability', 'edit_posts');
\OgreAlert\Settings::set('path', $path);
\OgreAlert\Settings::set('dir', self::get_dir(__FILE__));
\OgreAlert\Settings::set('hook', self::get_hook(__FILE__));
// Setup Plugin Updates
include_once(\OgreAlert\Settings::get('path') . 'lib/wp-package-updater/class-wp-package-updater.php'); // Include private plugin updating library
$package_updater = new \WP_Package_Updater(
'https://plugins.cleverogre.com',
wp_normalize_path(__FILE__),
wp_normalize_path(plugin_dir_path(__FILE__)),
false // License key not necessary
);
global $wppul_server, $wppul_license_required, $wppul_plugin_file;
$wppul_server = 'https://plugins.cleverogre.com';
$wppul_license_required = false;
$wppul_plugin_file = __FILE__;
$dir = trailingslashit(dirname(__FILE__));
require_once($dir . 'lib/wp-package-updater-lib/plugin-update-checker/plugin-update-checker.php');
require_once($dir . 'lib/wp-package-updater-lib/package-updater.php');
// Set Text Domain
load_plugin_textdomain('ogrealert', false, plugin_basename(dirname(__FILE__)) . '/lang');

View File

@@ -4,7 +4,7 @@ Donate link: https://cleverogre.com/
Tags: development, warning, modal, dismissable
Requires at least: 4.8.0
Tested up to: 5.7.1
Stable tag: 0.1.8
Stable tag: 0.2.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
@@ -62,6 +62,14 @@ By default, the OgreAlert plugin will be able to update without an activated lic
== Changelog ==
= 0.2.0 - 07-22-2025 =
* DEV: Updated plugin updater libraries.
= 0.1.9 - 05-24-2021 =
* NEW: Z-index field in OgreAlert settings.
* BUG: Replaced wp_make_content_images_responsive filter with wp_filter_content_tags for WP 5.5.0 compatibility.
* BUG: Renamed display.js to frontend.js to prevent ad blockers.
= 0.1.8 - 05-12-2021 =
* DEV: Moved FontAwesome webfonts to separated folder in assets.
* DEV: Added plugin packaging makefile.

View File

@@ -7,6 +7,9 @@
if (!defined('ABSPATH')) exit;
$index = \OgreAlert\Settings::get('message_index');
if (!is_numeric($index)) $index = 10001;
?>
<section class="ogrealert-messages ogrealert-position-<?php esc_attr_e(\OgreAlert\Settings::get('message_position')); ?>">
<section class="ogrealert-messages ogrealert-position-<?php esc_attr_e(\OgreAlert\Settings::get('message_position')); ?>" style="--messages-index: <?php echo intval($index); ?>">
<ul class="ogrealert-messages__list">