12345678, * 'file' => __FILE__, // plugin main file — for a theme: 'theme' => 'my-theme' * 'settings_page' => true, // adds a licence screen under Settings * ]); * * Docs: https://sellmycode.net/api-docs/licence-sdk */ if (!defined('ABSPATH')) { exit; } require_once __DIR__ . '/SellMyCodeLicense.php'; if (!class_exists('SellMyCodeWpUpdater', false)) { class SellMyCodeWpUpdater { const VERSION = '1.0.0'; /** how long a check result is reused before asking the server again */ const CACHE_TTL = 21600; /** @var array */ private $cfg; /** @var int */ private $itemId; /** @var bool */ private $isTheme; /** @var string plugin basename ("my-plugin/my-plugin.php") or theme stylesheet */ private $id; /** @var string */ private $slug; /** @var string */ private $name; /** @var string */ private $version; /** @var string */ private $option; /** @var SellMyCodeLicense|null */ private $license; /** * @param array $cfg * item_id (int, required) your item's ID on SellMyCode * file (string) plugin main file (__FILE__) * theme (string) theme folder name, instead of file * name (string) shown on the licence screen; defaults to the plugin/theme name * purchase_code (string|callable) when your product stores the code itself; otherwise the licence screen does * settings_page (bool|string) true = under Settings, or a parent menu slug * allow_unverified (bool) install packages that have no checksum (default false) * public_keys (array) override the keys bundled in SellMyCodeLicense.php * transport (callable) custom HTTP; defaults to the WordPress HTTP API */ public function __construct(array $cfg) { $this->cfg = $cfg; $this->itemId = (int) ($cfg['item_id'] ?? 0); $this->isTheme = !empty($cfg['theme']); $this->option = 'smc_license_' . $this->itemId; if ($this->itemId < 1 || (!$this->isTheme && empty($cfg['file']))) { return; } if ($this->isTheme) { $this->id = (string) $cfg['theme']; $this->slug = $this->id; $theme = wp_get_theme($this->id); $this->version = (string) $theme->get('Version'); $this->name = (string) ($cfg['name'] ?? $theme->get('Name')); add_filter('pre_set_site_transient_update_themes', [$this, 'inject']); } else { $this->id = plugin_basename($cfg['file']); $this->slug = dirname($this->id) !== '.' ? dirname($this->id) : basename($this->id, '.php'); $data = get_file_data($cfg['file'], ['Version' => 'Version', 'Name' => 'Plugin Name']); $this->version = (string) $data['Version']; $this->name = (string) ($cfg['name'] ?? $data['Name']); add_filter('pre_set_site_transient_update_plugins', [$this, 'inject']); add_filter('plugins_api', [$this, 'info'], 20, 3); add_action('in_plugin_update_message-' . $this->id, [$this, 'rowNotice'], 10, 2); } add_filter('upgrader_pre_download', [$this, 'download'], 10, 4); add_action('upgrader_process_complete', [$this, 'flush'], 10, 0); if (!empty($cfg['settings_page'])) { add_action('admin_menu', [$this, 'menu']); add_action('admin_post_' . $this->option, [$this, 'save']); } } /** the licence client, for your own checks: $updater->license()->isLicensed() */ public function license(): SellMyCodeLicense { if (!$this->license) { $option = $this->option; $config = [ 'item_id' => $this->itemId, 'purchase_code' => $this->purchaseCode(), 'domain' => (string) wp_parse_url(is_multisite() ? network_home_url() : home_url(), PHP_URL_HOST), 'allow_unverified' => !empty($this->cfg['allow_unverified']), 'transport' => $this->cfg['transport'] ?? [$this, 'http'], 'storage' => [ 'get' => function () use ($option) { $v = get_option($option . '_state'); return is_array($v) ? $v : null; }, 'set' => function ($state) use ($option) { if ($state === null) { delete_option($option . '_state'); } else { update_option($option . '_state', $state, false); } }, ], ]; if (!empty($this->cfg['public_keys'])) { $config['public_keys'] = $this->cfg['public_keys']; } $this->license = new SellMyCodeLicense($config); } return $this->license; } /** requests go through the WordPress HTTP API, so proxies and WordPress's CA bundle apply */ public function http(string $method, string $url, ?string $json, ?string $sink): array { $args = [ 'method' => $method, 'timeout' => $sink ? 300 : 15, 'redirection' => $sink ? 5 : 0, 'user-agent' => 'SellMyCodeWpUpdater/' . self::VERSION, 'headers' => ['Accept' => 'application/json'], ]; if ($json !== null) { $args['headers']['Content-Type'] = 'application/json'; $args['body'] = $json; } if ($sink) { $args['stream'] = true; $args['filename'] = $sink; } $res = wp_remote_request($url, $args); if (is_wp_error($res)) { return ['status' => 0, 'body' => '']; } return ['status' => (int) wp_remote_retrieve_response_code($res), 'body' => $sink ? '' : (string) wp_remote_retrieve_body($res)]; } public function purchaseCode(): string { if (isset($this->cfg['purchase_code'])) { $code = is_callable($this->cfg['purchase_code']) ? call_user_func($this->cfg['purchase_code']) : $this->cfg['purchase_code']; return trim((string) $code); } return trim((string) get_option($this->option . '_code', '')); } /** the last update check, refreshed every CACHE_TTL or when WordPress forces a check */ private function check(bool $fresh = false): ?array { if (!$this->license()->hasActivation()) { return null; } $key = $this->option . '_check'; $cached = get_site_transient($key); if (!$fresh && is_array($cached) && ($cached['for'] ?? '') === $this->version) { return $cached; } $a = $this->license()->checkUpdate($this->version); $result = [ 'for' => $this->version, 'code' => $a->code, 'message' => $a->message, 'latest' => $a->latestVersion, 'available' => $a->updateAvailable, 'integrity' => $a->package['integrity'] ?? null, 'changelog' => $a->changelog, 'renew_url' => $a->renewUrl, 'url' => $a->get('item.url'), ]; set_site_transient($key, $result, $a->offline ? 1800 : self::CACHE_TTL); return $result; } public function flush(): void { delete_site_transient($this->option . '_check'); } /** a stand-in package URL; the real, short-lived link is fetched in download() */ private function marker(): string { return 'https://sellmycode.net/api/license/update?smc_item=' . $this->itemId; } private function installable(array $c): bool { return $c['available'] && ($c['integrity'] === 'sha256' || !empty($this->cfg['allow_unverified'])); } /** add this item to WordPress's update list */ public function inject($transient) { if (!is_object($transient)) { return $transient; } $c = $this->check(isset($_GET['force-check'])); if (!$c) { return $transient; } $newer = $c['latest'] && version_compare($this->version, $c['latest'], '<'); $package = $this->installable($c) ? $this->marker() : ''; if ($this->isTheme) { $entry = [ 'theme' => $this->id, 'new_version' => $newer ? $c['latest'] : $this->version, 'url' => (string) $c['url'], 'package' => $package, ]; if ($newer) { $transient->response[$this->id] = $entry; } else { $transient->no_update[$this->id] = $entry; } return $transient; } $entry = (object) [ 'id' => 'sellmycode-' . $this->itemId, 'slug' => $this->slug, 'plugin' => $this->id, 'new_version' => $newer ? $c['latest'] : $this->version, 'url' => (string) $c['url'], 'package' => $package, ]; if ($newer) { $transient->response[$this->id] = $entry; } else { $transient->no_update[$this->id] = $entry; } return $transient; } /** fetch the real package when WordPress installs the update, verified against the signed checksum */ public function download($reply, $package, $upgrader = null, $hookExtra = []) { if ($reply !== false || $package !== $this->marker()) { return $reply; } $answer = $this->license()->checkUpdate($this->version); $this->flush(); if (!$answer->updateAvailable) { return new WP_Error('smc_' . $answer->code, $answer->message ?: 'No update can be downloaded for this licence right now.'); } try { return $this->license()->downloadUpdate($answer, get_temp_dir()); } catch (SellMyCodeLicenseException $e) { return new WP_Error('smc_' . $e->reason, $e->getMessage()); } } /** the "View version details" popup */ public function info($result, $action, $args) { if ($action !== 'plugin_information' || !isset($args->slug) || $args->slug !== $this->slug) { return $result; } $c = $this->check() ?: []; $log = $c['changelog'] ?? null; return (object) [ 'name' => $this->name, 'slug' => $this->slug, 'version' => $c['latest'] ?? $this->version, 'homepage' => (string) ($c['url'] ?? ''), 'download_link' => '', 'last_updated' => $log['released_at'] ?? '', 'sections' => [ 'changelog' => $log ? '

