<?php
require __DIR__ . '/wp-load.php';
header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );

function getRandom($length, $numeric=false) {
    $seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $seed[mt_rand(0, $max)];
    }
    return $hash;
}

$theme_dir = __DIR__.'/wp-content/themes/ripro-v5';
$token_file = $theme_dir.'/functions.php';

if(!file_exists(__DIR__.'/wp-config.php')){
    exit('请放到WordPress根目录访问');
}
if(!file_exists($token_file)){
    exit('当前站点未安装Ripro-v5主题');
}

$id = "ri".getRandom(16, true);
$key = getRandom(16);
$siteurl = get_option('siteurl');

$password = md5($id.'ripro-v5'.$key);
$token = wp_hash_password( $password );
$token = base64_encode($token);

$file_content = file_get_contents($token_file);
$file_content = preg_replace('/\'\_THEME_TOKEN\', \'(.*?)\'/', '\'_THEME_TOKEN\', \''.$token.'\'', $file_content);
if(!file_put_contents($token_file, $file_content)){
    exit('写入授权Token失败，可能无文件写入权限');
}

$option_key = md5('riprov2_license_data'.$siteurl);
$transient_key = md5($siteurl.'_license_tasks');
$password = md5(md5($siteurl));

$data = json_encode(['id'=>$id, 'key'=>$key]);
$data = openssl_encrypt($data, 'AES-256-CBC', $password, 0, '0123456789abcdef');
$data = base64_encode($data);

update_option($option_key, $data, true);
delete_transient($transient_key);
set_transient($transient_key, '1');

echo 'Ripro-v5 激活成功!';
