# codoc/0.9.3/class-codoc-util.php

codoc, version 0.9.3. 248 lines.

- Page: https://pluginprobe.com/plugins/codoc/0.9.3/code/class-codoc-util.php
- Raw: https://pluginprobe.com/plugins/codoc/0.9.3/raw/class-codoc-util.php
- Modified: 2020-02-26T18:26:00+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/codoc/0.9.3/code/class-codoc-util.php#L10-L20`.

```php
<?php

if (!defined('WPINC')) {
    define( 'WPINC', 'wp-includes' );
}

if (!defined('CODOC_URL')) {
    define( 'CODOC_URL', 'https://codoc.jp' );
}

require_once( ABSPATH . WPINC . '/class-http.php');
require_once( ABSPATH . WPINC . '/class-wp-error.php');

final class CodocUtil {

    public function __construct($params = ['usercode' => null, 'token' => null]) {
        $this->setAuthInfo($params);
        return $this;
    }
    
    public function callAPI($method,$path,$body = [],$headers = []) {
        $usercode = $this->usercode;
        $token    = $this->token;

        $headers['X-CodocToken'] = $token;
        $host = CODOC_URL;
        $sslverify = true;

        if (preg_match('/local/',CODOC_URL)) {
            $sslverify = false;
            $host = 'https://host.docker.internal';
        }
        $url = sprintf("%s/api/v1/cms/%s%s",$host,$usercode,$path);
        $http = new WP_Http();
        try {
            $response = $http->request(
                $url,
                [
                    'sslverify' => $sslverify,
                    'method'  => $method,
                    'timeout' => 10,
                    'headers' => $headers,
                    'body'    => $body,
                ]
            );
            if ( is_wp_error($response) || $response['response']['code'] != 200 ) {
                //何もしない
                //var_dump( $response );
            }
        } catch(Exception $e) {

        }
        if (!is_wp_error($response) and
            isset($response['body']) and
            is_string($response['body']) and
            is_array(json_decode($response['body'], true)) and
            (json_last_error() == JSON_ERROR_NONE)) {
            return json_decode($response['body']);
        } else {
            return null;
        }
    }
    public function setAuthInfo($params = [ "usercode" => null, "token" => null ]) {
        if ($params["usercode"]) {
            $this->usercode = $params["usercode"];
        }
        if ($params["token"]) {
            $this->token = $params["token"];
        }
        return true;
    }
    public function get_token($params = ["fetch_token_key" => null],$auth_info = ["usercode" => null, "token" => null]) {
        $this->setAuthInfo($auth_info);
        return $this->callAPI('GET','/token',[ "fetch_token_key" => $params["fetch_token_key"] ]);
    }
    public function get_user_info($params = [] ,$auth_info = ["usercode" => null, "token" => null]) {
        $this->setAuthInfo($auth_info);
        return $this->callAPI('GET','');
    }
    public function sync_entry($params = [
        "post_title"       => null,
        "post_content"     => null,
        "post_status"      => null, # 0, 1
        "post_permalink"   => null,
        "codoc_entry_code" => null,
    ],$auth_info = ["usercode" => null, "token" => null]) {

        $this->setAuthInfo($auth_info);
        
        $post_content = $params['post_content'];
        preg_match('/wp:codoc\/codoc-block +?({.*})/',$post_content,$matches);
        // GUTENBERG で指定されたjson(記事情報)がない場合
        if (!$matches) {
            return;
        }
        // GUTENBERG で保存している内容を取得
        $codoc_info = json_decode($matches[1],true);
        // codoc タグがない場合はなにもしない
        //preg_match('/(<span +data-id="codoc-tag"[^>]+>(?:.+|)<\/span>)/',$post_content,$matches);
        preg_match('/(<(?:span|div)[^>]+data-id="codoc-tag"(?:[^>]+|)>(?:.+|)<\/(?:span|div)>)/',$post_content,$matches);       
        if (!$matches) {
            return;
        }
        // TODO: split or html parse? HTMLがつながってる場合はおかしくなる
        // classic(tinymce)版の場合p、もしくはdivにかこまれている
        $splited  = preg_split('/(?:<(?:div|p)(?:[^>]+|)>|)<\!-- +wp:codoc\/codoc-block .*<\!-- +\/wp:codoc\/codoc-block +-->(?:<\/(?:div|p)>|)/s',$post_content);
        $status = $params['post_status'];
        # $body_free = '';
        # $body_paywalled = '';
        # if (count($splited) >= 2) {
        #   
        # }
        $binded_url = $params['post_permalink'];
        $CODOC_SETTINGS = get_option(CODOC_SETTINGS_OPTION_NAME);
        if (isset($CODOC_SETTINGS['str_replace_binded_url_from']) and
            isset($CODOC_SETTINGS['str_replace_binded_url_to']) and
            $CODOC_SETTINGS['str_replace_binded_url_from']) {
            $binded_url = str_replace(sanitize_text_field($CODOC_SETTINGS['str_replace_binded_url_from']),
                                      sanitize_text_field($CODOC_SETTINGS['str_replace_binded_url_to']),
                                      $binded_url);
        }
        $api_params = [
            'title'          => $params['post_title'],
            'body_free'      => $splited[0],
            'body_paywalled' => $splited[1],
            'status'         => $status,
            'binded_url'     => $binded_url,
            'show_price'     => isset($codoc_info['showPrice']) ? ($codoc_info['showPrice'] ? 1 : 0) : 0,
            'price'          => isset($codoc_info['price']) ? $codoc_info['price'] : 100,
            'limited'        => isset($codoc_info['limited']) ? ($codoc_info['limited'] ? 1 : 0) : 0,
            'limited_count'  => isset($codoc_info['limitedCount']) ? $codoc_info['limitedCount'] : 1,
            'affiliate_mode' => isset($codoc_info['affiliateMode']) ? ($codoc_info['affiliateMode'] ? 1 : 0) : 0,
            'affiliate_rate' => isset($codoc_info['affiliateRate']) ? $codoc_info['affiliateRate'] : '0.0500',
            'show_support'   => isset($codoc_info['showSupport']) ? ($codoc_info['showSupport'] ? 1 : 0) : 0,
            'subscriptions'  => isset($codoc_info['subscriptions']) ? array_keys($codoc_info['subscriptions']) : [],
        ];
        $entryCode = $params['codoc_entry_code'];
        $res = null;
        if ($entryCode) {
            $res = $this->callAPI('PUT','/entries/' . $entryCode ,$api_params);
        } else {
            $res = $this->callAPI('POST', '/entries', $api_params);
        }
        return $res;
    }
    
    function post_thumbnail( $params = [
        "file_path"        => null,
        "boundary"         => null,
        "codoc_entry_code" => null,
    ], $auth_info = ["usercode" => null, "token" => null] ) {

        $this->setAuthInfo($auth_info);

        $file_path  = $params['file_path'];
        $boundary   = $params['boundary']; # ランダム変数24桁 wp_generate_password(24);
        $res = null;
        if (is_readable($file_path)) {
            $name = 'file';

            $payload = '';
                $payload .= '--' . $boundary;
                $payload .= "\r\n";
                $payload .= 'Content-Disposition: form-data; name="' . $name . '"; filename="' . basename( $file_path ) . '"' . "\r\n";
                $payload .= "Content-Type: application/octet-stream\r\n";
                $payload .= "Content-Transfer-Encoding: binary\r\n";
                $payload .= "\r\n";
                $payload .= file_get_contents( $file_path );
                $payload .= "\r\n";

                $payload .= '--' . $boundary . '--';

                $entryCode = $params['codoc_entry_code'];
                $res = $this->callAPI(
                    'POST',
                    '/entries/' . $entryCode . '/thumbnail',
                    $payload,
                    ['content-type' => 'multipart/form-data; boundary=' . $boundary]
                );
        }
        return $res;
    }
    
    function reset_thumbnail( $params = [
        "codoc_entry_code" => null,
    ],$auth_info = ["usercode" => null, "token" => null] ) {

        $this->setAuthInfo($auth_info);

        $entryCode = $params['codoc_entry_code'];
        $res = $this->callAPI(
            'POST',
            '/entries/' . $entryCode . '/thumbnail',
            [ "reset" => 1 ]
        );
        return $res;
    }
    
    function filter_content( $params = [
        "post_content"     => null,
        "preview"          => null,
        "codoc_entry_code" => null,
        "codoc_settings"   => null,
    ]) {
        $post_content = $params['post_content'];
        // codoc タグがあるかどうか (202001:span -> div に変更)
        preg_match('/(<(span|div)[^>]+data-id="codoc-tag"(?:[^>]+|)>(?:.+|)<\/(?:div|span)>)/',$post_content,$matches);
        // data-wp-plugin-ver が無いタグは分割しない
        if (!$matches) {
            return $post_content;
        }
        // codocタグで分割 (202001: gutenbergで直前のdivタグを削除)
        $tag_regex = '/(?:<div(?:[^>]+|)>|)<(?:span|div)[^>]+data-id="codoc-tag"(?:[^>]+|)>(?:.+|)<\/(?:span|div)>(?:<\/div>|)/';
        if ( $params['preview'] ) {
            $post_content = preg_replace($tag_regex,'<div class="codoc-continue">ここから上は無料で表示されます</div>',$post_content);
            return $post_content;
        }
        // codoc タグの前後で分ける
        $splited  = preg_split($tag_regex,$post_content);
        // codoc タグにID属性のentrycodeとdata-without-body(無料分を非表示)をつける
        $entryCodeFormated = sprintf('"codoc-entry-%s" ',$params['codoc_entry_code']);
        $codoc_tag = preg_replace('/<((?:span|div)[^>]+)data-id="[^"]+"((?:[^>]+|))>/','<${1} ${2} data-without-body="1" id=' . $entryCodeFormated  . ">", $matches[1]);
        # THE THOR の page-lp.php が "   " をけずるための対策
        # "div   class" -> "div class"
        $codoc_tag = preg_replace('/div +class/','div class',$codoc_tag);

        # タグの前後にHTMLを挿入
        $CODOC_SETTINGS = $params['codoc_settings'];
        if (!isset($CODOC_SETTINGS['str_before_codoc_tag'])) {
            $CODOC_SETTINGS['str_before_codoc_tag']  = '';
        }
        if (!isset($CODOC_SETTINGS['str_after_codoc_tag'])) {
            $CODOC_SETTINGS['str_after_codoc_tag']  = '';
        }
        // 無料部分のみ表示
        $post_content = $splited[0] . sprintf(
            '%s<div class="wp-block-codoc-codoc-block">%s</div>%s',
            $CODOC_SETTINGS['str_before_codoc_tag'],
            $codoc_tag,
            $CODOC_SETTINGS['str_after_codoc_tag']
        );
        return $post_content;
    }

    
}


```