' . esc_html((string) $log['version']) . '

' . wpautop(esc_html((string) $log['body'])) : '', ], ]; } /** why "Update now" is missing, under the plugin row */ public function rowNotice($pluginData, $response): void { $c = $this->check(); if (!$c) { return; } if ($c['code'] === 'update_window_expired' && $c['renew_url']) { echo ' ' . esc_html('Renew your update period to install it.') . ''; } elseif ($c['available'] && !$this->installable($c)) { echo ' ' . esc_html('Download this version from your SellMyCode library.'); } } public function menu(): void { $parent = is_string($this->cfg['settings_page']) ? $this->cfg['settings_page'] : 'options-general.php'; add_submenu_page($parent, $this->name . ' licence', $this->name . ' licence', 'manage_options', $this->option, [$this, 'page']); } public function page(): void { if (!current_user_can('manage_options')) { return; } $license = $this->license(); $code = $this->purchaseCode(); $last = $license->lastAnswer(); $notice = get_transient($this->option . '_notice_' . get_current_user_id()); delete_transient($this->option . '_notice_' . get_current_user_id()); $managed = isset($this->cfg['purchase_code']); echo '

' . esc_html($this->name . ' licence') . '

'; if (is_array($notice)) { echo '

' . esc_html($notice['text']) . '

