@@ -282,9 +420,6 @@ public function new_invoice_form() {
@@ -311,36 +449,34 @@ public function new_invoice_form() {
* @return void
*/
public function form_submit_handle() {
- echo 'hello world!';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['nonce'] && wp_verify_nonce($_POST['nonce'], 'lkn_wcip_add_invoice')) {
- echo 'nonce found ' . var_export($_POST, true);
$invoices = [];
- $products = [];
$totalAmount = 0;
$c = 0;
foreach ($_POST as $key => $value) {
// Get invoice description
if (preg_match('/lkn_wcip_name_invoice_/i', $key)) {
- $invoices[$c]['desc'] = $value;
+ $invoices[$c]['desc'] = strip_tags($value);
}
// Get invoice amount
if (preg_match('/lkn_wcip_amount_invoice_/i', $key)) {
// Save amount and description in same index because they are related
- $invoices[$c]['amount'] = $value;
- $totalAmount += $value;
+ $invoices[$c]['amount'] = number_format($value, 2, '.', '');
+ $totalAmount += number_format($value, 2, '.', '');
// Only increment when amount is found
$c++;
}
}
- // TODO review order metadata to store these attributes
- $paymentStatus = $_POST['lkn_wcip_payment_status'];
- $paymentMethod = $_POST['lkn_wcip_default_payment_method'];
- $currency = $_POST['lkn_wcip_currency'];
- $name = $_POST['lkn_wcip_name'];
- $email = $_POST['lkn_wcip_email'];
- $dueDate = $_POST['lkn_wcip_due_date'];
+ $paymentStatus = sanitize_text_field($_POST['lkn_wcip_payment_status']);
+ $paymentMethod = sanitize_text_field($_POST['lkn_wcip_default_payment_method']);
+ $currency = sanitize_text_field($_POST['lkn_wcip_currency']);
+ $name = sanitize_text_field($_POST['lkn_wcip_name']);
+ $firstName = explode(' ', $name)[0];
+ $lastname = substr(strstr($name, ' '), 1);
+ $email = sanitize_email($_POST['lkn_wcip_email']);
+ $dueDate = preg_replace('/[^0-9\-]+/i', '', $_POST['lkn_wcip_due_date']);
/*
$username = sanitize_title( 'testusername-' . microtime( true ) . wp_generate_password( 6, false, false ) );
@@ -368,15 +504,32 @@ public function form_submit_handle() {
$product->set_name($invoices[$i]['desc']);
$product->set_regular_price($invoices[$i]['amount']);
$product->save();
- $product = wc_get_product($product->get_id());
+ $productId = wc_get_product($product->get_id());
- $order->add_product($product);
+ $order->add_product($productId);
+
+ $product->delete(true);
}
+ $order->set_billing_email($email);
+ $order->set_billing_first_name($firstName);
+ $order->set_billing_last_name($lastname);
+ $order->set_payment_method($paymentMethod);
+ $order->set_currency($currency);
+
$order->calculate_totals();
$order->save();
+ // $order->get_checkout_payment_url();
+ $orderId = $order->get_id();
- echo 'PEDIDO CRIADO: ' . var_export(json_encode($invoices), true);
+ $invoiceList = get_option('lkn_wcip_invoices');
+
+ if ($invoiceList !== false) {
+ $invoiceList[] = $orderId;
+ update_option('lkn_wcip_invoices', $invoiceList);
+ } else {
+ update_option('lkn_wcip_invoices', [$orderId]);
+ }
} else {
echo 'nonce not found ' . var_export($_POST, true);
}
diff --git a/admin/class-wc-invoice-payment-table.php b/admin/class-wc-invoice-payment-table.php
new file mode 100644
index 0000000..189f28f
--- /dev/null
+++ b/admin/class-wc-invoice-payment-table.php
@@ -0,0 +1,1541 @@
+get_column_info().
+ *
+ * @since 4.1.0
+ * @var array
+ */
+ protected $_column_headers;
+
+ /**
+ * {@internal Missing Summary}
+ *
+ * @var array
+ */
+ protected $compat_fields = ['_args', '_pagination_args', 'screen', '_actions', '_pagination'];
+
+ /**
+ * {@internal Missing Summary}
+ *
+ * @var array
+ */
+ protected $compat_methods = [
+ 'set_pagination_args',
+ 'get_views',
+ 'get_bulk_actions',
+ 'bulk_actions',
+ 'row_actions',
+ 'months_dropdown',
+ 'view_switcher',
+ 'comments_bubble',
+ 'get_items_per_page',
+ 'pagination',
+ 'get_sortable_columns',
+ 'get_column_info',
+ 'get_table_classes',
+ 'display_tablenav',
+ 'extra_tablenav',
+ 'single_row_columns',
+ ];
+
+ /**
+ * Constructor.
+ *
+ * The child class should call this constructor from its own constructor to override
+ * the default $args.
+ *
+ * @since 3.1.0
+ *
+ * @param array|string $args {
+ * Array or string of arguments.
+ *
+ * @type string $plural Plural value used for labels and the objects being listed.
+ * This affects things such as CSS class-names and nonces used
+ * in the list table, e.g. 'posts'. Default empty.
+ * @type string $singular Singular label for an object being listed, e.g. 'post'.
+ * Default empty
+ * @type bool $ajax Whether the list table supports Ajax. This includes loading
+ * and sorting data, for example. If true, the class will call
+ * the _js_vars() method in the footer to provide variables
+ * to any scripts handling Ajax events. Default false.
+ * @type string $screen String containing the hook name used to determine the current
+ * screen. If left null, the current screen will be automatically set.
+ * Default null.
+ * }
+ */
+ public function __construct($args = []) {
+ $args = wp_parse_args(
+ $args,
+ [
+ 'plural' => '',
+ 'singular' => '',
+ 'ajax' => false,
+ 'screen' => null,
+ ]
+ );
+
+ $this->screen = convert_to_screen($args['screen']);
+
+ add_filter("manage_{$this->screen->id}_columns", [$this, 'get_columns'], 0);
+
+ if (!$args['plural']) {
+ $args['plural'] = $this->screen->base;
+ }
+
+ $args['plural'] = sanitize_key($args['plural']);
+ $args['singular'] = sanitize_key($args['singular']);
+
+ $this->_args = $args;
+
+ if ($args['ajax']) {
+ // wp_enqueue_script( 'list-table' );
+ add_action('admin_footer', [$this, '_js_vars']);
+ }
+
+ if (empty($this->modes)) {
+ $this->modes = [
+ 'list' => __('Compact view'),
+ 'excerpt' => __('Extended view'),
+ ];
+ }
+ }
+
+ /**
+ * Make private properties readable for backward compatibility.
+ *
+ * @since 4.0.0
+ *
+ * @param string $name Property to get.
+ * @return mixed Property.
+ */
+ public function __get($name) {
+ if (in_array($name, $this->compat_fields, true)) {
+ return $this->$name;
+ }
+ }
+
+ /**
+ * Make private properties settable for backward compatibility.
+ *
+ * @since 4.0.0
+ *
+ * @param string $name Property to check if set.
+ * @param mixed $value Property value.
+ * @return mixed Newly-set property.
+ */
+ public function __set($name, $value) {
+ if (in_array($name, $this->compat_fields, true)) {
+ return $this->$name = $value;
+ }
+ }
+
+ /**
+ * Make private properties checkable for backward compatibility.
+ *
+ * @since 4.0.0
+ *
+ * @param string $name Property to check if set.
+ * @return bool Whether the property is a back-compat property and it is set.
+ */
+ public function __isset($name) {
+ if (in_array($name, $this->compat_fields, true)) {
+ return isset($this->$name);
+ }
+
+ return false;
+ }
+
+ /**
+ * Make private properties un-settable for backward compatibility.
+ *
+ * @since 4.0.0
+ *
+ * @param string $name Property to unset.
+ */
+ public function __unset($name) {
+ if (in_array($name, $this->compat_fields, true)) {
+ unset($this->$name);
+ }
+ }
+
+ /**
+ * Make private/protected methods readable for backward compatibility.
+ *
+ * @since 4.0.0
+ *
+ * @param string $name Method to call.
+ * @param array $arguments Arguments to pass when calling.
+ * @return mixed|bool Return value of the callback, false otherwise.
+ */
+ public function __call($name, $arguments) {
+ if (in_array($name, $this->compat_methods, true)) {
+ return $this->$name(...$arguments);
+ }
+
+ return false;
+ }
+
+ /**
+ * Checks the current user's permissions
+ *
+ * @since 3.1.0
+ * @abstract
+ */
+ public function ajax_user_can() {
+ die('function WP_List_Table::ajax_user_can() must be overridden in a subclass.');
+ }
+
+ /**
+ * An internal method that sets all the necessary pagination arguments
+ *
+ * @since 3.1.0
+ *
+ * @param array|string $args Array or string of arguments with information about the pagination.
+ */
+ protected function set_pagination_args($args) {
+ $args = wp_parse_args(
+ $args,
+ [
+ 'total_items' => 0,
+ 'total_pages' => 0,
+ 'per_page' => 0,
+ ]
+ );
+
+ if (!$args['total_pages'] && $args['per_page'] > 0) {
+ $args['total_pages'] = ceil($args['total_items'] / $args['per_page']);
+ }
+
+ // Redirect if page number is invalid and headers are not already sent.
+ if (!headers_sent() && !wp_doing_ajax() && $args['total_pages'] > 0 && $this->get_pagenum() > $args['total_pages']) {
+ wp_redirect(add_query_arg('paged', $args['total_pages']));
+ exit;
+ }
+
+ $this->_pagination_args = $args;
+ }
+
+ /**
+ * Access the pagination args.
+ *
+ * @since 3.1.0
+ *
+ * @param string $key Pagination argument to retrieve. Common values include 'total_items',
+ * 'total_pages', 'per_page', or 'infinite_scroll'.
+ * @return int Number of items that correspond to the given pagination argument.
+ */
+ public function get_pagination_arg($key) {
+ if ('page' === $key) {
+ return $this->get_pagenum();
+ }
+
+ if (isset($this->_pagination_args[$key])) {
+ return $this->_pagination_args[$key];
+ }
+
+ return 0;
+ }
+
+ /**
+ * Whether the table has items to display or not
+ *
+ * @since 3.1.0
+ *
+ * @return bool
+ */
+ public function has_items() {
+ return !empty($this->items);
+ }
+
+ /**
+ * Message to be displayed when there are no items
+ *
+ * @since 3.1.0
+ */
+ public function no_items() {
+ _e('No items found.');
+ }
+
+ /**
+ * Displays the search box.
+ *
+ * @since 3.1.0
+ *
+ * @param string $text The 'submit' button label.
+ * @param string $input_id ID attribute value for the search input field.
+ */
+ public function search_box($text, $input_id) {
+ if (empty($_REQUEST['s']) && !$this->has_items()) {
+ return;
+ }
+
+ $input_id = $input_id . '-search-input';
+
+ if (!empty($_REQUEST['orderby'])) {
+ echo '
';
+ }
+ if (!empty($_REQUEST['order'])) {
+ echo '
';
+ }
+ if (!empty($_REQUEST['post_mime_type'])) {
+ echo '
';
+ }
+ if (!empty($_REQUEST['detached'])) {
+ echo '
';
+ } ?>
+
+ :
+
+ 'search-submit']); ?>
+
+ 'link'`
+ *
+ * @since 3.1.0
+ *
+ * @return array
+ */
+ protected function get_views() {
+ return [];
+ }
+
+ /**
+ * Displays the list of views available on this table.
+ *
+ * @since 3.1.0
+ */
+ public function views() {
+ $views = $this->get_views();
+ /**
+ * Filters the list of available list table views.
+ *
+ * The dynamic portion of the hook name, `$this->screen->id`, refers
+ * to the ID of the current screen.
+ *
+ * @since 3.1.0
+ *
+ * @param string[] $views An array of available list table views.
+ */
+ $views = apply_filters("views_{$this->screen->id}", $views);
+
+ if (empty($views)) {
+ return;
+ }
+
+ $this->screen->render_screen_reader_content('heading_views');
+
+ echo "
\n";
+ foreach ($views as $class => $view) {
+ $views[$class] = "\t$view";
+ }
+ echo implode(" | \n", $views) . "\n";
+ echo ' ';
+ }
+
+ /**
+ * Displays the bulk actions dropdown.
+ *
+ * @since 3.1.0
+ *
+ * @param string $which The location of the bulk actions: 'top' or 'bottom'.
+ * This is designated as optional for backward compatibility.
+ */
+ protected function bulk_actions($which = '') {
+ if (is_null($this->_actions)) {
+ $this->_actions = $this->get_bulk_actions();
+
+ /**
+ * Filters the items in the bulk actions menu of the list table.
+ *
+ * The dynamic portion of the hook name, `$this->screen->id`, refers
+ * to the ID of the current screen.
+ *
+ * @since 3.1.0
+ * @since 5.6.0 A bulk action can now contain an array of options in order to create an optgroup.
+ *
+ * @param array $actions An array of the available bulk actions.
+ */
+ $this->_actions = apply_filters("bulk_actions-{$this->screen->id}", $this->_actions); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
+
+ $two = '';
+ } else {
+ $two = '2';
+ }
+
+ if (empty($this->_actions)) {
+ return;
+ }
+
+ echo '
' . __('Select bulk action') . ' ';
+ echo '
\n";
+ echo '' . __('Bulk actions') . " \n";
+
+ foreach ($this->_actions as $key => $value) {
+ if (is_array($value)) {
+ echo "\t" . '' . "\n";
+
+ foreach ($value as $name => $title) {
+ $class = ('edit' === $name) ? ' class="hide-if-no-js"' : '';
+
+ echo "\t\t" . '' . $title . " \n";
+ }
+ echo "\t" . " \n";
+ } else {
+ $class = ('edit' === $key) ? ' class="hide-if-no-js"' : '';
+
+ echo "\t" . '' . $value . " \n";
+ }
+ }
+
+ echo " \n";
+
+ submit_button(__('Apply'), 'action', '', false, ['id' => "doaction$two"]);
+ echo "\n";
+ }
+
+ /**
+ * Gets the current action selected from the bulk actions dropdown.
+ *
+ * @since 3.1.0
+ *
+ * @return string|false The action name. False if no action was selected.
+ */
+ public function current_action() {
+ if (isset($_REQUEST['filter_action']) && !empty($_REQUEST['filter_action'])) {
+ return false;
+ }
+
+ if (isset($_REQUEST['action']) && -1 != $_REQUEST['action']) {
+ return $_REQUEST['action'];
+ }
+
+ return false;
+ }
+
+ /**
+ * Generates the required HTML for a list of row action links.
+ *
+ * @since 3.1.0
+ *
+ * @param string[] $actions An array of action links.
+ * @param bool $always_visible Whether the actions should be always visible.
+ * @return string The HTML for the row actions.
+ */
+ protected function row_actions($actions, $always_visible = false) {
+ $action_count = count($actions);
+
+ if (!$action_count) {
+ return '';
+ }
+
+ $mode = get_user_setting('posts_list_mode', 'list');
+
+ if ('excerpt' === $mode) {
+ $always_visible = true;
+ }
+
+ $out = '
';
+
+ $i = 0;
+
+ foreach ($actions as $action => $link) {
+ ++$i;
+
+ $sep = ($i < $action_count) ? ' | ' : '';
+
+ $out .= "$link$sep ";
+ }
+
+ $out .= '
';
+
+ $out .= '
' . __('Show more details') . ' ';
+
+ return $out;
+ }
+
+ /**
+ * Displays a dropdown for filtering items in the list table by month.
+ *
+ * @since 3.1.0
+ *
+ * @global wpdb $wpdb WordPress database abstraction object.
+ * @global WP_Locale $wp_locale WordPress date and time locale object.
+ *
+ * @param string $post_type The post type.
+ */
+ protected function months_dropdown($post_type) {
+ global $wpdb, $wp_locale;
+
+ /**
+ * Filters whether to remove the 'Months' drop-down from the post list table.
+ *
+ * @since 4.2.0
+ *
+ * @param bool $disable Whether to disable the drop-down. Default false.
+ * @param string $post_type The post type.
+ */
+ if (apply_filters('disable_months_dropdown', false, $post_type)) {
+ return;
+ }
+
+ /**
+ * Filters to short-circuit performing the months dropdown query.
+ *
+ * @since 5.7.0
+ *
+ * @param object[]|false $months 'Months' drop-down results. Default false.
+ * @param string $post_type The post type.
+ */
+ $months = apply_filters('pre_months_dropdown_query', false, $post_type);
+
+ if (!is_array($months)) {
+ $extra_checks = "AND post_status != 'auto-draft'";
+ if (!isset($_GET['post_status']) || 'trash' !== $_GET['post_status']) {
+ $extra_checks .= " AND post_status != 'trash'";
+ } elseif (isset($_GET['post_status'])) {
+ $extra_checks = $wpdb->prepare(' AND post_status = %s', $_GET['post_status']);
+ }
+
+ $months = $wpdb->get_results(
+ $wpdb->prepare(
+ "
+ SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
+ FROM $wpdb->posts
+ WHERE post_type = %s
+ $extra_checks
+ ORDER BY post_date DESC
+ ",
+ $post_type
+ )
+ );
+ }
+
+ /**
+ * Filters the 'Months' drop-down results.
+ *
+ * @since 3.7.0
+ *
+ * @param object[] $months Array of the months drop-down query results.
+ * @param string $post_type The post type.
+ */
+ $months = apply_filters('months_dropdown_results', $months, $post_type);
+
+ $month_count = count($months);
+
+ if (!$month_count || (1 == $month_count && 0 == $months[0]->month)) {
+ return;
+ }
+
+ $m = isset($_GET['m']) ? (int) $_GET['m'] : 0; ?>
+
labels->filter_by_date; ?>
+
+ value="0">
+ year) {
+ continue;
+ }
+
+ $month = zeroise($arc_row->month, 2);
+ $year = $arc_row->year;
+
+ printf(
+ "%s \n",
+ selected($m, $year . $month, false),
+ esc_attr($arc_row->year . $month),
+ /* translators: 1: Month name, 2: 4-digit year. */
+ sprintf(__('%1$s %2$d'), $wp_locale->get_month($month), $year)
+ );
+ } ?>
+
+
+
+
+ modes as $mode => $title) {
+ $classes = ['view-' . $mode];
+ $aria_current = '';
+
+ if ($current_mode === $mode) {
+ $classes[] = 'current';
+ $aria_current = ' aria-current="page"';
+ }
+
+ printf(
+ "
%s \n",
+ esc_url(remove_query_arg('attachment-filter', add_query_arg('mode', $mode))),
+ implode(' ', $classes),
+ $title
+ );
+ } ?>
+
+ —
%s ',
+ __('No comments')
+ );
+ } elseif ($approved_comments && 'trash' === get_post_status($post_id)) {
+ // Don't link the comment bubble for a trashed post.
+ printf(
+ '
%s ',
+ $approved_comments_number,
+ $pending_comments ? $approved_phrase : $approved_only_phrase
+ );
+ } elseif ($approved_comments) {
+ // Link the comment bubble to approved comments.
+ printf(
+ '
%s ',
+ esc_url(
+ add_query_arg(
+ [
+ 'p' => $post_id,
+ 'comment_status' => 'approved',
+ ],
+ admin_url('edit-comments.php')
+ )
+ ),
+ $approved_comments_number,
+ $pending_comments ? $approved_phrase : $approved_only_phrase
+ );
+ } else {
+ // Don't link the comment bubble when there are no approved comments.
+ printf(
+ '',
+ $approved_comments_number,
+ $pending_comments ? __('No approved comments') : __('No comments')
+ );
+ }
+
+ if ($pending_comments) {
+ printf(
+ '
%s ',
+ esc_url(
+ add_query_arg(
+ [
+ 'p' => $post_id,
+ 'comment_status' => 'moderated',
+ ],
+ admin_url('edit-comments.php')
+ )
+ ),
+ $pending_comments_number,
+ $pending_phrase
+ );
+ } else {
+ printf(
+ '
%s ',
+ $pending_comments_number,
+ $approved_comments ? __('No pending comments') : __('No comments')
+ );
+ }
+ }
+
+ /**
+ * Gets the current page number.
+ *
+ * @since 3.1.0
+ *
+ * @return int
+ */
+ public function get_pagenum() {
+ $pagenum = isset($_REQUEST['paged']) ? absint($_REQUEST['paged']) : 0;
+
+ if (isset($this->_pagination_args['total_pages']) && $pagenum > $this->_pagination_args['total_pages']) {
+ $pagenum = $this->_pagination_args['total_pages'];
+ }
+
+ return max(1, $pagenum);
+ }
+
+ /**
+ * Gets the number of items to display on a single page.
+ *
+ * @since 3.1.0
+ *
+ * @param string $option
+ * @param int $default
+ * @return int
+ */
+ protected function get_items_per_page($option, $default = 20) {
+ $per_page = (int) get_user_option($option);
+ if (empty($per_page) || $per_page < 1) {
+ $per_page = $default;
+ }
+
+ /**
+ * Filters the number of items to be displayed on each page of the list table.
+ *
+ * The dynamic hook name, `$option`, refers to the `per_page` option depending
+ * on the type of list table in use. Possible filter names include:
+ *
+ * - `edit_comments_per_page`
+ * - `sites_network_per_page`
+ * - `site_themes_network_per_page`
+ * - `themes_network_per_page'`
+ * - `users_network_per_page`
+ * - `edit_post_per_page`
+ * - `edit_page_per_page'`
+ * - `edit_{$post_type}_per_page`
+ * - `edit_post_tag_per_page`
+ * - `edit_category_per_page`
+ * - `edit_{$taxonomy}_per_page`
+ * - `site_users_network_per_page`
+ * - `users_per_page`
+ *
+ * @since 2.9.0
+ *
+ * @param int $per_page Number of items to be displayed. Default 20.
+ */
+ return (int) apply_filters("{$option}", $per_page);
+ }
+
+ /**
+ * Displays the pagination.
+ *
+ * @since 3.1.0
+ *
+ * @param string $which
+ */
+ protected function pagination($which) {
+ if (empty($this->_pagination_args)) {
+ return;
+ }
+
+ $total_items = $this->_pagination_args['total_items'];
+ $total_pages = $this->_pagination_args['total_pages'];
+ $infinite_scroll = false;
+ if (isset($this->_pagination_args['infinite_scroll'])) {
+ $infinite_scroll = $this->_pagination_args['infinite_scroll'];
+ }
+
+ if ('top' === $which && $total_pages > 1) {
+ $this->screen->render_screen_reader_content('heading_pagination');
+ }
+
+ $output = '
' . sprintf(
+ /* translators: %s: Number of items. */
+ _n('%s item', '%s items', $total_items),
+ number_format_i18n($total_items)
+ ) . ' ';
+
+ $current = $this->get_pagenum();
+ $removable_query_args = wp_removable_query_args();
+
+ $current_url = set_url_scheme('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
+
+ $current_url = remove_query_arg($removable_query_args, $current_url);
+
+ $page_links = [];
+
+ $total_pages_before = '
';
+ $total_pages_after = ' ';
+
+ $disable_first = false;
+ $disable_last = false;
+ $disable_prev = false;
+ $disable_next = false;
+
+ if (1 == $current) {
+ $disable_first = true;
+ $disable_prev = true;
+ }
+ if ($total_pages == $current) {
+ $disable_last = true;
+ $disable_next = true;
+ }
+
+ if ($disable_first) {
+ $page_links[] = '
« ';
+ } else {
+ $page_links[] = sprintf(
+ "
%s %s ",
+ esc_url(remove_query_arg('paged', $current_url)),
+ __('First page'),
+ '«'
+ );
+ }
+
+ if ($disable_prev) {
+ $page_links[] = '
‹ ';
+ } else {
+ $page_links[] = sprintf(
+ "
%s %s ",
+ esc_url(add_query_arg('paged', max(1, $current - 1), $current_url)),
+ __('Previous page'),
+ '‹'
+ );
+ }
+
+ if ('bottom' === $which) {
+ $html_current_page = $current;
+ $total_pages_before = '
' . __('Current Page') . ' ';
+ } else {
+ $html_current_page = sprintf(
+ "%s",
+ '' . __('Current Page') . ' ',
+ $current,
+ strlen($total_pages)
+ );
+ }
+ $html_total_pages = sprintf("%s ", number_format_i18n($total_pages));
+ $page_links[] = $total_pages_before . sprintf(
+ /* translators: 1: Current page, 2: Total pages. */
+ _x('%1$s of %2$s', 'paging'),
+ $html_current_page,
+ $html_total_pages
+ ) . $total_pages_after;
+
+ if ($disable_next) {
+ $page_links[] = '› ';
+ } else {
+ $page_links[] = sprintf(
+ "%s %s ",
+ esc_url(add_query_arg('paged', min($total_pages, $current + 1), $current_url)),
+ __('Next page'),
+ '›'
+ );
+ }
+
+ if ($disable_last) {
+ $page_links[] = '» ';
+ } else {
+ $page_links[] = sprintf(
+ "%s %s ",
+ esc_url(add_query_arg('paged', $total_pages, $current_url)),
+ __('Last page'),
+ '»'
+ );
+ }
+
+ $pagination_links_class = 'pagination-links';
+ if (!empty($infinite_scroll)) {
+ $pagination_links_class .= ' hide-if-js';
+ }
+ $output .= "\n';
+
+ if ($total_pages) {
+ $page_class = $total_pages < 2 ? ' one-page' : '';
+ } else {
+ $page_class = ' no-pages';
+ }
+ $this->_pagination = "$output
";
+
+ echo $this->_pagination;
+ }
+
+ /**
+ * Gets a list of sortable columns.
+ *
+ * The format is:
+ * - `'internal-name' => 'orderby'`
+ * - `'internal-name' => array( 'orderby', 'asc' )` - The second element sets the initial sorting order.
+ * - `'internal-name' => array( 'orderby', true )` - The second element makes the initial order descending.
+ *
+ * @since 3.1.0
+ *
+ * @return array
+ */
+ protected function get_sortable_columns() {
+ return [];
+ }
+
+ /**
+ * Gets the name of the default primary column.
+ *
+ * @since 4.3.0
+ *
+ * @return string Name of the default primary column, in this case, an empty string.
+ */
+ protected function get_default_primary_column_name() {
+ $columns = $this->get_columns();
+ $column = '';
+
+ if (empty($columns)) {
+ return $column;
+ }
+
+ // We need a primary defined so responsive views show something,
+ // so let's fall back to the first non-checkbox column.
+ foreach ($columns as $col => $column_name) {
+ if ('cb' === $col) {
+ continue;
+ }
+
+ $column = $col;
+
+ break;
+ }
+
+ return $column;
+ }
+
+ /**
+ * Public wrapper for WP_List_Table::get_default_primary_column_name().
+ *
+ * @since 4.4.0
+ *
+ * @return string Name of the default primary column.
+ */
+ public function get_primary_column() {
+ return $this->get_primary_column_name();
+ }
+
+ /**
+ * Gets the name of the primary column.
+ *
+ * @since 4.3.0
+ *
+ * @return string The name of the primary column.
+ */
+ protected function get_primary_column_name() {
+ $columns = get_column_headers($this->screen);
+ $default = $this->get_default_primary_column_name();
+
+ // If the primary column doesn't exist,
+ // fall back to the first non-checkbox column.
+ if (!isset($columns[$default])) {
+ $default = self::get_default_primary_column_name();
+ }
+
+ /**
+ * Filters the name of the primary column for the current list table.
+ *
+ * @since 4.3.0
+ *
+ * @param string $default Column name default for the specific list table, e.g. 'name'.
+ * @param string $context Screen ID for specific list table, e.g. 'plugins'.
+ */
+ $column = apply_filters('list_table_primary_column', $default, $this->screen->id);
+
+ if (empty($column) || !isset($columns[$column])) {
+ $column = $default;
+ }
+
+ return $column;
+ }
+
+ /**
+ * Gets a list of all, hidden, and sortable columns, with filter applied.
+ *
+ * @since 3.1.0
+ *
+ * @return array
+ */
+ protected function get_column_info() {
+ // $_column_headers is already set / cached.
+ if (isset($this->_column_headers) && is_array($this->_column_headers)) {
+ /*
+ * Backward compatibility for `$_column_headers` format prior to WordPress 4.3.
+ *
+ * In WordPress 4.3 the primary column name was added as a fourth item in the
+ * column headers property. This ensures the primary column name is included
+ * in plugins setting the property directly in the three item format.
+ */
+ $column_headers = [[], [], [], $this->get_primary_column_name()];
+ foreach ($this->_column_headers as $key => $value) {
+ $column_headers[$key] = $value;
+ }
+
+ return $column_headers;
+ }
+
+ $columns = get_column_headers($this->screen);
+ $hidden = get_hidden_columns($this->screen);
+
+ $sortable_columns = $this->get_sortable_columns();
+ /**
+ * Filters the list table sortable columns for a specific screen.
+ *
+ * The dynamic portion of the hook name, `$this->screen->id`, refers
+ * to the ID of the current screen.
+ *
+ * @since 3.1.0
+ *
+ * @param array $sortable_columns An array of sortable columns.
+ */
+ $_sortable = apply_filters("manage_{$this->screen->id}_sortable_columns", $sortable_columns);
+
+ $sortable = [];
+ foreach ($_sortable as $id => $data) {
+ if (empty($data)) {
+ continue;
+ }
+
+ $data = (array) $data;
+ if (!isset($data[1])) {
+ $data[1] = false;
+ }
+
+ $sortable[$id] = $data;
+ }
+
+ $primary = $this->get_primary_column_name();
+ $this->_column_headers = [$columns, $hidden, $sortable, $primary];
+
+ return $this->_column_headers;
+ }
+
+ /**
+ * Returns the number of visible columns.
+ *
+ * @since 3.1.0
+ *
+ * @return int
+ */
+ public function get_column_count() {
+ list($columns, $hidden) = $this->get_column_info();
+ $hidden = array_intersect(array_keys($columns), array_filter($hidden));
+
+ return count($columns) - count($hidden);
+ }
+
+ /**
+ * Prints column headers, accounting for hidden and sortable columns.
+ *
+ * @since 3.1.0
+ *
+ * @param bool $with_id Whether to set the ID attribute or not
+ */
+ public function print_column_headers($with_id = true) {
+ list($columns, $hidden, $sortable, $primary) = $this->get_column_info();
+
+ $current_url = set_url_scheme('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
+ $current_url = remove_query_arg('paged', $current_url);
+
+ if (isset($_GET['orderby'])) {
+ $current_orderby = $_GET['orderby'];
+ } else {
+ $current_orderby = '';
+ }
+
+ if (isset($_GET['order']) && 'desc' === $_GET['order']) {
+ $current_order = 'desc';
+ } else {
+ $current_order = 'asc';
+ }
+
+ if (!empty($columns['cb'])) {
+ static $cb_counter = 1;
+ $columns['cb'] = '' . __('Select All') . ' '
+ . ' ';
+ $cb_counter++;
+ }
+
+ foreach ($columns as $column_key => $column_display_name) {
+ $class = ['manage-column', "column-$column_key"];
+
+ if (in_array($column_key, $hidden, true)) {
+ $class[] = 'hidden';
+ }
+
+ if ('cb' === $column_key) {
+ $class[] = 'check-column';
+ } elseif (in_array($column_key, ['posts', 'comments', 'links'], true)) {
+ $class[] = 'num';
+ }
+
+ if ($column_key === $primary) {
+ $class[] = 'column-primary';
+ }
+
+ if (isset($sortable[$column_key])) {
+ list($orderby, $desc_first) = $sortable[$column_key];
+
+ if ($current_orderby === $orderby) {
+ $order = 'asc' === $current_order ? 'desc' : 'asc';
+
+ $class[] = 'sorted';
+ $class[] = $current_order;
+ } else {
+ $order = strtolower($desc_first);
+
+ if (!in_array($order, ['desc', 'asc'], true)) {
+ $order = $desc_first ? 'desc' : 'asc';
+ }
+
+ $class[] = 'sortable';
+ $class[] = 'desc' === $order ? 'asc' : 'desc';
+ }
+
+ $column_display_name = sprintf(
+ '%s ',
+ esc_url(add_query_arg(compact('orderby', 'order'), $current_url)),
+ $column_display_name
+ );
+ }
+
+ $tag = ('cb' === $column_key) ? 'td' : 'th';
+ $scope = ('th' === $tag) ? 'scope="col"' : '';
+ $id = $with_id ? "id='$column_key'" : '';
+
+ if (!empty($class)) {
+ $class = "class='" . implode(' ', $class) . "'";
+ }
+
+ echo "<$tag $scope $id $class>$column_display_name$tag>";
+ }
+ }
+
+ /**
+ * Displays the table.
+ *
+ * @since 3.1.0
+ */
+ public function display() {
+ $singular = $this->_args['singular'];
+
+ $this->display_tablenav('top');
+
+ $this->screen->render_screen_reader_content('heading_list'); ?>
+
+
+
+ print_column_headers(); ?>
+
+
+
+
+ >
+ display_rows_or_placeholder(); ?>
+
+
+
+
+ print_column_headers(false); ?>
+
+
+
+
+ display_tablenav('bottom');
+ }
+
+ /**
+ * Gets a list of CSS classes for the WP_List_Table table tag.
+ *
+ * @since 3.1.0
+ *
+ * @return string[] Array of CSS classes for the table tag.
+ */
+ protected function get_table_classes() {
+ $mode = get_user_setting('posts_list_mode', 'list');
+
+ $mode_class = esc_attr('table-view-' . $mode);
+
+ return ['widefat', 'fixed', 'striped', $mode_class, $this->_args['plural']];
+ }
+
+ /**
+ * Generates the table navigation above or below the table
+ *
+ * @since 3.1.0
+ * @param string $which
+ */
+ protected function display_tablenav($which) {
+ if ('top' === $which) {
+ wp_nonce_field('bulk-' . $this->_args['plural']);
+ } ?>
+
+
+ has_items()) : ?>
+
+ bulk_actions($which); ?>
+
+ extra_tablenav($which);
+ $this->pagination($which); ?>
+
+
+
+ has_items()) {
+ $this->display_rows();
+ } else {
+ echo '';
+ $this->no_items();
+ echo ' ';
+ }
+ }
+
+ /**
+ * Generates the table rows.
+ *
+ * @since 3.1.0
+ */
+ public function display_rows() {
+ foreach ($this->items as $item) {
+ $this->single_row($item);
+ }
+ }
+
+ /**
+ * Generates content for a single row of the table.
+ *
+ * @since 3.1.0
+ *
+ * @param object|array $item The current item
+ */
+ public function single_row($item) {
+ echo '';
+ $this->single_row_columns($item);
+ echo ' ';
+ }
+
+ /**
+ * Generates the columns for a single row of the table.
+ *
+ * @since 3.1.0
+ *
+ * @param object|array $item The current item.
+ */
+ protected function single_row_columns($item) {
+ list($columns, $hidden, $sortable, $primary) = $this->get_column_info();
+
+ foreach ($columns as $column_name => $column_display_name) {
+ $classes = "$column_name column-$column_name";
+ if ($primary === $column_name) {
+ $classes .= ' has-row-actions column-primary';
+ }
+
+ if (in_array($column_name, $hidden, true)) {
+ $classes .= ' hidden';
+ }
+
+ // Comments column uses HTML in the display name with screen reader text.
+ // Strip tags to get closer to a user-friendly string.
+ $data = 'data-colname="' . esc_attr(wp_strip_all_tags($column_display_name)) . '"';
+
+ $attributes = "class='$classes' $data";
+
+ if ('cb' === $column_name) {
+ echo ' ';
+ echo $this->column_cb($item);
+ echo ' ';
+ } elseif (method_exists($this, '_column_' . $column_name)) {
+ echo call_user_func(
+ [$this, '_column_' . $column_name],
+ $item,
+ $classes,
+ $data,
+ $primary
+ );
+ } elseif (method_exists($this, 'column_' . $column_name)) {
+ echo "
";
+ echo call_user_func([$this, 'column_' . $column_name], $item);
+ echo $this->handle_row_actions($item, $column_name, $primary);
+ echo ' ';
+ } else {
+ echo "
";
+ echo $this->column_default($item, $column_name);
+ echo $this->handle_row_actions($item, $column_name, $primary);
+ echo ' ';
+ }
+ }
+ }
+
+ /**
+ * Handles an incoming ajax request (called from admin-ajax.php)
+ *
+ * @since 3.1.0
+ */
+ public function ajax_response() {
+ $this->prepare_items();
+
+ ob_start();
+ if (!empty($_REQUEST['no_placeholder'])) {
+ $this->display_rows();
+ } else {
+ $this->display_rows_or_placeholder();
+ }
+
+ $rows = ob_get_clean();
+
+ $response = ['rows' => $rows];
+
+ if (isset($this->_pagination_args['total_items'])) {
+ $response['total_items_i18n'] = sprintf(
+ /* translators: Number of items. */
+ _n('%s item', '%s items', $this->_pagination_args['total_items']),
+ number_format_i18n($this->_pagination_args['total_items'])
+ );
+ }
+ if (isset($this->_pagination_args['total_pages'])) {
+ $response['total_pages'] = $this->_pagination_args['total_pages'];
+ $response['total_pages_i18n'] = number_format_i18n($this->_pagination_args['total_pages']);
+ }
+
+ die(wp_json_encode($response));
+ }
+
+ /**
+ * Sends required variables to JavaScript land.
+ *
+ * @since 3.1.0
+ */
+ public function _js_vars() {
+ $args = [
+ 'class' => get_class($this),
+ 'screen' => [
+ 'id' => $this->screen->id,
+ 'base' => $this->screen->base,
+ ],
+ ];
+
+ printf("\n", wp_json_encode($args));
+ }
+
+
+ /**
+ * Prepares the list of items for displaying.
+ */
+ public function prepare_items() {
+ $order_by = isset($_GET['orderby']) ? $_GET['orderby'] : '';
+ $order = isset($_GET['order']) ? $_GET['order'] : '';
+ $search_term = isset($_POST['s']) ? $_POST['s'] : '';
+
+ $this->items = $this->lkn_wcip_list_table_data($order_by, $order, $search_term);
+
+ $lkn_wcip_columns = $this->get_columns();
+ $lkn_wcip_hidden = $this->get_hidden_columns();
+ $ldul_sortable = $this->get_sortable_columns();
+
+ $this->_column_headers = [$lkn_wcip_columns, $lkn_wcip_hidden, $ldul_sortable];
+ }
+
+ /**
+ * Wp list table bulk actions
+ */
+ public function get_bulk_actions() {
+ return [
+
+ 'lkn_wcip_delete' => __('Delete', 'wc-invoice-payment'),
+ // 'lkn_wcip_edit' => __('Edit', 'wc-invoice-payment'),
+ ];
+ }
+
+ /**
+ * WP list table row actions
+ */
+ public function handle_row_actions($item, $column_name, $primary) {
+ if ($primary !== $column_name) {
+ return '';
+ }
+
+
+ $action = [];
+ // $action['edit'] = '
' . __('Edit', 'wc-invoice-payment') . ' ';
+ // $action['delete'] = 'a';
+ /*$action['quick-edit'] = '
' . __('Update', 'wc-invoice-payment') . ' ';
+ $action['view'] = '
' . __('View', 'wc-invoice-payment') . ' ';*/
+
+ return $this->row_actions($action);
+ }
+
+ /**
+ * Display columns datas
+ */
+ public function lkn_wcip_list_table_data($order_by = '', $order = '', $search_term = '') {
+ ?>
+ ' ' . $invoiceId . ' ',
+ 'lkn_wcip_client' => $order->get_billing_first_name(),
+ 'lkn_wcip_status' => ucfirst(__($order->get_status(), 'woocommerce')),
+ 'lkn_wcip_total_price' => get_woocommerce_currency_symbol($order->get_currency()) . ' ' . number_format($order->get_total(), 2, ',', '.'),
+ ];
+ }
+ } ?> '
',
+ 'lkn_wcip_id' => __('Invoice', 'wc-invoice-payment'),
+ 'lkn_wcip_client' => __('Name', 'wc-invoice-payment'),
+ 'lkn_wcip_status' => __('Payment status', 'wc-invoice-payment'),
+ 'lkn_wcip_total_price' => __('Total', 'wc-invoice-payment'),
+ ];
+
+ return $columns;
+ }
+
+ /**
+ * Return column value
+ */
+ public function column_default($item, $column_name) {
+ switch ($column_name) {
+ case 'lkn_wcip_id':
+ case 'lkn_wcip_client':
+ case 'lkn_wcip_status':
+ case 'lkn_wcip_total_price':
+ return $item[$column_name];
+ default:
+ return 'no list found';
+ }
+ }
+
+ /**
+ * Rows check box
+ */
+ public function column_cb($items) {
+ $top_checkbox = '
';
+
+ return $top_checkbox;
+ }
+}
diff --git a/admin/css/wc-invoice-payment-admin.css b/admin/css/wc-invoice-payment-admin.css
index 373ea0a..8d49539 100644
--- a/admin/css/wc-invoice-payment-admin.css
+++ b/admin/css/wc-invoice-payment-admin.css
@@ -4,7 +4,7 @@
*/
.wcip-invoice-data {
background-color: white;
- border: solid 1px black;
+ border: 1px solid #c3c4c7;
padding: 23px 24px 12px;
margin-top: 20px;
min-width: 714px;
@@ -57,8 +57,8 @@
cursor: pointer; /* Mouse pointer on hover */
}
.btn-delete {
- background-color: rgba(255, 0, 0, 0.822);
- color: white;
+ background-color: white;
+ color: black;
padding: 4px 10px;
}
.btn-delete:hover {
@@ -79,7 +79,7 @@
color: #0a4b78;
}
.lkn_wcip_amount_input {
- width: 80%;
+ width: 193px;
}
#lkn_wcip_due_date_input {
width: 100%;
diff --git a/admin/js/wc-invoice-payment-admin.js b/admin/js/wc-invoice-payment-admin.js
index dd6d500..bea5635 100644
--- a/admin/js/wc-invoice-payment-admin.js
+++ b/admin/js/wc-invoice-payment-admin.js
@@ -23,15 +23,15 @@ function lkn_wcip_add_amount_row() {
inputRow.innerHTML =
'
' +
- ' ' +
- '
' +
- '
' +
' Name ' +
' ' +
'
' +
'
' +
' Amount ' +
' ' +
+ '
' +
+ '
' +
+ ' ' +
'
';
}
diff --git a/includes/class-wc-invoice-payment.php b/includes/class-wc-invoice-payment.php
index 16f79f5..b1fef81 100644
--- a/includes/class-wc-invoice-payment.php
+++ b/includes/class-wc-invoice-payment.php
@@ -114,6 +114,11 @@ private function load_dependencies() {
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-wc-invoice-payment-admin.php';
+ /**
+ * The class responsible for rendering the invoice table.
+ */
+ require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-wc-invoice-payment-table.php';
+
/**
* The class responsible for defining all actions that occur in the public-facing
* side of the site.
diff --git a/uninstall.php b/uninstall.php
index c21c180..871e69c 100644
--- a/uninstall.php
+++ b/uninstall.php
@@ -29,3 +29,5 @@
if (!defined('WP_UNINSTALL_PLUGIN')) {
exit;
}
+
+delete_option('lkn_wcip_invoices');
From f3dee2464f886b842bee2b12ba244dcc9bb4a4e3 Mon Sep 17 00:00:00 2001
From: emanuellopess
Date: Mon, 28 Mar 2022 17:19:45 -0300
Subject: [PATCH 07/20] =?UTF-8?q?improvement:=20Implementada=20notifica?=
=?UTF-8?q?=C3=A7ao=20de=20fatura=20criada=20via=20e-mail,=20ajuste=20na?=
=?UTF-8?q?=20fun=C3=A7ao=20de=20renderiza=C3=A7ao=20de=20submenus=20e=20a?=
=?UTF-8?q?di=C3=A7ao=20de=20tratamento=20de=20edi=C3=A7ao=20de=20pedidos?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
admin/class-wc-invoice-payment-admin.php | 229 ++++++++++++++++-------
admin/css/wc-invoice-payment-admin.css | 1 +
admin/js/wc-invoice-payment-admin.js | 5 -
3 files changed, 166 insertions(+), 69 deletions(-)
diff --git a/admin/class-wc-invoice-payment-admin.php b/admin/class-wc-invoice-payment-admin.php
index 60b5c8c..64815db 100644
--- a/admin/class-wc-invoice-payment-admin.php
+++ b/admin/class-wc-invoice-payment-admin.php
@@ -123,16 +123,6 @@ public function add_setting_session() {
[$this, 'render_invoice_list_page'],
1
);
-
- add_submenu_page(
- null,
- __('Edit invoice', 'wc-invoice-payment'),
- __('Edit invoice', 'wc-invoice-payment'),
- 'manage_options',
- 'edit-invoice',
- [$this, 'render_edit_invoice_page'],
- 1
- );
}
/**
@@ -145,10 +135,23 @@ public function render_edit_invoice_page() {
return;
}
$invoiceId = $_GET['invoice'];
- $today = date('Y-m-d');
+
+ $statusWc = [];
+ $statusWc[] = ['status' => 'wc-pending', 'label' => _x('Pending payment', 'Order status', 'woocommerce')];
+ $statusWc[] = ['status' => 'wc-processing', 'label' => _x('Processing', 'Order status', 'woocommerce')];
+ $statusWc[] = ['status' => 'wc-on-hold', 'label' => _x('On hold', 'Order status', 'woocommerce')];
+ $statusWc[] = ['status' => 'wc-completed', 'label' => _x('Completed', 'Order status', 'woocommerce')];
+ $statusWc[] = ['status' => 'wc-cancelled', 'label' => _x('Cancelled', 'Order status', 'woocommerce')];
+ $statusWc[] = ['status' => 'wc-refunded', 'label' => _x('Refunded', 'Order status', 'woocommerce')];
+ $statusWc[] = ['status' => 'wc-failed', 'label' => _x('Failed', 'Order status', 'woocommerce')];
+
+ $c = 0;
+ $order = wc_get_order($invoiceId);
+ $items = $order->get_items();
+ $checkoutUrl = $order->get_checkout_payment_url();
+ $orderStatus = $order->get_status();
$currencies = get_woocommerce_currencies();
- $active_currency = get_woocommerce_currency();
$gateways = WC()->payment_gateways->get_available_payment_gateways();
$enabled_gateways = [];
@@ -163,22 +166,23 @@ public function render_edit_invoice_page() {
';
}
+/**
+ * Remove line in the charges options box
+ *
+ * @param {String} id
+ *
+ * @return void
+ */
function lkn_wcip_remove_amount_row(id) {
let priceLines = document.getElementsByClassName('price-row-wrap');
let lineQtd = priceLines.length;
@@ -42,8 +54,27 @@ function lkn_wcip_remove_amount_row(id) {
}
}
+/**
+ * Filter the input in the amount input to allow only numbers and comma and dot
+ *
+ * @param {String} val
+ * @param {String} row
+ *
+ * @return void
+ */
function lkn_wcip_filter_amount_input(val, row) {
let filteredVal = val.replace(/[^0-9.,]/g, '').replace(/(\..*?)\..*/g, '$1');
let inputAmount = document.getElementById('lkn_wcip_amount_invoice_' + row);
inputAmount.value = filteredVal;
+}
+
+/**
+ * Notifies before the deletion of a invoice
+ *
+ * @return void
+ */
+function lkn_wcip_delete_invoice () {
+ if(confirm(__('Are you sure you want to delete the invoice?','wc-invoice-payment')) === true) {
+ window.location.href += '&lkn_wcip_delete=true';
+ }
}
\ No newline at end of file
From 0374f6463b57ccf1d7d6ccb5b055adbb2fa489df Mon Sep 17 00:00:00 2001
From: emanuellopess
Date: Thu, 31 Mar 2022 15:10:13 -0300
Subject: [PATCH 15/20] =?UTF-8?q?docs:=20Adicionado=20novo=20readme=20e=20?=
=?UTF-8?q?informa=C3=A7oes=20atualizadas?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 40 +++++++++++++++++++++
README.txt | 104 ++++++++++++++---------------------------------------
2 files changed, 66 insertions(+), 78 deletions(-)
create mode 100644 README.md
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..06d952a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,40 @@
+# WooCommerce Invoice Payment
+
+WooCommerce Invoice Payment is an extension plugin for WooCommerce that aims to facilitate the management of invoices through the platform. It sends a new invoice email notification for the client and invoice creation with a direct payment link.
+
+## Dependencies
+
+WooCommerce Invoice Payment plugin is dependent on WooCommerce plugin, please make sure WooCommerce is installed and properly configured before starting WooCommerce Invoice Payment installation.
+
+
+## Installation
+
+1) Look in the sidebar for the WordPress plugins area;
+
+2) In installed plugins look for the 'add new' option in the header;
+
+3) Click on the 'submit plugin' option in the page title and upload the woocommerce-invoice-payment-main.zip plugin;
+
+4) Click on the 'install now' button and then activate the installed plugin;
+
+The WooCommerce Invoice Payment plugin is now live and working.
+
+## User instructions
+
+1) Search the WordPress sidebar for 'WooCommerce Invoice Payment';
+
+2) In the plugin options look for 'Add invoice';
+
+3) Fill in the customer data, currency, payment method and add the charges;
+
+4) If you want to send the invoice to the customer's email, select the 'Send invoice to customer' option in the invoice actions;
+
+5) Click save;
+
+You have created your first invoice with the WooCommerce Invoice Payment plugin.
+
+## Changelog
+
+### v1.0.0
+- Plugin launch.
+
diff --git a/README.txt b/README.txt
index 7fc7c9c..125ba06 100644
--- a/README.txt
+++ b/README.txt
@@ -1,61 +1,47 @@
=== Plugin Name ===
-Contributors: (this should be a list of wordpress.org userid's)
-Donate link: https://www.linknacional.com/
-Tags: comments, spam
-Requires at least: 3.0.1
-Tested up to: 3.4
+Contributors: @linknacional
+Donate link: https://www.linknacional.com.br/wordpress/
+Tags: woocommerce, invoice, payment
+Requires at least: 4.7
+Tested up to: 5.9
Stable tag: 4.3
+Requires PHP: 7.0
License: GPLv2 or later
-License URI: http://www.gnu.org/licenses/gpl-2.0.html
+License URI: https://www.gnu.org/licenses/gpl-2.0.html
-Here is a short description of the plugin. This should be no more than 150 characters. No markup here.
+Invoice payment generation and management for WooCommerce.
== Description ==
-This is the long description. No limit, and you can use Markdown (as well as in the following sections).
+**Dependencies**
-For backwards compatibility, if this section is missing, the full length of the short description will be used, and
-Markdown parsed.
+WooCommerce Invoice Payment plugin is dependent on WooCommerce plugin, please make sure WooCommerce is installed and properly configured before starting WooCommerce Invoice Payment installation.
-A few notes about the sections above:
+**User instructions**
-* "Contributors" is a comma separated list of wp.org/wp-plugins.org usernames
-* "Tags" is a comma separated list of tags that apply to the plugin
-* "Requires at least" is the lowest version that the plugin will work on
-* "Tested up to" is the highest version that you've *successfully used to test the plugin*. Note that it might work on
-higher versions... this is just the highest one you've verified.
-* Stable tag should indicate the Subversion "tag" of the latest stable version, or "trunk," if you use `/trunk/` for
-stable.
+1. Search the WordPress sidebar for 'WooCommerce Invoice Payment';
- Note that the `readme.txt` of the stable tag is the one that is considered the defining one for the plugin, so
-if the `/trunk/readme.txt` file says that the stable tag is `4.3`, then it is `/tags/4.3/readme.txt` that'll be used
-for displaying information about the plugin. In this situation, the only thing considered from the trunk `readme.txt`
-is the stable tag pointer. Thus, if you develop in trunk, you can update the trunk `readme.txt` to reflect changes in
-your in-development version, without having that information incorrectly disclosed about the current stable version
-that lacks those changes -- as long as the trunk's `readme.txt` points to the correct stable tag.
+2. In the plugin options look for 'Add invoice';
- If no stable tag is provided, it is assumed that trunk is stable, but you should specify "trunk" if that's where
-you put the stable version, in order to eliminate any doubt.
+3. Fill in the customer data, currency, payment method and add the charges;
-== Installation ==
+4. If you want to send the invoice to the customer's email, select the 'Send invoice to customer' option in the invoice actions;
-This section describes how to install the plugin and get it working.
+5. Click save;
-e.g.
+You have created your first invoice with the WooCommerce Invoice Payment plugin.
-1. Upload `boilerplate-wc.php` to the `/wp-content/plugins/` directory
-1. Activate the plugin through the 'Plugins' menu in WordPress
-1. Place `` in your templates
+== Installation ==
-== Frequently Asked Questions ==
+1. Look in the sidebar for the WordPress plugins area;
-= A question that someone might have =
+2. In installed plugins look for the 'add new' option in the header;
-An answer to that question.
+3. Click on the 'submit plugin' option in the page title and upload the woocommerce-invoice-payment-main.zip plugin;
-= What about foo bar? =
+4. Click on the 'install now' button and then activate the installed plugin;
-Answer to foo bar dilemma.
+The WooCommerce Invoice Payment plugin is now live and working.
== Screenshots ==
@@ -67,48 +53,10 @@ directory take precedence. For example, `/assets/screenshot-1.png` would win ove
== Changelog ==
-= 1.0 =
-* A change since the previous version.
-* Another change.
-
-= 0.5 =
-* List versions from most recent at top to oldest at bottom.
+= 1.0.0 =
+* Plugin launch.
== Upgrade Notice ==
-= 1.0 =
+= 1.0.0 =
Upgrade notices describe the reason a user should upgrade. No more than 300 characters.
-
-= 0.5 =
-This version fixes a security related bug. Upgrade immediately.
-
-== Arbitrary section ==
-
-You may provide arbitrary sections, in the same format as the ones above. This may be of use for extremely complicated
-plugins where more information needs to be conveyed that doesn't fit into the categories of "description" or
-"installation." Arbitrary sections will be shown below the built-in sections outlined above.
-
-== A brief Markdown Example ==
-
-Ordered list:
-
-1. Some feature
-1. Another feature
-1. Something else about the plugin
-
-Unordered list:
-
-* something
-* something else
-* third thing
-
-Here's a link to [WordPress](http://wordpress.org/ "Your favorite software") and one to [Markdown's Syntax Documentation][markdown syntax].
-Titles are optional, naturally.
-
-[markdown syntax]: http://daringfireball.net/projects/markdown/syntax
- "Markdown is what the parser uses to process much of the readme file"
-
-Markdown uses email style notation for blockquotes and I've been told:
-> Asterisks for *emphasis*. Double it up for **strong**.
-
-``
\ No newline at end of file
From 5ed2b68f28e0e999de225dd580e0dd006e57e0f1 Mon Sep 17 00:00:00 2001
From: emanuellopess
Date: Thu, 31 Mar 2022 15:10:34 -0300
Subject: [PATCH 16/20] =?UTF-8?q?feat:=20Implementa=C3=A7ao=20da=20bibliot?=
=?UTF-8?q?eca=20de=20atualiza=C3=A7oes=20automaticas?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
...ent-pt_BR-wc-invoice-payment-admin-js.json | 3 +
languages/wc-invoice-payment-pt_BR.mo | Bin 1287 -> 1381 bytes
languages/wc-invoice-payment-pt_BR.po | 5 +-
languages/wc-invoice-payment.pot | 3 +
plugin-updater/Puc/Autoloader.php | 59 ++
plugin-updater/Puc/InstalledPackage.php | 103 ++
plugin-updater/Puc/Metadata.php | 135 +++
plugin-updater/Puc/Plugin/Info.php | 134 +++
plugin-updater/Puc/Plugin/Package.php | 215 ++++
plugin-updater/Puc/Plugin/Ui.php | 292 ++++++
plugin-updater/Puc/Plugin/Update.php | 114 +++
plugin-updater/Puc/Plugin/UpdateChecker.php | 417 ++++++++
plugin-updater/Puc/Scheduler.php | 258 +++++
plugin-updater/Puc/StateStore.php | 231 +++++
plugin-updater/Puc/Update.php | 38 +
plugin-updater/Puc/UpdateChecker.php | 959 ++++++++++++++++++
plugin-updater/Puc/UpgraderStatus.php | 182 ++++
plugin-updater/Puc/Utils.php | 72 ++
plugin-updater/README.md | 26 +
.../languages/plugin-update-checker-ca.mo | Bin 0 -> 1186 bytes
.../languages/plugin-update-checker-ca.po | 48 +
.../languages/plugin-update-checker-pt_BR.mo | Bin 0 -> 1014 bytes
.../languages/plugin-update-checker-pt_BR.po | 48 +
.../languages/plugin-update-checker.pot | 49 +
plugin-updater/license.txt | 7 +
plugin-updater/load-puc.php | 6 +
plugin-updater/plugin-update-checker.php | 10 +
wc-invoice-payment.php | 18 +-
28 files changed, 3430 insertions(+), 2 deletions(-)
create mode 100644 plugin-updater/Puc/Autoloader.php
create mode 100644 plugin-updater/Puc/InstalledPackage.php
create mode 100644 plugin-updater/Puc/Metadata.php
create mode 100644 plugin-updater/Puc/Plugin/Info.php
create mode 100644 plugin-updater/Puc/Plugin/Package.php
create mode 100644 plugin-updater/Puc/Plugin/Ui.php
create mode 100644 plugin-updater/Puc/Plugin/Update.php
create mode 100644 plugin-updater/Puc/Plugin/UpdateChecker.php
create mode 100644 plugin-updater/Puc/Scheduler.php
create mode 100644 plugin-updater/Puc/StateStore.php
create mode 100644 plugin-updater/Puc/Update.php
create mode 100644 plugin-updater/Puc/UpdateChecker.php
create mode 100644 plugin-updater/Puc/UpgraderStatus.php
create mode 100644 plugin-updater/Puc/Utils.php
create mode 100644 plugin-updater/README.md
create mode 100644 plugin-updater/languages/plugin-update-checker-ca.mo
create mode 100644 plugin-updater/languages/plugin-update-checker-ca.po
create mode 100644 plugin-updater/languages/plugin-update-checker-pt_BR.mo
create mode 100644 plugin-updater/languages/plugin-update-checker-pt_BR.po
create mode 100644 plugin-updater/languages/plugin-update-checker.pot
create mode 100644 plugin-updater/license.txt
create mode 100644 plugin-updater/load-puc.php
create mode 100644 plugin-updater/plugin-update-checker.php
diff --git a/languages/wc-invoice-payment-pt_BR-wc-invoice-payment-admin-js.json b/languages/wc-invoice-payment-pt_BR-wc-invoice-payment-admin-js.json
index bc73127..72e4470 100644
--- a/languages/wc-invoice-payment-pt_BR-wc-invoice-payment-admin-js.json
+++ b/languages/wc-invoice-payment-pt_BR-wc-invoice-payment-admin-js.json
@@ -12,6 +12,9 @@
],
"Amount": [
"Valor"
+ ],
+ "Are you sure you want to delete the invoice?": [
+ "Tem certeza que deseja deletar a fatura?"
]
}
}
diff --git a/languages/wc-invoice-payment-pt_BR.mo b/languages/wc-invoice-payment-pt_BR.mo
index 6ce3467e58520ae11238fcaf94d549cb2c73dde0..421e3cc0530e9f4647f519f4b82d3cce897f9469 100644
GIT binary patch
delta 628
zcmYk(zb^xE7{~E%f2yjYRV_*`5jznEy4oxT(pcnD6_rxCv`HnTiABr}iNyb4C?@`d
zjs}TZ#9%Y{1H3==t$1=zU-!Mc-t*k^J&%4w8*ho=r6Dq8mV6~=$s3BQ0>6b8aEf&f2XPC7xQB5(
zKovT{B%Yy~zd|*5YwthcFzZKD;kLcrvA$!L`sR}py*Nx2y%X`sGf(OzH25!QK3
z;65(lDeCz<)R(q#8lO?`{YDNGpldZ8LDk7(n)+sj6ODew-pC_|+2%)`_dKTE?<6o=uHm{yzGR%^BOPc;;Ak**Gz9GnF~5XT_6xzvhKhmH<)D;=bhlSOdq
zClDOm6$b}#@dLOx6a?R2y^DvQJUL0Z=iHmm@G@+_7lWP=WpaglA=k(&&n$~mK8Ynv
zW7XB`xIkUUY23jS?%^^X;3S@60WX{#jH&y$WY)G+`v3;q8h|F
zhuc`eebitl?tK$ys9UJU9rwKNyg_aB7W4GCM{cyhGivfTSAXLy^$!-Yz%*M}Lp44`
z?XZEX*g_3@jr?rDMT6d>)_*{q@)IuNhn~~lM%-v;o-Ty`tfN`cx%yyb+|OanP30(W`H+TlbHKcmBCIjDxh7jgsg%X`VHbDCzE|
F%D-tWDo6kT
diff --git a/languages/wc-invoice-payment-pt_BR.po b/languages/wc-invoice-payment-pt_BR.po
index 97faeae..a3024c5 100644
--- a/languages/wc-invoice-payment-pt_BR.po
+++ b/languages/wc-invoice-payment-pt_BR.po
@@ -23,6 +23,9 @@ msgstr "Erro na geração da fatura"
msgid "Invoices successfully deleted"
msgstr "Faturas excluídas com sucesso"
+msgid "Error on invoice deletion"
+msgstr "Erro ao excluir a fatura"
+
msgid "Invoice details"
msgstr "Detalhes da fatura"
@@ -54,7 +57,7 @@ msgid "Select an action..."
msgstr "Selecione uma ação..."
msgid "Send invoice to customer"
-msgstr "Envia a fatura ao cliente"
+msgstr "Enviar fatura para o cliente"
msgid "Price"
msgstr "Preço"
diff --git a/languages/wc-invoice-payment.pot b/languages/wc-invoice-payment.pot
index 29918e9..602c1ee 100644
--- a/languages/wc-invoice-payment.pot
+++ b/languages/wc-invoice-payment.pot
@@ -23,6 +23,9 @@ msgstr ""
msgid "Invoices successfully deleted"
msgstr ""
+msgid "Error on invoice deletion"
+msgstr ""
+
msgid "Invoice details"
msgstr ""
diff --git a/plugin-updater/Puc/Autoloader.php b/plugin-updater/Puc/Autoloader.php
new file mode 100644
index 0000000..f80468c
--- /dev/null
+++ b/plugin-updater/Puc/Autoloader.php
@@ -0,0 +1,59 @@
+rootDir = dirname(__FILE__) . '/';
+ $nameParts = explode('_', __CLASS__, 3);
+ $this->prefix = $nameParts[0] . '_' . $nameParts[1] . '_';
+
+ $this->libraryDir = $this->rootDir . '../..';
+ if (!self::isPhar()) {
+ $this->libraryDir = realpath($this->libraryDir);
+ }
+ $this->libraryDir = $this->libraryDir . '/';
+
+ spl_autoload_register([$this, 'autoload']);
+ }
+
+ /**
+ * Determine if this file is running as part of a Phar archive.
+ *
+ * @return bool
+ */
+ private static function isPhar() {
+ //Check if the current file path starts with "phar://".
+ static $pharProtocol = 'phar://';
+
+ return (substr(__FILE__, 0, strlen($pharProtocol)) === $pharProtocol);
+ }
+
+ 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;
diff --git a/plugin-updater/Puc/InstalledPackage.php b/plugin-updater/Puc/InstalledPackage.php
new file mode 100644
index 0000000..1b1c194
--- /dev/null
+++ b/plugin-updater/Puc/InstalledPackage.php
@@ -0,0 +1,103 @@
+updateChecker = $updateChecker;
+ }
+
+ /**
+ * 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 (without a trailing slash).
+ *
+ * @return string
+ */
+ abstract public function getAbsoluteDirectoryPath();
+
+ /**
+ * Check whether a regular file exists in the package's directory.
+ *
+ * @param string $relativeFileName File name relative to the package directory.
+ * @return bool
+ */
+ public function fileExists($relativeFileName) {
+ return is_file(
+ $this->getAbsoluteDirectoryPath()
+ . DIRECTORY_SEPARATOR
+ . ltrim($relativeFileName, '/\\')
+ );
+ }
+
+ /* -------------------------------------------------------------------
+ * 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 = [];
+ 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();
+
+ /**
+ * Get the value of a specific plugin or theme header.
+ *
+ * @param string $headerName
+ * @return string Either the value of the header, or an empty string if the header doesn't exist.
+ */
+ abstract public function getHeaderValue($headerName);
+ }
+endif;
diff --git a/plugin-updater/Puc/Metadata.php b/plugin-updater/Puc/Metadata.php
new file mode 100644
index 0000000..5a1bfd9
--- /dev/null
+++ b/plugin-updater/Puc/Metadata.php
@@ -0,0 +1,135 @@
+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 [];
+ }
+
+ /**
+ * @param string $tag
+ * @return string
+ */
+ protected function getPrefixedFilter($tag) {
+ return 'puc_' . $tag;
+ }
+ }
+
+endif;
diff --git a/plugin-updater/Puc/Plugin/Info.php b/plugin-updater/Puc/Plugin/Info.php
new file mode 100644
index 0000000..b0d147f
--- /dev/null
+++ b/plugin-updater/Puc/Plugin/Info.php
@@ -0,0 +1,134 @@
+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 = [
+ 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
+ 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
+ 'requires_php',
+ ];
+ 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(['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, ['high' => true, 'low' => true]);
+ }
+
+ return $info;
+ }
+
+ protected function getFormattedAuthor() {
+ if (!empty($this->author_homepage)) {
+ /** @noinspection HtmlUnknownTarget */
+ return sprintf('%s ', $this->author_homepage, $this->author);
+ }
+
+ return $this->author;
+ }
+ }
+
+endif;
diff --git a/plugin-updater/Puc/Plugin/Package.php b/plugin-updater/Puc/Plugin/Package.php
new file mode 100644
index 0000000..13dbabc
--- /dev/null
+++ b/plugin-updater/Puc/Plugin/Package.php
@@ -0,0 +1,215 @@
+pluginAbsolutePath = $pluginAbsolutePath;
+ $this->pluginFile = plugin_basename($this->pluginAbsolutePath);
+
+ parent::__construct($updateChecker);
+
+ //Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
+ add_filter('upgrader_post_install', [$this, 'clearCachedVersion']);
+ add_action('delete_site_transient_update_plugins', [$this, 'clearCachedVersion']);
+ }
+
+ 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->updateChecker->triggerError(
+ sprintf(
+ "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
+ $this->updateChecker->pluginFile
+ ),
+ E_USER_WARNING
+ );
+
+ return null;
+ }
+ }
+
+ /**
+ * 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;
+ }
+
+ public function getAbsoluteDirectoryPath() {
+ return dirname($this->pluginAbsolutePath);
+ }
+
+ /**
+ * Get the value of a specific plugin or theme header.
+ *
+ * @param string $headerName
+ * @param string $defaultValue
+ * @return string Either the value of the header, or $defaultValue if the header doesn't exist or is empty.
+ */
+ public function getHeaderValue($headerName, $defaultValue = '') {
+ $headers = $this->getPluginHeader();
+ if (isset($headers[$headerName]) && ($headers[$headerName] !== '')) {
+ return $headers[$headerName];
+ }
+
+ return $defaultValue;
+ }
+
+ protected function getHeaderNames() {
+ return [
+ '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',
+ ];
+ }
+
+ /**
+ * Get the translated plugin title.
+ *
+ * @return string
+ */
+ public function getPluginTitle() {
+ $title = '';
+ $header = $this->getPluginHeader();
+ if ($header && !empty($header['Name']) && isset($header['TextDomain'])) {
+ $title = translate($header['Name'], $header['TextDomain']);
+ }
+
+ return $title;
+ }
+
+ /**
+ * Get plugin's metadata from its file header.
+ *
+ * @return array
+ */
+ public function getPluginHeader() {
+ if (!is_file($this->pluginAbsolutePath)) {
+ //This can happen if the plugin filename is wrong.
+ $this->updateChecker->triggerError(
+ sprintf(
+ "Can't to read the plugin header for '%s'. The file does not exist.",
+ $this->updateChecker->pluginFile
+ ),
+ E_USER_WARNING
+ );
+
+ return [];
+ }
+
+ if (!function_exists('get_plugin_data')) {
+ /** @noinspection PhpIncludeInspection */
+ require_once ABSPATH . '/wp-admin/includes/plugin.php';
+ }
+
+ return get_plugin_data($this->pluginAbsolutePath, false, false);
+ }
+
+ public function removeHooks() {
+ remove_filter('upgrader_post_install', [$this, 'clearCachedVersion']);
+ remove_action('delete_site_transient_update_plugins', [$this, 'clearCachedVersion']);
+ }
+
+ /**
+ * Check if the plugin file is inside the mu-plugins directory.
+ *
+ * @return bool
+ */
+ public function isMuPlugin() {
+ static $cachedResult = null;
+
+ if ($cachedResult === null) {
+ if (!defined('WPMU_PLUGIN_DIR') || !is_string(WPMU_PLUGIN_DIR)) {
+ $cachedResult = false;
+
+ return $cachedResult;
+ }
+
+ //Convert both paths to the canonical form before comparison.
+ $muPluginDir = realpath(WPMU_PLUGIN_DIR);
+ $pluginPath = realpath($this->pluginAbsolutePath);
+ //If realpath() fails, just normalize the syntax instead.
+ if (($muPluginDir === false) || ($pluginPath === false)) {
+ $muPluginDir = self::normalizePath(WPMU_PLUGIN_DIR);
+ $pluginPath = self::normalizePath($this->pluginAbsolutePath);
+ }
+
+ $cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
+ }
+
+ return $cachedResult;
+ }
+
+ /**
+ *
+ * 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;
+ }
+ }
+
+endif;
diff --git a/plugin-updater/Puc/Plugin/Ui.php b/plugin-updater/Puc/Plugin/Ui.php
new file mode 100644
index 0000000..4e32f94
--- /dev/null
+++ b/plugin-updater/Puc/Plugin/Ui.php
@@ -0,0 +1,292 @@
+updateChecker = $updateChecker;
+ $this->manualCheckErrorTransient = $this->updateChecker->getUniqueName('manual_check_errors');
+
+ add_action('admin_init', [$this, 'onAdminInit']);
+ }
+
+ public function onAdminInit() {
+ if ($this->updateChecker->userCanInstallUpdates()) {
+ $this->handleManualCheck();
+
+ add_filter('plugin_row_meta', [$this, 'addViewDetailsLink'], 10, 3);
+ add_filter('plugin_row_meta', [$this, 'addCheckForUpdatesLink'], 10, 2);
+ add_action('all_admin_notices', [$this, 'displayManualCheckResult']);
+ }
+ }
+
+ /**
+ * 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 = []) {
+ if ($this->isMyPluginFile($pluginFile) && !isset($pluginData['slug'])) {
+ $linkText = apply_filters($this->updateChecker->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->updateChecker->getUniqueName('view_details_link_position'),
+ 'before'
+ );
+
+ break;
+ }
+ }
+ }
+
+ $viewDetailsLink = sprintf(
+ '%s ',
+ esc_url(network_admin_url('plugin-install.php?tab=plugin-information&plugin=' . urlencode($this->updateChecker->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;
+ }
+
+ /**
+ * 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) {
+ if ($this->isMyPluginFile($pluginFile)) {
+ $linkUrl = wp_nonce_url(
+ add_query_arg(
+ [
+ 'puc_check_for_updates' => 1,
+ 'puc_slug' => $this->updateChecker->slug,
+ ],
+ self_admin_url('plugins.php')
+ ),
+ 'puc_check_for_updates'
+ );
+
+ $linkText = apply_filters(
+ $this->updateChecker->getUniqueName('manual_check_link'),
+ __('Check for updates', 'plugin-update-checker')
+ );
+ if (!empty($linkText)) {
+ /** @noinspection HtmlUnknownTarget */
+ $pluginMeta[] = sprintf('%s ', esc_attr($linkUrl), $linkText);
+ }
+ }
+
+ return $pluginMeta;
+ }
+
+ protected function isMyPluginFile($pluginFile) {
+ return ($pluginFile == $this->updateChecker->pluginFile)
+ || (!empty($this->updateChecker->muPluginFile) && ($pluginFile == $this->updateChecker->muPluginFile));
+ }
+
+ /**
+ * 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->updateChecker->slug
+ && check_admin_referer('puc_check_for_updates');
+
+ if ($shouldCheck) {
+ $update = $this->updateChecker->checkForUpdates();
+ $status = ($update === null) ? 'no_update' : 'update_available';
+ $lastRequestApiErrors = $this->updateChecker->getLastRequestApiErrors();
+
+ if (($update === null) && !empty($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 = [
+ 'puc-github-http-error',
+ 'puc-gitlab-http-error',
+ 'puc-bitbucket-http-error',
+ ];
+
+ foreach ($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, $lastRequestApiErrors, 60);
+ }
+ }
+
+ wp_redirect(add_query_arg(
+ [
+ 'puc_update_check_result' => $status,
+ 'puc_slug' => $this->updateChecker->slug,
+ ],
+ self_admin_url('plugins.php')
+ ));
+ exit;
+ }
+ }
+
+ /**
+ * 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->updateChecker->slug)) {
+ $status = strval($_GET['puc_update_check_result']);
+ $title = $this->updateChecker->getInstalledPackage()->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(
+ '',
+ $noticeClass,
+ apply_filters($this->updateChecker->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 .= '';
+ $formatString = '%1$s %2$s
';
+ } else {
+ $formatString = '%1$s %2$s
';
+ }
+ 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 .= ' ';
+ }
+
+ return $output;
+ }
+
+ public function removeHooks() {
+ remove_action('admin_init', [$this, 'onAdminInit']);
+ remove_filter('plugin_row_meta', [$this, 'addViewDetailsLink'], 10);
+ remove_filter('plugin_row_meta', [$this, 'addCheckForUpdatesLink'], 10);
+ remove_action('all_admin_notices', [$this, 'displayManualCheckResult']);
+ }
+ }
+endif;
diff --git a/plugin-updater/Puc/Plugin/Update.php b/plugin-updater/Puc/Plugin/Update.php
new file mode 100644
index 0000000..eccc1cd
--- /dev/null
+++ b/plugin-updater/Puc/Plugin/Update.php
@@ -0,0 +1,114 @@
+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->requires_php = $this->requires_php;
+ $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,
+ ['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;
diff --git a/plugin-updater/Puc/Plugin/UpdateChecker.php b/plugin-updater/Puc/Plugin/UpdateChecker.php
new file mode 100644
index 0000000..f28db06
--- /dev/null
+++ b/plugin-updater/Puc/Plugin/UpdateChecker.php
@@ -0,0 +1,417 @@
+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, [$this, 'getAbsolutePath']);
+
+ parent::__construct($metadataUrl, dirname($this->pluginFile), $slug, $checkPeriod, $optionName);
+
+ //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, [$this, 'removeHooks']);
+
+ $this->extraUi = new Lkn_Puc_Plugin_Ui($this);
+ }
+
+ /**
+ * Create an instance of the scheduler.
+ *
+ * @param int $checkPeriod
+ * @return Lkn_Puc_Scheduler
+ */
+ protected function createScheduler($checkPeriod) {
+ $scheduler = new Lkn_Puc_Scheduler($this, $checkPeriod, ['load-plugins.php']);
+ register_deactivation_hook($this->pluginFile, [$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', [$this, 'injectInfo'], 20, 3);
+
+ 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();
+ $this->extraUi->removeHooks();
+ $this->package->removeHooks();
+
+ remove_filter('plugins_api', [$this, 'injectInfo'], 20);
+ }
+
+ /**
+ * 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 Lkn_Puc_Plugin_Info
+ */
+ public function requestInfo($queryArgs = []) {
+ list($pluginInfo, $result) = $this->requestMetadata('Lkn_Puc_Plugin_Info', $queryArgs);
+
+ if ($pluginInfo !== null) {
+ /** @var Lkn_Puc_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 Lkn_Puc_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(['checking_for_updates' => '1']);
+ if ($pluginInfo === null) {
+ return null;
+ }
+ $update = Lkn_Puc_Plugin_Update::fromPluginInfo($pluginInfo);
+
+ $update = $this->filterUpdateResult($update);
+
+ return $update;
+ }
+
+ /**
+ * 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();
+ $this->fixSupportedWordpressVersion($pluginInfo);
+
+ $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->package->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->package->isMuPlugin()) {
+ return $this->muPluginFile;
+ }
+
+ return $this->pluginFile;
+ }
+
+ protected function getNoUpdateItemFields() {
+ return array_merge(
+ parent::getNoUpdateItemFields(),
+ [
+ 'id' => $this->pluginFile,
+ 'slug' => $this->slug,
+ 'plugin' => $this->pluginFile,
+ 'icons' => [],
+ 'banners' => [],
+ 'banners_rtl' => [],
+ 'tested' => '',
+ 'compatibility' => new stdClass(),
+ ]
+ );
+ }
+
+ /**
+ * 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 Lkn_Puc_Plugin_Update|null
+ */
+ public function getUpdate() {
+ $update = parent::getUpdate();
+ if (isset($update)) {
+ /** @var Lkn_Puc_Plugin_Update $update */
+ $update->filename = $this->pluginFile;
+ }
+
+ return $update;
+ }
+
+ /**
+ * Get the translated plugin title.
+ *
+ * @deprecated
+ * @return string
+ */
+ public function getPluginTitle() {
+ return $this->package->getPluginTitle();
+ }
+
+ /**
+ * 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.
+ *
+ * @deprecated
+ * @return bool
+ */
+ protected function isMuPlugin() {
+ return $this->package->isMuPlugin();
+ }
+
+ /**
+ * 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->package->isMuPlugin();
+ }
+
+ /**
+ * Get absolute path to the main plugin file.
+ *
+ * @return string
+ */
+ public function getAbsolutePath() {
+ return $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);
+ }
+
+ /**
+ * Create a package instance that represents this plugin or theme.
+ *
+ * @return Lkn_Puc_InstalledPackage
+ */
+ protected function createInstalledPackage() {
+ return new Lkn_Puc_Plugin_Package($this->pluginAbsolutePath, $this);
+ }
+
+ /**
+ * @return Lkn_Puc_Plugin_Package
+ */
+ public function getInstalledPackage() {
+ return $this->package;
+ }
+ }
+
+endif;
diff --git a/plugin-updater/Puc/Scheduler.php b/plugin-updater/Puc/Scheduler.php
new file mode 100644
index 0000000..2a8ecb3
--- /dev/null
+++ b/plugin-updater/Puc/Scheduler.php
@@ -0,0 +1,258 @@
+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 = [
+ 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', [$this, '_addCustomSchedule']);
+ }
+
+ if (!wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING')) {
+ //Randomly offset the schedule to help prevent update server traffic spikes. Without this
+ //most checks may happen during times of day when people are most likely to install new plugins.
+ $firstCheckTime = time() - rand(0, max($this->checkPeriod * 3600 - 15 * 60, 1));
+ $firstCheckTime = apply_filters(
+ $this->updateChecker->getUniqueName('first_check_time'),
+ $firstCheckTime
+ );
+ wp_schedule_event($firstCheckTime, $scheduleName, $this->cronHook);
+ }
+ add_action($this->cronHook, [$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', [$this, 'maybeCheckForUpdates']);
+
+ //Like WordPress itself, we check more often on certain pages.
+ /** @see wp_update_plugins */
+ add_action('load-update-core.php', [$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, [$this, 'maybeCheckForUpdates']);
+ }
+ //This hook fires after a bulk update is complete.
+ add_action('upgrader_process_complete', [$this, 'upgraderProcessComplete'], 11, 2);
+ } else {
+ //Periodic checks are disabled.
+ wp_clear_scheduled_hook($this->cronHook);
+ }
+ }
+
+ /**
+ * Runs upon the WP action upgrader_process_complete.
+ *
+ * We look at the parameters to decide whether to call maybeCheckForUpdates() or not.
+ * We also check if the update checker has been removed by the update.
+ *
+ * @param WP_Upgrader $upgrader WP_Upgrader instance
+ * @param array $upgradeInfo extra information about the upgrade
+ */
+ public function upgraderProcessComplete(
+ /** @noinspection PhpUnusedParameterInspection */
+ $upgrader,
+ $upgradeInfo
+ ) {
+ //Cancel all further actions if the current version of PUC has been deleted or overwritten
+ //by a different version during the upgrade. If we try to do anything more in that situation,
+ //we could trigger a fatal error by trying to autoload a deleted class.
+ clearstatcache();
+ if (!file_exists(__FILE__)) {
+ $this->removeHooks();
+ $this->updateChecker->removeHooks();
+
+ return;
+ }
+
+ //Sanity check and limitation to relevant types.
+ if (
+ !is_array($upgradeInfo) || !isset($upgradeInfo['type'], $upgradeInfo['action'])
+ || 'update' !== $upgradeInfo['action'] || !in_array($upgradeInfo['type'], ['plugin', 'theme'])
+ ) {
+ return;
+ }
+
+ if (is_a($this->updateChecker, 'Lkn_Puc_Plugin_UpdateChecker')) {
+ if ('plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins'])) {
+ return;
+ }
+
+ //Themes pass in directory names in the information array, but plugins use the relative plugin path.
+ if (!in_array(
+ strtolower($this->updateChecker->directoryName),
+ array_map('dirname', array_map('strtolower', $upgradeInfo['plugins']))
+ )) {
+ return;
+ }
+ }
+
+ $this->maybeCheckForUpdates();
+ }
+
+ /**
+ * 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, ['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] = [
+ '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;
+ }
+
+ /**
+ * Remove most hooks added by the scheduler.
+ */
+ public function removeHooks() {
+ remove_filter('cron_schedules', [$this, '_addCustomSchedule']);
+ remove_action('admin_init', [$this, 'maybeCheckForUpdates']);
+ remove_action('load-update-core.php', [$this, 'maybeCheckForUpdates']);
+
+ if ($this->cronHook !== null) {
+ remove_action($this->cronHook, [$this, 'maybeCheckForUpdates']);
+ }
+ if (!empty($this->hourlyCheckHooks)) {
+ foreach ($this->hourlyCheckHooks as $hook) {
+ remove_action($hook, [$this, 'maybeCheckForUpdates']);
+ }
+ }
+ }
+ }
+
+endif;
diff --git a/plugin-updater/Puc/StateStore.php b/plugin-updater/Puc/StateStore.php
new file mode 100644
index 0000000..49725ca
--- /dev/null
+++ b/plugin-updater/Puc/StateStore.php
@@ -0,0 +1,231 @@
+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|Lkn_Puc_Update
+ */
+ public function getUpdate() {
+ $this->lazyLoad();
+
+ return $this->update;
+ }
+
+ /**
+ * @param Lkn_Puc_Update|null $update
+ * @return $this
+ */
+ public function setUpdate(Lkn_Puc_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 [];
+ }
+
+ /**
+ * Set translation updates.
+ *
+ * @param array $translationUpdates
+ */
+ public function setTranslations($translationUpdates) {
+ $this->lazyLoad();
+ if (isset($this->update)) {
+ $this->update->translations = $translationUpdates;
+ $this->save();
+ }
+ }
+
+ /**
+ * Saves the updated state of the plugin on the database
+ */
+ 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 (Lkn_Puc_Utils::startsWith($updateClass, $prefix)) {
+ $state->updateBaseClass = substr($updateClass, strlen($prefix));
+ }
+ }
+
+ update_site_option($this->optionName, $state);
+ $this->isLoaded = true;
+ }
+
+ /**
+ * Checks if the database already has a state
+ *
+ * @return $this
+ */
+ public function lazyLoad() {
+ if (!$this->isLoaded) {
+ $this->load();
+ }
+
+ return $this;
+ }
+
+ /**
+ * Load the state version
+ */
+ 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(Lkn_Puc_Utils::get($state, 'lastCheck', 0));
+ $this->checkedVersion = Lkn_Puc_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([$updateClass, 'fromObject'], $state->update);
+ }
+ }
+ }
+
+ /**
+ * Delete the option name from database
+ */
+ 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;
diff --git a/plugin-updater/Puc/Update.php b/plugin-updater/Puc/Update.php
new file mode 100644
index 0000000..d4fbafd
--- /dev/null
+++ b/plugin-updater/Puc/Update.php
@@ -0,0 +1,38 @@
+slug = $this->slug;
+ $update->new_version = $this->version;
+ $update->package = $this->download_url;
+
+ return $update;
+ }
+ }
+
+endif;
diff --git a/plugin-updater/Puc/UpdateChecker.php b/plugin-updater/Puc/UpdateChecker.php
new file mode 100644
index 0000000..425f265
--- /dev/null
+++ b/plugin-updater/Puc/UpdateChecker.php
@@ -0,0 +1,959 @@
+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->package = $this->createInstalledPackage();
+ $this->scheduler = $this->createScheduler($checkPeriod);
+ $this->upgraderStatus = new Lkn_Puc_UpgraderStatus();
+ $this->updateState = new Lkn_Puc_StateStore($this->optionName);
+
+ if (did_action('init')) {
+ $this->loadTextDomain();
+ } else {
+ add_action('init', [$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, [$this, 'injectUpdate']);
+
+ //Insert translation updates into the update list.
+ add_filter('site_transient_' . $this->updateTransient, [$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,
+ [$this, 'clearCachedTranslationUpdates']
+ );
+
+ //Rename the update directory to be the same as the existing directory.
+ if ($this->directoryName !== '.') {
+ add_filter('upgrader_source_selection', [$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', [$this, 'allowMetadataHost'], 10, 2);
+ }
+
+ /**
+ * Remove hooks that were added by this update checker instance.
+ */
+ public function removeHooks() {
+ remove_filter('site_transient_' . $this->updateTransient, [$this, 'injectUpdate']);
+ remove_filter('site_transient_' . $this->updateTransient, [$this, 'injectTranslationUpdates']);
+ remove_action(
+ 'delete_site_transient_' . $this->updateTransient,
+ [$this, 'clearCachedTranslationUpdates']
+ );
+
+ remove_filter('upgrader_source_selection', [$this, 'fixDirectoryName'], 10);
+ remove_filter('http_request_host_is_external', [$this, 'allowMetadataHost'], 10);
+
+ remove_action('init', [$this, 'loadTextDomain']);
+
+ if ($this->scheduler) {
+ $this->scheduler->removeHooks();
+ }
+ }
+
+ /**
+ * 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) {
+ if ($this->cachedMetadataHost === 0) {
+ $this->cachedMetadataHost = parse_url($this->metadataUrl, PHP_URL_HOST);
+ }
+
+ if (is_string($this->cachedMetadataHost) && (strtolower($host) === strtolower($this->cachedMetadataHost))) {
+ return true;
+ }
+
+ return $allow;
+ }
+
+ /**
+ * Create a package instance that represents this plugin or theme.
+ *
+ * @return Lkn_Puc_InstalledPackage
+ */
+ abstract protected function createInstalledPackage();
+
+ /**
+ * @return Lkn_Puc_InstalledPackage
+ */
+ public function getInstalledPackage() {
+ return $this->package;
+ }
+
+ /**
+ * 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 Lkn_Puc_Scheduler
+ */
+ abstract protected function createScheduler($checkPeriod);
+
+ /**
+ * Check for updates. The results are stored in the DB option specified in $optionName.
+ *
+ * @return Lkn_Puc_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 = [];
+ add_action('puc_api_error', [$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', [$this, 'collectApiErrors'], 10);
+
+ return $this->getUpdate();
+ }
+
+ /**
+ * Load the update checker state from the DB.
+ *
+ * @return Lkn_Puc_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 Lkn_Puc_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 Lkn_Puc_Update An instance of Update, or NULL when no updates are available.
+ */
+ abstract public function requestUpdate();
+
+ /**
+ * Filter the result of a requestUpdate() call.
+ *
+ * @param Lkn_Puc_Update|null $update
+ * @param array|WP_Error|null $httpResult The value returned by wp_remote_get(), if any.
+ * @return Lkn_Puc_Update
+ */
+ protected function filterUpdateResult($update, $httpResult = null) {
+ //Let plugins/themes modify the update.
+ $update = apply_filters($this->getUniqueName('request_update_result'), $update, $httpResult);
+
+ $this->fixSupportedWordpressVersion($update);
+
+ if (isset($update, $update->translations)) {
+ //Keep only those translation updates that apply to this site.
+ $update->translations = $this->filterApplicableTranslations($update->translations);
+ }
+
+ return $update;
+ }
+
+ /**
+ * The "Tested up to" field in the plugin metadata is supposed to be in the form of "major.minor",
+ * while WordPress core's list_plugin_updates() expects the $update->tested field to be an exact
+ * version, e.g. "major.minor.patch", to say it's compatible. In other case it shows
+ * "Compatibility: Unknown".
+ * The function mimics how wordpress.org API crafts the "tested" field out of "Tested up to".
+ *
+ * @param Lkn_Puc_Metadata|null $update
+ */
+ protected function fixSupportedWordpressVersion(Lkn_Puc_Metadata $update = null) {
+ if (!isset($update->tested) || !preg_match('/^\d++\.\d++$/', $update->tested)) {
+ return;
+ }
+
+ $actualWpVersions = [];
+
+ $wpVersion = $GLOBALS['wp_version'];
+
+ if (function_exists('get_core_updates')) {
+ $coreUpdates = get_core_updates();
+ if (is_array($coreUpdates)) {
+ foreach ($coreUpdates as $coreUpdate) {
+ if (isset($coreUpdate->current)) {
+ $actualWpVersions[] = $coreUpdate->current;
+ }
+ }
+ }
+ }
+
+ $actualWpVersions[] = $wpVersion;
+
+ $actualWpPatchNumber = null;
+ foreach ($actualWpVersions as $version) {
+ if (preg_match('/^(?P\d++\.\d++)(?:\.(?P\d++))?/', $version, $versionParts)) {
+ if ($versionParts['majorMinor'] === $update->tested) {
+ $patch = isset($versionParts['patch']) ? intval($versionParts['patch']) : 0;
+ if ($actualWpPatchNumber === null) {
+ $actualWpPatchNumber = $patch;
+ } else {
+ $actualWpPatchNumber = max($actualWpPatchNumber, $patch);
+ }
+ }
+ }
+ }
+ if ($actualWpPatchNumber === null) {
+ $actualWpPatchNumber = 999;
+ }
+
+ if ($actualWpPatchNumber > 0) {
+ $update->tested .= '.' . $actualWpPatchNumber;
+ }
+ }
+
+ /**
+ * Get the currently installed version of the plugin or theme.
+ *
+ * @return string|null Version number.
+ */
+ public function getInstalledVersion() {
+ return $this->package->getInstalledVersion();
+ }
+
+ /**
+ * Get the full path of the plugin or theme directory.
+ *
+ * @return string
+ */
+ public function getAbsoluteDirectoryPath() {
+ return $this->package->getAbsoluteDirectoryPath();
+ }
+
+ /**
+ * Trigger a PHP error, but only when $debugMode is enabled.
+ *
+ * @param string $message
+ * @param int $errorType
+ */
+ public 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[] = [
+ '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 update is passed to WordPress.
+ $updates = $this->addUpdateToList($updates, $update->toWpFormat());
+ } else {
+ //Clean up any stale update info.
+ $updates = $this->removeUpdateFromList($updates);
+ //Add a placeholder item to the "no_update" list to enable auto-update support.
+ //If we don't do this, the option to enable automatic updates will only show up
+ //when an update is available.
+ $updates = $this->addNoUpdateItem($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 = [];
+ }
+
+ $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;
+ }
+
+ /**
+ * See this post for more information:
+ * @link https://make.wordpress.org/core/2020/07/30/recommended-usage-of-the-updates-api-to-support-the-auto-updates-ui-for-plugins-and-themes-in-wordpress-5-5/
+ *
+ * @param stdClass|null $updates
+ * @return stdClass
+ */
+ protected function addNoUpdateItem($updates) {
+ if (!is_object($updates)) {
+ $updates = new stdClass();
+ $updates->response = [];
+ $updates->no_update = [];
+ } else {
+ if (!isset($updates->no_update)) {
+ $updates->no_update = [];
+ }
+ }
+
+ $updates->no_update[$this->getUpdateListKey()] = (object) $this->getNoUpdateItemFields();
+
+ return $updates;
+ }
+
+ /**
+ * Subclasses should override this method to add fields that are specific to plugins or themes.
+ * @return array
+ */
+ protected function getNoUpdateItemFields() {
+ return [
+ 'new_version' => $this->getInstalledVersion(),
+ 'url' => '',
+ 'package' => '',
+ 'requires_php' => '',
+ ];
+ }
+
+ /**
+ * 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 array $queryArgs Additional query arguments.
+ * @return array [Lkn_Puc_Metadata|null, array|WP_Error] A metadata instance and the value returned by wp_remote_get().
+ */
+ protected function requestMetadata($metaClass, $queryArgs = []) {
+ //Query args to append to the URL.
+ $queryArgs = array_merge(
+ [
+ 'installed_version' => strval($this->getInstalledVersion()),
+ 'php' => phpversion(),
+ 'locale' => get_locale(),
+ 's' => '1f685366b804ef443c1620469b6aea3f',
+ ],
+ $queryArgs
+ );
+
+ //Various options for the wp_remote_get() call.
+ $options = [
+ 'timeout' => 10, //seconds
+ 'headers' => [
+ 'Accept' => 'application/json',
+ ],
+ ];
+
+ //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);
+
+ //Try to parse the response
+ $status = $this->validateApiResponse($result);
+ $metadata = null;
+ if (!is_wp_error($status)) {
+ if (version_compare(PHP_VERSION, '5.3', '>=') && (strpos($metaClass, '\\') === false)) {
+ $metaClass = __NAMESPACE__ . '\\' . $metaClass;
+ }
+ $metadata = call_user_func([$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 [$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 = [];
+ 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 [];
+ }
+ $installedTranslations = wp_get_installed_translations($this->translationType . 's');
+ if (isset($installedTranslations[$this->directoryName])) {
+ $installedTranslations = $installedTranslations[$this->directoryName];
+ } else {
+ $installedTranslations = [];
+ }
+
+ 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 = [];
+ }
+
+ //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,
+ [$this, 'isNotMyTranslation']
+ ));
+
+ //Add our updates to the list.
+ foreach ($translationUpdates as $update) {
+ $convertedUpdate = array_merge(
+ [
+ '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([]);
+ }
+
+ /**
+ * 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 %s , 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…',
+ '' . basename($source) . ' ',
+ '' . $this->directoryName . ' '
+ ));
+
+ 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;
+ }
+ }
+
+endif;
diff --git a/plugin-updater/Puc/UpgraderStatus.php b/plugin-updater/Puc/UpgraderStatus.php
new file mode 100644
index 0000000..55a51ca
--- /dev/null
+++ b/plugin-updater/Puc/UpgraderStatus.php
@@ -0,0 +1,182 @@
+isBeingUpgraded('plugin', $pluginFile, $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 [null, null];
+ }
+
+ //Figure out which plugin or theme is being upgraded.
+ $pluginFile = null;
+
+ $skin = $upgrader->skin;
+ if ($skin instanceof Plugin_Upgrader_Skin) {
+ if (isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '')) {
+ $pluginFile = $skin->plugin;
+ }
+ } 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 ['plugin', $pluginFile];
+ }
+
+ return [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 = [];
+ 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';
+ } 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;
diff --git a/plugin-updater/Puc/Utils.php b/plugin-updater/Puc/Utils.php
new file mode 100644
index 0000000..0c2d3d3
--- /dev/null
+++ b/plugin-updater/Puc/Utils.php
@@ -0,0 +1,72 @@
+$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;
diff --git a/plugin-updater/README.md b/plugin-updater/README.md
new file mode 100644
index 0000000..aec93b7
--- /dev/null
+++ b/plugin-updater/README.md
@@ -0,0 +1,26 @@
+# plugin-updater
+
+Está é uma biblioteca PHP com o objetivo de atualizar automaticamente plugins que não são hospedados no site oficial do WordPress. Ela é dividida em duas pastas 'plugin-updater' corresponde a biblioteca que precisa ser importada pelo plugin, 'API' que corresponde as configurações do servidor de downloads.
+
+## Modo de uso
+
+Antes de adicionar o bloco de código ao seu plugin é importante que o servidor já esteja configurado para receber as requisições do mesmo, verifique a pasta API para mais informações.
+
+* Primeiro é necessário que a biblioteca de atualizações esteja na raíz do plugin;
+* Após isso é necessário que o seguinte bloco de código seja inserido no arquivo principal do seu plugin:
+
+```php
+ require_once __DIR__ . '/plugin-updater/plugin-update-checker.php';
+
+
+ function lkn_give_unique_plugin_slug_updater() {
+ return new Lkn_Puc_Plugin_UpdateChecker(
+ 'https://api.linknacional.com.br/linknac_dev/link_api_update.php?slug=give-visa',
+ __DIR__ . '/give-unique_plugin_slug.php',//(caso o plugin não precise de compatibilidade com ioncube utilize: __FILE__), //Full path to the main plugin file or functions.php.
+ 'give-unique_plugin_slug'
+ );
+ }
+
+lkn_give_unique_plugin_slug_updater();
+```
+Pronto agora o plugin-updater está devidamente configurado.
diff --git a/plugin-updater/languages/plugin-update-checker-ca.mo b/plugin-updater/languages/plugin-update-checker-ca.mo
new file mode 100644
index 0000000000000000000000000000000000000000..59645faba22e5f3b1358ef076a01d5a7fa3aa534
GIT binary patch
literal 1186
zcmZ`&%We}f6g5yD3JU~l7MF@jAn=eGUhPB?f>02mg$Po_u5xE?6T{RV*`7X-koW+0
zhy^>uFR+0P5@LzOC$M16M{p*S5}sDhoY=mPbM5P|$7Ws%jDx^&U;rEjo&)uG2OI_7
z0|a~qW`XZO7dWy8}I`73-}WF&`jfh1$+|or(n2@
z$6kD4Ca@&-k5_~^FyUI~c=Se`J*IW*s48<6*o(o49h3HCEM+5QhFsVosZFH|wN`K>
zR?K5#x6H%=Hi*EEd{CkCG&|>KMHn%aMK#ohf(`}GTqVO>w8_qEYsjusZ87I}jgak^
z1b=z=Y*pmY6Da4vZbKUgT;Ekp3VMIKk87Fp(ccPYmReZ*Oiw{rQQ
zQJGG}$>w0>q|R3V?m+e&tAI-6bvUP#wByS%j%9Lz;>&3}Inz$sZ5YaXys7Jor*;dn
zyi|6wjye#l~(4XI!Zv%K@v6lv>NTmKUcY;;7x~Srga|VW$KqCtXwwgL#J#*X-o9%M(OOP
zBClzLpCXloN)jJ<-gN!%O{
zB>(p8)gMt|<1=e`ScRtXSByfRLdUq(KfSFJ6!629vGE!UXnOYH)9c?7LY#*cWS6#%
cwcF+j&+0z~QHeLF5H1o+|4uN~nyX0s0EpISt^fc4
literal 0
HcmV?d00001
diff --git a/plugin-updater/languages/plugin-update-checker-ca.po b/plugin-updater/languages/plugin-update-checker-ca.po
new file mode 100644
index 0000000..36f3ad7
--- /dev/null
+++ b/plugin-updater/languages/plugin-update-checker-ca.po
@@ -0,0 +1,48 @@
+msgid ""
+msgstr ""
+"Project-Id-Version: plugin-update-checker\n"
+"POT-Creation-Date: 2017-11-24 17:02+0200\n"
+"PO-Revision-Date: 2019-09-25 18:15+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.2.3\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: ca\n"
+"X-Poedit-SearchPath-0: .\n"
+
+#: Puc/v4p3/Plugin/UpdateChecker.php:395
+msgid "Check for updates"
+msgstr "Comprova si hi ha actualitzacions"
+
+#: Puc/v4p3/Plugin/UpdateChecker.php:548
+#, php-format
+msgctxt "the plugin title"
+msgid "The %s plugin is up to date."
+msgstr "L’extensió %s està actualitzada."
+
+#: Puc/v4p3/Plugin/UpdateChecker.php:550
+#, php-format
+msgctxt "the plugin title"
+msgid "A new version of the %s plugin is available."
+msgstr "Una nova versió de l’extensió %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 "No s’ha pogut determinar si hi ha actualitzacions per a %s."
+
+#: Puc/v4p3/Plugin/UpdateChecker.php:558
+#, php-format
+msgid "Unknown update checker status \"%s\""
+msgstr "Estat del comprovador d’actualitzacions desconegut \"%s\""
+
+#: Puc/v4p3/Vcs/PluginUpdateChecker.php:95
+msgid "There is no changelog available."
+msgstr "No hi ha cap registre de canvis disponible."
diff --git a/plugin-updater/languages/plugin-update-checker-pt_BR.mo b/plugin-updater/languages/plugin-update-checker-pt_BR.mo
new file mode 100644
index 0000000000000000000000000000000000000000..d1c0f283287da07c7060255756947399fde75ca6
GIT binary patch
literal 1014
zcmZuv!EVz)6f{scgcF=V;_y_d5=dPW2P%rAAllGEMM|SKMcksreu>>WyVmYHZ4oE_
zfe%0&fCEQPT#)h`h+lzm97qtXGJgB)+1bhN{J6UG*2B02+yFYjW#BbXj*q|<;1fW=
zS6~_V4zz%ufGFqZJntKD3|vFMdZFTNpgW5oypn^Ib=kY}AEddv&Zz?~t
zX;s<@N5?eKhKf9vj;+^A*f6D*l%^<=YRH)$k{ru4lP@#&y+d`Z^og1+00#ed~o)yDXkxO01OB=CIb?>xs5u>EJ;;!s3t`_28bUuZiG31#98mK-BNl>mZ7K
z9;c<(|MMCZuOqD!JtLLPq|+v(S_kJ<$RUd!%h5s)ORm4UU)$Z;-J07B{Ccgem16~&
zvmAaLpSs(5CR5cc58qgJt;627SfBIC?FMYbmWp(os$od$FH={0As(}0Q~Bs>j#Ed0
zzwWQ&OVx@^X*riJ3CZ_s-K;P&6WiL1Y)A^Xh1Rwj&GPUtZQWG#fP!1i`T7H0n26hz
zt&l2Tf7GAy*@-r>?WER))bBU@-0Yv?7Y3`1XhDUgiIOgSh&r6qJltA3NF!-z!xb`1
zU&+ab$rmK?+2p;ZWb%%R(LxgA)aF`EK94!`y@Pq^C}taJg*2wI_Pr<5brLBa%W3dR
uv0NHSC{;9(zXh@CV~k{HTE@P&w?I3B7+Z&@l4Ogy;7B66h9le{qWB9G2Q7U7
literal 0
HcmV?d00001
diff --git a/plugin-updater/languages/plugin-update-checker-pt_BR.po b/plugin-updater/languages/plugin-update-checker-pt_BR.po
new file mode 100644
index 0000000..70a0f62
--- /dev/null
+++ b/plugin-updater/languages/plugin-update-checker-pt_BR.po
@@ -0,0 +1,48 @@
+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."
diff --git a/plugin-updater/languages/plugin-update-checker.pot b/plugin-updater/languages/plugin-update-checker.pot
new file mode 100644
index 0000000..99cc24c
--- /dev/null
+++ b/plugin-updater/languages/plugin-update-checker.pot
@@ -0,0 +1,49 @@
+#, fuzzy
+msgid ""
+msgstr ""
+"Project-Id-Version: plugin-update-checker\n"
+"POT-Creation-Date: 2020-08-08 14:36+0300\n"
+"PO-Revision-Date: 2016-01-10 20:59+0100\n"
+"Last-Translator: Tamás András Horváth \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.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/v4p11/Plugin/Ui.php:128
+msgid "Check for updates"
+msgstr ""
+
+#: Puc/v4p11/Plugin/Ui.php:213
+#, php-format
+msgctxt "the plugin title"
+msgid "The %s plugin is up to date."
+msgstr ""
+
+#: Puc/v4p11/Plugin/Ui.php:215
+#, php-format
+msgctxt "the plugin title"
+msgid "A new version of the %s plugin is available."
+msgstr ""
+
+#: Puc/v4p11/Plugin/Ui.php:217
+#, php-format
+msgctxt "the plugin title"
+msgid "Could not determine if updates are available for %s."
+msgstr ""
+
+#: Puc/v4p11/Plugin/Ui.php:223
+#, php-format
+msgid "Unknown update checker status \"%s\""
+msgstr ""
+
+#: Puc/v4p11/Vcs/PluginUpdateChecker.php:98
+msgid "There is no changelog available."
+msgstr ""
diff --git a/plugin-updater/license.txt b/plugin-updater/license.txt
new file mode 100644
index 0000000..be948f6
--- /dev/null
+++ b/plugin-updater/license.txt
@@ -0,0 +1,7 @@
+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.
diff --git a/plugin-updater/load-puc.php b/plugin-updater/load-puc.php
new file mode 100644
index 0000000..50ebff7
--- /dev/null
+++ b/plugin-updater/load-puc.php
@@ -0,0 +1,6 @@
+run();
}
run_wc_payment_invoice();
+
+/**
+ * Instance for the Plugin Updater lib
+ *
+ * @return Lkn_Puc_Plugin_UpdateChecker
+ */
+function lkn_woocommerce_invoice_payment_updater() {
+ return new Lkn_Puc_Plugin_UpdateChecker(
+ 'https://api.linknacional.com.br/app/u/link_api_update.php?slug=woocommerce-invoice-payment',
+ __FILE__,
+ 'woocommerce-invoice-payment'
+ );
+}
+
+lkn_woocommerce_invoice_payment_updater();
From 1043e8c43c0b79173c6dc8f2bbbf4af39e6c9de1 Mon Sep 17 00:00:00 2001
From: emanuellopess
Date: Thu, 31 Mar 2022 15:52:32 -0300
Subject: [PATCH 17/20] fix: Retirar classe desnecessaria
---
admin/class-wc-invoice-payment-table.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/admin/class-wc-invoice-payment-table.php b/admin/class-wc-invoice-payment-table.php
index 958cd0d..bc67082 100644
--- a/admin/class-wc-invoice-payment-table.php
+++ b/admin/class-wc-invoice-payment-table.php
@@ -1487,7 +1487,7 @@ public function handle_row_actions($item, $column_name, $primary) {
$editUrl = home_url('wp-admin/admin.php?page=edit-invoice&invoice=' . $item['lkn_wcip_id']);
$action = [];
- $action['edit'] = '' . __('Edit') . ' ';
+ $action['edit'] = '' . __('Edit') . ' ';
// $action['delete'] = '' . __('Delete') . ' ';
return $this->row_actions($action);
From e66ea67c9ebbc9213296f0bef766730a9d82dd82 Mon Sep 17 00:00:00 2001
From: emanuellopess
Date: Thu, 31 Mar 2022 16:32:23 -0300
Subject: [PATCH 18/20] feat: Implementado notice caso o WooCommerce esteja
desabilitado ou nao esteja instalado
---
...oice-payment-admin-missing-woocommerce.php | 33 ++++++++++++++++++
languages/wc-invoice-payment-pt_BR.mo | Bin 1381 -> 1620 bytes
languages/wc-invoice-payment-pt_BR.po | 11 +++++-
languages/wc-invoice-payment.pot | 11 +++++-
wc-invoice-payment.php | 11 ++++++
5 files changed, 64 insertions(+), 2 deletions(-)
create mode 100644 admin/partials/wc-invoice-payment-admin-missing-woocommerce.php
diff --git a/admin/partials/wc-invoice-payment-admin-missing-woocommerce.php b/admin/partials/wc-invoice-payment-admin-missing-woocommerce.php
new file mode 100644
index 0000000..231bd77
--- /dev/null
+++ b/admin/partials/wc-invoice-payment-admin-missing-woocommerce.php
@@ -0,0 +1,33 @@
+
+
+
+
WooCommerce Invoice Payment
+
+
+
+
+
+
+
diff --git a/languages/wc-invoice-payment-pt_BR.mo b/languages/wc-invoice-payment-pt_BR.mo
index 421e3cc0530e9f4647f519f4b82d3cce897f9469..106c9d845605da0ee42c2e6fe512a487a0e462a2 100644
GIT binary patch
literal 1620
zcmZXS&ub(_6vs=Aan~feCee+$kqWp+gRqMSJ%wZp0TTidg*{nx*G!spSB0+Xaf1i-
zWY~)b5xgq|4=S*DYXdSd044A7~m!NKAeT8&H7{b4C~L}Jp39y3V(pl!k?hT{sS(-f8b+q
z{t=~~gv$+Igs-x`37>-=O1?XA6@CI2;9WQae}qrKpP}TtfD-?AxB~xzqH~tZa=rj>
zz$GYkZNn?@78D&vQ0~3g@Ixs5_y|g#FQCNx21@*MD0N-HWq7YSpCQOotmmNQS%t5_
zm!bSOfKvYl@CA4ZCH@&Cg!&Fj9p6LA_ba>#e}kgu?`D6FLq63ad=0KZ$=eReA^n$e
znTeg_JmQh`SBCUgYHx?sBe})T$C=V^>5u+Elde7564G`P#d&+7gW1WZ6x7?
zb*t?`SZ!RY3**edj#c+jHc|R|7b;XqVngUxd48gU8QQcx>cR&-b!l7`*WSoN*MXq+
zOkvf2(<3U1RZ#n-boPKQBoRSP8SCro>>;mdy^dZdRfrx_)It5{o1UJi)E;v$NK50P
z)wv
zf0Vx7=;QLYHi(8s@fL>XhqBcL*tYUMGn3+McQGKfG*il1P8hH16gZs^jZSfNpEy4;qP~4|q8F#Bq8F4gnFi_$_T2SjTw~qF0-oVM-k_d;
zMty0F+c-wO_Xj!5r)xEwLDh+{N`0$yqR}6^8*SvUEp`550aT7z~53run();
+
+ add_action('admin_notices', 'lkn_wcip_woocommerce_missing_notice');
}
run_wc_payment_invoice();
@@ -95,3 +97,12 @@ function lkn_woocommerce_invoice_payment_updater() {
}
lkn_woocommerce_invoice_payment_updater();
+
+/**
+ * WooCommerce missing notice
+ *
+ * @return void
+ */
+function lkn_wcip_woocommerce_missing_notice() {
+ include_once dirname(__FILE__) . '/admin/partials/wc-invoice-payment-admin-missing-woocommerce.php';
+}
From c514279996ac8f38bb237da919b07580b1a982c9 Mon Sep 17 00:00:00 2001
From: emanuellopess
Date: Fri, 1 Apr 2022 15:35:32 -0300
Subject: [PATCH 19/20] =?UTF-8?q?refactor:=20Ajuste=20na=20tradu=C3=A7ao?=
=?UTF-8?q?=20do=20plugin?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
admin/class-wc-invoice-payment-admin.php | 2 +-
languages/wc-invoice-payment-pt_BR.mo | Bin 1620 -> 1685 bytes
languages/wc-invoice-payment-pt_BR.po | 5 ++++-
languages/wc-invoice-payment.pot | 3 +++
4 files changed, 8 insertions(+), 2 deletions(-)
diff --git a/admin/class-wc-invoice-payment-admin.php b/admin/class-wc-invoice-payment-admin.php
index 0793317..4e3ee5a 100644
--- a/admin/class-wc-invoice-payment-admin.php
+++ b/admin/class-wc-invoice-payment-admin.php
@@ -248,7 +248,7 @@ public function render_edit_invoice_page() {
if ($orderStatus === 'pending') {
?>
diff --git a/languages/wc-invoice-payment-pt_BR.mo b/languages/wc-invoice-payment-pt_BR.mo
index 106c9d845605da0ee42c2e6fe512a487a0e462a2..e8c2a022dc2eaae32dcf9fa76123a85deea0ccb8 100644
GIT binary patch
delta 659
zcmXxhKP*F06vy%N+M;OvsXr|(c>{wO2qMBnj7(xM7+#_kQPl{8se@HQQcY}3(m`VA
zViTjpBq9c3F_4HAiHPry_9VBT``*31=iKvdLxpheF%l>kktmOE>}5PSW)aN#%<6Fm
zgSdy)cvyZu!gijE7{Uvz!fWin8;s){wqVe2R)Yy_G|O4f|HMXcoP}v@#T<6x0V?qs
zcHudO@eTv{j1BmTO8kjR^n)>sut^2?qt=IT7{@R|eoHfH;zbUr$o5eikISB*x^s$3
zbcH(b9+lt;b;D0o;jR2x>wVaagQ!kU;V90d_U~eh{8nV5mRw>tUZE1bAZOYK>PFwF
zgPZt?ViZ-_0P6h=KWwo%oWKQC;z}roI;yB;@P#e^<^*R|jY4f!2Nddv4%dy8td60!
z>qaVu?*4uEHdK+7=*Um{;!doz=<9SsS#NtSnb~yHE1A_{cESXPCK5NjK{)ds(^b
delta 587
zcmXxhF-yZh7{>88Xri11#blHt+$p_dC|`7e}yMFq>dItN%}I4p&%M!Y1yb0*|qcF;?&j
zJ-o+pd_)BfQ2}olVTx+B#LHT*;3C#g2V27``L@Y~PHY?X;(q2K>PC)GLFcFq6I8$r
z>SRN#<5#xsvB@OQJ}Rh<%ea90ZVPn-2RPed(qp243uF(wMxEpq75I!HzM>lX%zpP-
zWNHDfVuT9Lhe8^0>V)gMPYvCtj+zg(uO$6}W0dZ-%fm4O#c9}MKELl
diff --git a/languages/wc-invoice-payment-pt_BR.po b/languages/wc-invoice-payment-pt_BR.po
index 110f594..3993d2e 100644
--- a/languages/wc-invoice-payment-pt_BR.po
+++ b/languages/wc-invoice-payment-pt_BR.po
@@ -78,4 +78,7 @@ msgid "Active WooCommerce"
msgstr "Ativar WooCommerce"
msgid "Install WooCommerce"
-msgstr "Instalar WooCommerce"
\ No newline at end of file
+msgstr "Instalar WooCommerce"
+
+msgid "Invoice payment link"
+msgstr "Link de pagamento da fatura"
\ No newline at end of file
diff --git a/languages/wc-invoice-payment.pot b/languages/wc-invoice-payment.pot
index fecb270..f728b36 100644
--- a/languages/wc-invoice-payment.pot
+++ b/languages/wc-invoice-payment.pot
@@ -79,3 +79,6 @@ msgstr ""
msgid "Install WooCommerce"
msgstr ""
+
+msgid "Invoice payment link"
+msgstr ""
\ No newline at end of file
From fab37c5b23126794f4f794b7190164bdadf5804e Mon Sep 17 00:00:00 2001
From: emanuellopess
Date: Fri, 1 Apr 2022 16:09:35 -0300
Subject: [PATCH 20/20] fix: Notice de WooCommerce desativado nao aparece a
todo momento
---
.../wc-invoice-payment-admin-missing-woocommerce.php | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/admin/partials/wc-invoice-payment-admin-missing-woocommerce.php b/admin/partials/wc-invoice-payment-admin-missing-woocommerce.php
index 231bd77..aa6c1e1 100644
--- a/admin/partials/wc-invoice-payment-admin-missing-woocommerce.php
+++ b/admin/partials/wc-invoice-payment-admin-missing-woocommerce.php
@@ -14,7 +14,9 @@
$is_installed = !empty($all_plugins['woocommerce/woocommerce.php']);
}
-?>
+// Verifies if WooCommerce is inactive
+if (!class_exists('WooCommerce')) {
+ ?>
WooCommerce Invoice Payment
@@ -26,8 +28,10 @@
$url = wp_nonce_url(self_admin_url('update.php?action=install-plugin&plugin=woocommerce'), 'install-plugin_woocommerce');
} else {
$url = 'http://wordpress.org/plugins/woocommerce/';
- }
- ?>
+ } ?>
+
\ No newline at end of file