__FILE__, // your main plugin file * 'public_key' => 'YOUR_PUBLIC_KEY', // safe to ship * 'product_id' => 'YOUR_PRODUCT_ID', * 'download_hosts' => array( 'downloads.example.com' ), // where your update zips are * ) ); * if ( $my_plugin_license->is_licensed() ) { ... } * * For automatic updates, add "Update URI: https://example.com/my-plugin" (your own * domain) to your plugin's header. Needs WordPress 5.8 and PHP 7.4. Not for plugins * that are hosted on wordpress.org, which have their own rules for updates. * * The class name carries the version, so two plugins can ship different versions. */ defined( 'ABSPATH' ) || exit; if ( ! class_exists( 'Licers_WP_1_0_0', false ) ) : final class Licers_WP_1_0_0 { const VERSION = '1.0.0'; /** A signed yes is good for this long without a new one (a server outage, a blocked cron). */ const GRACE = 1209600; // 14 days /** Ask again this often. */ const EVERY = 43200; // 12 hours private $file, $base, $slug, $pk, $product, $hosts, $api, $name, $version, $update_host, $option, $memo, $hook; /** @return self */ public static function register( array $c ) { return new self( $c ); } private function __construct( array $c ) { $this->file = (string) $c['file']; $this->base = plugin_basename( $this->file ); $this->slug = strpos( $this->base, '/' ) !== false ? dirname( $this->base ) : basename( $this->base, '.php' ); $raw = base64_decode( isset( $c['public_key'] ) ? trim( (string) $c['public_key'] ) : '', true ); $this->pk = is_string( $raw ) && strlen( $raw ) === 32 ? $raw : ''; $this->product = isset( $c['product_id'] ) ? (string) $c['product_id'] : ''; $this->hosts = isset( $c['download_hosts'] ) ? array_map( 'strtolower', (array) $c['download_hosts'] ) : array(); $this->api = isset( $c['api_url'] ) ? rtrim( (string) $c['api_url'], '/' ) : 'https://licers.com'; $h = get_file_data( $this->file, array( 'n' => 'Plugin Name', 'v' => 'Version', 'u' => 'Update URI' ) ); $this->name = isset( $c['name'] ) ? (string) $c['name'] : ( $h['n'] ? $h['n'] : $this->slug ); $this->version = isset( $c['version'] ) ? (string) $c['version'] : $h['v']; $host = $h['u'] ? wp_parse_url( $h['u'], PHP_URL_HOST ) : ''; $this->update_host = is_string( $host ) ? strtolower( $host ) : ''; $this->option = 'licers_' . substr( md5( $this->base ), 0, 12 ); $this->hook = $this->option . '_check'; add_action( 'admin_menu', array( $this, 'menu' ) ); add_action( 'admin_post_' . $this->option, array( $this, 'save' ) ); add_filter( 'plugin_action_links_' . $this->base, array( $this, 'link' ) ); add_action( $this->hook, array( $this, 'check' ) ); add_action( 'admin_init', array( $this, 'schedule' ) ); register_deactivation_hook( $this->file, array( $this, 'unschedule' ) ); if ( '' !== $this->update_host && '' !== $this->product ) { add_filter( 'update_plugins_' . $this->update_host, array( $this, 'update' ), 10, 3 ); add_filter( 'plugins_api', array( $this, 'details' ), 20, 3 ); } } // ---- for your plugin -------------------------------------------------------- /** A signed yes for this site that has not expired. No network. */ public function is_licensed() { return null !== $this->answer(); } /** A signed entitlement, for example feature( 'pro' ). No network. */ public function feature( $name, $default = null ) { $a = $this->answer(); return null !== $a && array_key_exists( $name, $a['features'] ) ? $a['features'][ $name ] : $default; } /** @return array{licensed:bool,message:string,expires_at:?string,has_key:bool} */ public function status() { $s = $this->stored(); $a = $this->answer(); return array( 'licensed' => null !== $a, 'message' => null !== $a ? '' : ( isset( $s['message'] ) ? (string) $s['message'] : '' ), 'expires_at' => null !== $a ? $a['expires_at'] : null, 'has_key' => ! empty( $s['key'] ), ); } /** The address of the license page. */ public function page_url() { return admin_url( 'options-general.php?page=' . $this->option ); } /** Forget everything. Call it from uninstall.php. */ public static function forget( $plugin_basename ) { $o = 'licers_' . substr( md5( $plugin_basename ), 0, 12 ); delete_option( $o ); delete_transient( $o . '_update' ); wp_clear_scheduled_hook( $o . '_check' ); } // ---- the license -------------------------------------------------------------- private function stored() { $s = get_option( $this->option ); return is_array( $s ) ? $s : array(); } private function store( array $s ) { $this->memo = null; update_option( $this->option, $s, false ); delete_transient( $this->option . '_update' ); } /** One website is one device. */ private function device() { $p = wp_parse_url( home_url() ); $host = isset( $p['host'] ) ? strtolower( rtrim( $p['host'], '.' ) ) : 'unknown'; if ( 0 === strpos( $host, 'www.' ) && substr_count( $host, '.' ) > 1 ) { $host = substr( $host, 4 ); } return substr( 'site:' . $host . rtrim( isset( $p['path'] ) ? $p['path'] : '', '/' ), 0, 200 ); } /** The stored answer, its signature checked again: editing the database can't make a license. */ private function answer() { if ( null === $this->memo ) { $s = $this->stored(); $this->memo = isset( $s['answer'] ) && is_array( $s['answer'] ) ? $this->verified( $s['answer'], $this->device() ) : false; } if ( ! $this->memo ) { return null; } $now = time(); $a = $this->memo; if ( $a['issued_at'] > $now + 300 || $now - $a['issued_at'] > self::GRACE ) { return null; } return null !== $a['expires_at'] && strtotime( $a['expires_at'] ) <= $now ? null : $a; } /** @return array|false */ private function verified( array $d, $device ) { if ( ! isset( $d['issued_at'], $d['signature'], $d['product_id'] ) || ! is_int( $d['issued_at'] ) || (string) $d['product_id'] !== $this->product ) { return false; } $msg = implode( '|', array( 'pylicense.v2', $this->part( $d, 'product_id' ), $device, $this->part( $d, 'expires_at' ), $this->part( $d, 'nonce' ), (string) $d['issued_at'], $this->part( $d, 'features_b64' ) ) ); if ( ! $this->signature( $msg, $d['signature'] ) ) { return false; } $features = array(); if ( '' !== $this->part( $d, 'features_b64' ) ) { $text = base64_decode( $d['features_b64'], true ); $features = is_string( $text ) ? json_decode( $text, true ) : null; if ( ! is_array( $features ) ) { return false; } } $expires = $this->part( $d, 'expires_at' ); return array( 'features' => $features, 'expires_at' => '' === $expires ? null : $expires, 'issued_at' => $d['issued_at'] ); } private function part( array $d, $k ) { $v = isset( $d[ $k ] ) ? $d[ $k ] : null; return is_bool( $v ) ? ( $v ? '1' : '0' ) : ( is_scalar( $v ) ? (string) $v : '' ); } private function signature( $msg, $sig ) { $raw = is_string( $sig ) ? base64_decode( $sig, true ) : false; // WordPress brings its own copy of these functions when the extension is missing. if ( '' === $this->pk || ! is_string( $raw ) || 64 !== strlen( $raw ) || ! function_exists( 'sodium_crypto_sign_verify_detached' ) ) { return false; } try { return sodium_crypto_sign_verify_detached( $raw, $msg, $this->pk ); } catch ( Exception $e ) { return false; } catch ( Error $e ) { return false; } } /** @return array{0:int,1:array} 0 = no usable answer */ private function post( $path, array $body ) { $r = wp_remote_post( $this->api . $path, array( 'timeout' => 10, 'redirection' => 0, // the body carries the license key 'sslverify' => true, 'limit_response_size' => 1048576, 'user-agent' => 'licers-wordpress/' . self::VERSION, 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json' ), 'body' => wp_json_encode( $body ), ) ); if ( is_wp_error( $r ) ) { return array( 0, array() ); } $code = (int) wp_remote_retrieve_response_code( $r ); $d = json_decode( wp_remote_retrieve_body( $r ), true ); // An outage, a redirect or the page of a proxy is no verdict on the key. return $code >= 500 || $code < 200 || ( $code >= 300 && $code < 400 ) || 429 === $code || ! is_array( $d ) ? array( 0, array() ) : array( $code, $d ); } /** @return array{ok:bool,network:bool,message:string,answer:?array} */ private function ask( $key ) { $n = bin2hex( random_bytes( 8 ) ); $device = $this->device(); list( $code, $d ) = $this->post( '/api/v1/validate', array( 'key' => $key, 'hwid' => $device, 'nonce' => $n, 'device_name' => substr( $device, 5, 100 ), 'platform' => 'WordPress ' . get_bloginfo( 'version' ), 'app_version' => substr( (string) $this->version, 0, 40 ) ) ); if ( 0 === $code ) { return array( 'ok' => false, 'network' => true, 'message' => __( 'The license server could not be reached. Please try again later.' ), 'answer' => null ); } if ( 200 !== $code || ! isset( $d['valid'] ) || true !== $d['valid'] ) { return array( 'ok' => false, 'network' => false, 'message' => isset( $d['error'] ) && is_string( $d['error'] ) ? substr( wp_strip_all_tags( $d['error'] ), 0, 300 ) : __( 'This license key is not valid.' ), 'answer' => null ); } if ( isset( $d['nonce'] ) && $d['nonce'] === $n && false !== $this->verified( $d, $device ) ) { $keep = array(); foreach ( array( 'product_id', 'expires_at', 'nonce', 'issued_at', 'features_b64', 'signature' ) as $f ) { $keep[ $f ] = isset( $d[ $f ] ) ? $d[ $f ] : null; } return array( 'ok' => true, 'network' => false, 'message' => '', 'answer' => $keep ); } $other = isset( $d['product_id'] ) && (string) $d['product_id'] !== $this->product; return array( 'ok' => false, 'network' => false, 'message' => $other ? __( 'This license key is for a different product.' ) : __( 'The answer of the license server could not be verified.' ), 'answer' => null ); } /** Check a new key and keep it if it is good. A refused key never replaces the stored one. */ public function activate( $key ) { $key = trim( (string) $key ); if ( '' === $key || strlen( $key ) > 200 ) { return array( 'ok' => false, 'network' => false, 'message' => __( 'Enter a license key.' ), 'answer' => null ); } $r = $this->ask( $key ); if ( $r['ok'] ) { $this->store( array( 'key' => $key, 'answer' => $r['answer'], 'checked' => time(), 'message' => '' ) ); } return $r; } /** Check the stored key again (twice a day by itself). */ public function check() { $s = $this->stored(); if ( empty( $s['key'] ) ) { return; } $r = $this->ask( $s['key'] ); $s['checked'] = time(); if ( $r['ok'] ) { $s['answer'] = $r['answer']; } elseif ( ! $r['network'] ) { unset( $s['answer'] ); } $s['message'] = $r['message']; $this->store( $s ); } public function schedule() { $s = $this->stored(); if ( empty( $s['key'] ) ) { wp_clear_scheduled_hook( $this->hook ); return; } if ( ! wp_next_scheduled( $this->hook ) ) { wp_schedule_event( time() + wp_rand( 3600, self::EVERY ), 'twicedaily', $this->hook ); } } public function unschedule() { wp_clear_scheduled_hook( $this->hook ); } // ---- updates ----------------------------------------------------------------------- /** The signed answer about the newest release, asked for at most once an hour. */ private function release() { $s = $this->stored(); if ( empty( $s['key'] ) ) { return null; } $c = get_transient( $this->option . '_update' ); if ( is_array( $c ) ) { return isset( $c['version'] ) ? $c : null; } $n = bin2hex( random_bytes( 8 ) ); list( $code, $d ) = $this->post( '/api/v1/update', array( 'key' => $s['key'], 'current_version' => (string) $this->version, 'channel' => 'stable', 'nonce' => $n ) ); $out = array(); if ( 200 === $code && isset( $d['issued_at'], $d['signature'], $d['nonce'], $d['version'] ) && is_int( $d['issued_at'] ) && $d['nonce'] === $n && $this->part( $d, 'product_id' ) === $this->product ) { $msg = implode( '|', array( 'pylicense.update.v1', $this->product, 'stable', $this->part( $d, 'update_available' ), $this->part( $d, 'version' ), $this->part( $d, 'filename' ), (string) (int) $this->part( $d, 'size' ), $n, (string) $d['issued_at'] ) ); if ( $this->signature( $msg, $d['signature'] ) && preg_match( '/^[0-9A-Za-z.+-]{1,40}$/', (string) $d['version'] ) ) { $out = array( 'version' => (string) $d['version'], 'package' => $this->package( isset( $d['download_url'] ) ? $d['download_url'] : '' ), 'notes' => isset( $d['notes'] ) && is_string( $d['notes'] ) ? substr( $d['notes'], 0, 20000 ) : '' ); } } set_transient( $this->option . '_update', $out, $out ? HOUR_IN_SECONDS : 10 * MINUTE_IN_SECONDS ); return $out ? $out : null; } /** The link is not covered by the signature, so only https links to your own hosts are used. */ private function package( $url ) { $p = is_string( $url ) ? wp_parse_url( $url ) : false; return is_array( $p ) && isset( $p['scheme'], $p['host'] ) && 'https' === strtolower( $p['scheme'] ) && ! isset( $p['user'] ) && ! isset( $p['pass'] ) && ( ! isset( $p['port'] ) || 443 === $p['port'] ) && in_array( strtolower( $p['host'] ), $this->hosts, true ) && esc_url_raw( $url ) === $url ? $url : ''; } public function update( $update, $data, $file ) { if ( $file !== $this->base ) { return $update; } $r = $this->release(); if ( null === $r ) { return $update; } // Also when it is not newer: WordPress then offers the automatic update switch. return array( 'id' => $this->update_host . '/' . $this->slug, 'slug' => $this->slug, 'version' => $r['version'], 'url' => isset( $data['PluginURI'] ) ? esc_url_raw( $data['PluginURI'] ) : '', 'package' => version_compare( $r['version'], (string) $this->version, '>' ) ? $r['package'] : '' ); } public function details( $result, $action, $args ) { if ( 'plugin_information' !== $action || ! isset( $args->slug ) || $args->slug !== $this->slug ) { return $result; } $r = $this->release(); if ( null === $r ) { return $result; } return (object) array( 'name' => $this->name, 'slug' => $this->slug, 'version' => $r['version'], 'download_link' => $r['package'], 'sections' => array( 'changelog' => '' === $r['notes'] ? esc_html__( 'No notes.' ) : wp_kses_post( wpautop( esc_html( $r['notes'] ) ) ) ) ); } // ---- the license page ----------------------------------------------------------------- public function menu() { /* translators: %s: plugin name */ add_options_page( sprintf( __( '%s license' ), $this->name ), sprintf( __( '%s license' ), $this->name ), 'manage_options', $this->option, array( $this, 'page' ) ); } public function link( $links ) { if ( current_user_can( 'manage_options' ) ) { array_unshift( $links, '' . esc_html( $this->is_licensed() ? __( 'License' ) : __( 'Enter license key' ) ) . '' ); } return $links; } public function save() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You are not allowed to do this.' ), '', array( 'response' => 403 ) ); } check_admin_referer( $this->option ); $do = isset( $_POST['licers_do'] ) && is_string( $_POST['licers_do'] ) ? sanitize_key( wp_unslash( $_POST['licers_do'] ) ) : ''; $msg = ''; if ( 'activate' === $do ) { $r = $this->activate( isset( $_POST['licers_key'] ) && is_string( $_POST['licers_key'] ) ? sanitize_text_field( wp_unslash( $_POST['licers_key'] ) ) : '' ); $msg = $r['message']; } elseif ( 'check' === $do ) { $this->check(); } elseif ( 'remove' === $do ) { $this->store( array() ); } if ( '' !== $msg ) { set_transient( $this->option . '_msg_' . get_current_user_id(), $msg, MINUTE_IN_SECONDS ); } wp_safe_redirect( $this->page_url() ); exit; } public function page() { if ( ! current_user_can( 'manage_options' ) ) { return; } $s = $this->stored(); $st = $this->status(); $t = $this->option . '_msg_' . get_current_user_id(); $msg = get_transient( $t ); delete_transient( $t ); $hint = ! empty( $s['key'] ) ? '••••-' . substr( $s['key'], -4 ) : ''; echo '

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

'; if ( is_string( $msg ) && '' !== $msg ) { echo '

' . esc_html( $msg ) . '

'; } if ( $st['licensed'] ) { /* translators: %s: date */ $until = $st['expires_at'] ? sprintf( __( 'Valid until %s.' ), wp_date( get_option( 'date_format' ), strtotime( $st['expires_at'] ) ) ) : __( 'It does not expire.' ); echo '

' . esc_html( __( 'This site is licensed.' ) . ' ' . $until ) . '

'; } elseif ( '' !== $st['message'] ) { echo '

' . esc_html( $st['message'] ) . '

'; } echo '
'; wp_nonce_field( $this->option ); echo '

'; echo ' '; if ( $st['has_key'] ) { echo ' '; } echo '

'; } } endif;