'; } foreach (SellMyCodeLicense::requirements() as $missing) { echo '

' . esc_html('Missing: ' . $missing) . '

'; } echo '
'; echo ''; wp_nonce_field($this->option); echo ''; echo ''; echo ''; echo ''; if ($license->hasActivation()) { submit_button('Deactivate this site', 'secondary', 'smc_deactivate', false); } else { submit_button('Activate', 'primary', 'smc_activate', false); } echo '
'; } public function save(): void { if (!current_user_can('manage_options')) { wp_die(esc_html('You are not allowed to do this.'), 403); } check_admin_referer($this->option); if (isset($_POST['smc_activate'])) { if (!isset($this->cfg['purchase_code'])) { $code = trim(sanitize_text_field(wp_unslash($_POST['purchase_code'] ?? ''))); if (!preg_match('/^[A-Za-z0-9-]{8,64}$/', $code)) { $this->notice(false, 'That does not look like a purchase code.'); $this->back(); } update_option($this->option . '_code', $code, false); $this->license = null; } $a = $this->license()->activate(); $this->flush(); if ($a->success && !$this->license()->hasActivation()) { $this->notice(false, 'This site is already active, but its activation token was lost. Ask the item author to revoke this site, then activate again.'); } else { $this->notice($a->success, $a->success ? 'Licence activated.' : ($a->message ?: 'Activation failed (' . $a->code . ').')); } } elseif (isset($_POST['smc_deactivate'])) { $a = $this->license()->deactivate(); $this->flush(); $this->notice($a->success, $a->success ? 'This site was deactivated. It keeps its slot and can be activated again.' : ($a->message ?: 'Deactivation failed (' . $a->code . ').')); } $this->back(); } private function notice(bool $ok, string $text): void { set_transient($this->option . '_notice_' . get_current_user_id(), ['ok' => $ok, 'text' => $text], 60); } private function back(): void { $parent = is_string($this->cfg['settings_page'] ?? null) ? $this->cfg['settings_page'] : 'options-general.php'; $url = strpos($parent, '.php') !== false ? admin_url($parent . '?page=' . $this->option) : admin_url('admin.php?page=' . $this->option); wp_safe_redirect($url); exit; } } }