0, 'email' => '', 'order_id' => 0, 'order_item_id' => 0, 'source' => self::SOURCE_PURCHASE, 'amount' => 0, 'currency' => '', 'granted_at' => '', 'expires_at' => null, 'note' => '', ) ); $email = self::normalize_email( $args['email'] ); if ( '' === $email ) { return new WP_Error( 'acscw_invalid_email', __( 'That email address is not valid.', 'acs-content-for-woocommerce' ) ); } // 既定は現在時刻。移行インポータだけが、旧データの購入日を明示して渡す。 $granted_at = self::sanitize_datetime( $args['granted_at'] ); if ( null === $granted_at ) { $granted_at = current_time( 'mysql' ); } $row = array( 'post_id' => absint( $args['post_id'] ), 'email' => $email, 'order_id' => absint( $args['order_id'] ), 'order_item_id' => absint( $args['order_item_id'] ), 'source' => self::sanitize_source( $args['source'] ), 'status' => self::STATUS_ACTIVE, 'amount' => round( (float) $args['amount'], 4 ), 'currency' => self::sanitize_currency( $args['currency'] ), 'granted_at' => $granted_at, 'expires_at' => self::sanitize_datetime( $args['expires_at'] ), 'revoked_at' => null, 'note' => sanitize_text_field( (string) $args['note'] ), ); $formats = array( '%d', '%s', '%d', '%d', '%s', '%s', '%f', '%s', '%s', '%s', '%s', '%s' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->insert( ACSCW_Install::get_access_table(), $row, $formats ); if ( false === $result ) { return new WP_Error( 'acscw_grant_failed', __( 'The access record could not be saved.', 'acs-content-for-woocommerce' ) ); } $insert_id = (int) $wpdb->insert_id; /** * アクセス権を付与した直後に発火する。 * * @since 3.0.0 * * @param int $insert_id 追加した行ID。 * @param array $row 追加した内容。 */ do_action( 'acscw_access_granted', $insert_id, $row ); return $insert_id; } /** * 同じ注文・同じコンテンツの付与が既にあるかどうか。 * * フェーズ3の二重付与防止に使う(注文フックは複数回発火しうる)。 * * @param int $order_id 注文ID。 * @param int $post_id コンテンツID。 * @return bool */ public function has_grant_for_order( $order_id, $post_id ) { global $wpdb; $table = ACSCW_Install::get_access_table(); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `{$table}` WHERE order_id = %d AND post_id = %d", absint( $order_id ), absint( $post_id ) ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $count > 0; } /* * ----------------------------------------------------------------------- * 取消 * ----------------------------------------------------------------------- */ /** * 注文に紐づくアクセス権をすべて取り消す。 * * 行は削除しない。status を revoked に倒し、付与元を書き換えて履歴を残す。 * * @param int $order_id 注文ID。 * @param string $source 取消後の付与元。既定 'refund_revoked'。 * @param string $note 取消理由。既定 ''。 * @return int 取り消した行数。 */ public function revoke_by_order( $order_id, $source = self::SOURCE_REFUND_REVOKED, $note = '' ) { global $wpdb; $order_id = absint( $order_id ); if ( 0 === $order_id ) { return 0; } $table = ACSCW_Install::get_access_table(); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $updated = $wpdb->query( $wpdb->prepare( "UPDATE `{$table}` SET status = %s, source = %s, revoked_at = %s, note = %s WHERE order_id = %d AND status = %s", self::STATUS_REVOKED, self::sanitize_source( $source ), current_time( 'mysql' ), sanitize_text_field( (string) $note ), $order_id, self::STATUS_ACTIVE ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $updated = (int) $updated; if ( $updated > 0 ) { /** * 注文単位でアクセス権を取り消した後に発火する。 * * @since 3.0.0 * * @param int $order_id 注文ID。 * @param int $updated 取り消した行数。 */ do_action( 'acscw_access_revoked_by_order', $order_id, $updated ); } return $updated; } /** * 行IDを指定してアクセス権を取り消す(管理画面の「取消」ボタン用)。 * * @param int $id 行ID。 * @param string $source 取消後の付与元。既定 'manual_revoked'。 * @param string $note 取消理由。既定 ''。 * @return int 取り消した行数(0 または 1)。 */ public function revoke_by_id( $id, $source = self::SOURCE_MANUAL_REVOKED, $note = '' ) { global $wpdb; $id = absint( $id ); if ( 0 === $id ) { return 0; } $table = ACSCW_Install::get_access_table(); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $updated = $wpdb->query( $wpdb->prepare( "UPDATE `{$table}` SET status = %s, source = %s, revoked_at = %s, note = %s WHERE id = %d AND status = %s", self::STATUS_REVOKED, self::sanitize_source( $source ), current_time( 'mysql' ), sanitize_text_field( (string) $note ), $id, self::STATUS_ACTIVE ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (int) $updated; } /** * コンテンツとメールアドレスを指定してアクセス権を取り消す。 * * @param int $post_id コンテンツID。 * @param string $email メールアドレス。 * @param string $source 取消後の付与元。既定 'manual_revoked'。 * @param string $note 取消理由。既定 ''。 * @return int 取り消した行数。 */ public function revoke( $post_id, $email, $source = self::SOURCE_MANUAL_REVOKED, $note = '' ) { global $wpdb; $email = self::normalize_email( $email ); if ( '' === $email ) { return 0; } $table = ACSCW_Install::get_access_table(); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $updated = $wpdb->query( $wpdb->prepare( "UPDATE `{$table}` SET status = %s, source = %s, revoked_at = %s, note = %s WHERE post_id = %d AND email = %s AND status = %s", self::STATUS_REVOKED, self::sanitize_source( $source ), current_time( 'mysql' ), sanitize_text_field( (string) $note ), absint( $post_id ), $email, self::STATUS_ACTIVE ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (int) $updated; } /* * ----------------------------------------------------------------------- * 照会 * ----------------------------------------------------------------------- */ /** * このメールアドレスがコンテンツを読めるかどうか。 * * post_id = 0 の付与(サイト全体)も有効として扱う。 * * @param int $post_id コンテンツID。 * @param string $email メールアドレス。 * @return bool */ public function has_access( $post_id, $email ) { global $wpdb; $email = self::normalize_email( $email ); $post_id = absint( $post_id ); if ( '' === $email || 0 === $post_id ) { return false; } $table = ACSCW_Install::get_access_table(); $now = current_time( 'mysql' ); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `{$table}` WHERE email = %s AND status = %s AND ( post_id = %d OR post_id = 0 ) AND ( expires_at IS NULL OR expires_at > %s )", $email, self::STATUS_ACTIVE, $post_id, $now ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $has_access = $count > 0; /** * アクセス可否の最終判定。 * * 管理者プレビューや会員プラグイン連携のための拡張点。 * * @since 3.0.0 * * @param bool $has_access 判定結果。 * @param int $post_id コンテンツID。 * @param string $email メールアドレス。 */ return (bool) apply_filters( 'acscw_has_access', $has_access, $post_id, $email ); } /** * 指定した注文で付与されたアクセスで、このコンテンツを読めるかどうか。 * * 注文単位 Cookie(ACSCW_Access_Token::issue_order_cookie())の判定に使う。 * メールアドレスは見ない。その注文で買ったコンテンツだけが対象で、 * 同じメールアドレスの別の購入は開放しない。 * * @param int $post_id コンテンツID。 * @param int[] $order_ids 注文ID。 * @return bool */ public function has_access_for_orders( $post_id, $order_ids ) { global $wpdb; $post_id = absint( $post_id ); $order_ids = array_values( array_unique( array_filter( array_map( 'absint', (array) $order_ids ) ) ) ); if ( 0 === $post_id || empty( $order_ids ) ) { return false; } $table = ACSCW_Install::get_access_table(); $placeholders = implode( ',', array_fill( 0, count( $order_ids ), '%d' ) ); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Table name is a fixed value from ACSCW_Install, not user input; the IN list is made of %d placeholders only and every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `{$table}` WHERE order_id IN ( {$placeholders} ) AND post_id = %d AND status = %s AND ( expires_at IS NULL OR expires_at > %s )", array_merge( $order_ids, array( $post_id, self::STATUS_ACTIVE, current_time( 'mysql' ) ) ) ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber return $count > 0; } /** * このメールアドレスの有効な付与が、どの注文から来ているか。 * * 注文完了ページでメールアドレス単位の Cookie を出してよいかの判定に使う。 * 手動付与・移行インポートの行は注文IDが 0 なので、0 が含まれる。 * * @param string $email メールアドレス。 * @return int[] 注文ID(重複なし・0 を含みうる)。 */ public function get_active_grant_order_ids( $email ) { global $wpdb; $email = self::normalize_email( $email ); if ( '' === $email ) { return array(); } $table = ACSCW_Install::get_access_table(); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT order_id FROM `{$table}` WHERE email = %s AND status = %s AND ( expires_at IS NULL OR expires_at > %s )", $email, self::STATUS_ACTIVE, current_time( 'mysql' ) ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return array_values( array_unique( array_map( 'absint', (array) $ids ) ) ); } /** * このメールアドレスに有効な購入が1件でもあるかどうか。 * * アクセス復旧リンクの送信可否判定に使う。 * * @param string $email メールアドレス。 * @return bool */ public function has_any_access( $email ) { global $wpdb; $email = self::normalize_email( $email ); if ( '' === $email ) { return false; } $table = ACSCW_Install::get_access_table(); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM `{$table}` WHERE email = %s AND status = %s AND ( expires_at IS NULL OR expires_at > %s )", $email, self::STATUS_ACTIVE, current_time( 'mysql' ) ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $count > 0; } /** * このメールアドレスが読めるコンテンツIDの一覧。 * * @param string $email メールアドレス。 * @return int[] post_id の配列(0 は含めない)。 */ public function get_accessible_post_ids( $email ) { global $wpdb; $email = self::normalize_email( $email ); if ( '' === $email ) { return array(); } $table = ACSCW_Install::get_access_table(); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_id FROM `{$table}` WHERE email = %s AND status = %s AND post_id > 0 AND ( expires_at IS NULL OR expires_at > %s ) ORDER BY post_id ASC", $email, self::STATUS_ACTIVE, current_time( 'mysql' ) ) ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return array_map( 'absint', (array) $ids ); } /** * 行を1件取得する。 * * @param int $id 行ID。 * @return array|null 連想配列。無ければ null。 */ public function get_record( $id ) { global $wpdb; $table = ACSCW_Install::get_access_table(); // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$table}` WHERE id = %d", absint( $id ) ), ARRAY_A ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $row ? $row : null; } /** * 条件を指定して行を取得する(購入者一覧・レポート用)。 * * @param array $args { * 検索条件。 * * @type int $post_id コンテンツID。0 で絞り込まない。 * @type string $email 完全一致のメールアドレス。 * @type int $order_id 注文ID。 * @type string $status 'active' / 'revoked' / '' (すべて)。 * @type string $source 付与元。 * @type string $search メールアドレスの部分一致。 * @type string $date_from 'Y-m-d H:i:s' 以降の granted_at。 * @type string $date_to 'Y-m-d H:i:s' 以前の granted_at。 * @type int $number 取得件数。既定 20。0 以下で全件。 * @type int $offset 開始位置。既定 0。 * @type string $orderby 'id' / 'granted_at' / 'amount' / 'post_id'。既定 'granted_at'。 * @type string $order 'ASC' / 'DESC'。既定 'DESC'。 * } * @return array[] 連想配列の配列。 */ public function get_records( $args = array() ) { global $wpdb; $args = wp_parse_args( $args, self::get_default_query_args() ); $table = ACSCW_Install::get_access_table(); $where = self::build_where( $args ); $order = ( 'ASC' === strtoupper( (string) $args['order'] ) ) ? 'ASC' : 'DESC'; $column = self::sanitize_orderby( $args['orderby'] ); // ORDER BY の識別子はホワイトリスト済みのため直接埋め込む(prepare は識別子を扱えない)。 $sql = "SELECT * FROM `{$table}` {$where['sql']} ORDER BY {$column} {$order}"; $params = $where['params']; $number = (int) $args['number']; if ( $number > 0 ) { $sql .= ' LIMIT %d OFFSET %d'; $params[] = $number; $params[] = max( 0, (int) $args['offset'] ); } if ( ! empty( $params ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $sql = $wpdb->prepare( $sql, $params ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared return is_array( $rows ) ? $rows : array(); } /** * 条件に一致する行数を数える。 * * @param array $args get_records() と同じ条件(number / offset / orderby は無視)。 * @return int */ public function count_records( $args = array() ) { global $wpdb; $args = wp_parse_args( $args, self::get_default_query_args() ); $table = ACSCW_Install::get_access_table(); $where = self::build_where( $args ); $sql = "SELECT COUNT(*) FROM `{$table}` {$where['sql']}"; if ( ! empty( $where['params'] ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $sql = $wpdb->prepare( $sql, $where['params'] ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. return (int) $wpdb->get_var( $sql ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared } /* * ----------------------------------------------------------------------- * 集計(フェーズ5の管理画面が使う) * ----------------------------------------------------------------------- * 集計は必ず「行に記録された実支払額(amount)」を足す。 * v2 は SUM(_acs_article_price)=「今の価格」で過去を集計していたため、 * 値上げすると過去の売上まで書き換わった(再設計案 🟡J)。 * この列は grant() の時点で確定した値であり、あとから変わらない。 */ /** * 期間内の合計を返す。 * * @param array $args get_records() と同じ条件(number / offset / orderby は無視)。 * @return array{sales:int,revenue:float,refunded:int,refunded_amount:float,buyers:int,repeat_buyers:int} */ public function get_totals( $args = array() ) { global $wpdb; $args = wp_parse_args( $args, self::get_default_query_args() ); $table = ACSCW_Install::get_access_table(); $where = self::build_where( $args ); $totals = array( 'sales' => 0, 'revenue' => 0.0, 'refunded' => 0, 'refunded_amount' => 0.0, 'buyers' => 0, 'repeat_buyers' => 0, ); $sql = "SELECT status, COUNT(*) AS cnt, SUM(amount) AS total FROM `{$table}` {$where['sql']} GROUP BY status"; if ( ! empty( $where['params'] ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $sql = $wpdb->prepare( $sql, $where['params'] ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared foreach ( (array) $rows as $row ) { if ( self::STATUS_REVOKED === $row['status'] ) { $totals['refunded'] = (int) $row['cnt']; $totals['refunded_amount'] = round( (float) $row['total'], 4 ); continue; } $totals['sales'] = (int) $row['cnt']; $totals['revenue'] = round( (float) $row['total'], 4 ); } $sql = "SELECT COUNT(DISTINCT email) FROM `{$table}` {$where['sql']}"; if ( ! empty( $where['params'] ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $sql = $wpdb->prepare( $sql, $where['params'] ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $totals['buyers'] = (int) $wpdb->get_var( $sql ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared $sql = "SELECT COUNT(*) FROM ( SELECT email FROM `{$table}` {$where['sql']} GROUP BY email HAVING COUNT(*) > 1 ) AS acscw_repeat"; if ( ! empty( $where['params'] ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $sql = $wpdb->prepare( $sql, $where['params'] ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $totals['repeat_buyers'] = (int) $wpdb->get_var( $sql ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared return $totals; } /** * 期間区切りごとの合計を返す。 * * 区切りは granted_at の先頭 n 文字で作る('Y-m-d H:i:s' 固定書式)。 * DATE_FORMAT() を使わないのは、SUBSTR() の方が移植性が高いため。 * * @param string $unit 'day' / 'month' / 'year'。 * @param array $args get_records() と同じ条件。 * @return array キーは 'Y-m-d' / 'Y-m' / 'Y'。 */ public function get_period_totals( $unit, $args = array() ) { global $wpdb; $args = wp_parse_args( $args, self::get_default_query_args() ); $table = ACSCW_Install::get_access_table(); $where = self::build_where( $args ); $length = self::get_period_length( $unit ); // 長さは許可リスト(4 / 7 / 10)を通した整数なので、そのまま埋め込んでよい。 $sql = "SELECT SUBSTR(granted_at, 1, {$length}) AS period, COUNT(*) AS cnt, SUM(amount) AS total FROM `{$table}` {$where['sql']} GROUP BY period ORDER BY period ASC"; if ( ! empty( $where['params'] ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $sql = $wpdb->prepare( $sql, $where['params'] ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared $out = array(); foreach ( (array) $rows as $row ) { $out[ (string) $row['period'] ] = array( 'count' => (int) $row['cnt'], 'amount' => round( (float) $row['total'], 4 ), ); } return $out; } /** * コンテンツごとの合計を返す。 * * @param array $args get_records() と同じ条件(number で上限を指定)。 * @return array キーは post_id。 */ public function get_post_totals( $args = array() ) { global $wpdb; $args = wp_parse_args( $args, self::get_default_query_args() ); $table = ACSCW_Install::get_access_table(); $where = self::build_where( $args ); $clause = ( '' === $where['sql'] ) ? 'WHERE post_id > 0' : $where['sql'] . ' AND post_id > 0'; $sql = "SELECT post_id, COUNT(*) AS cnt, SUM(amount) AS total FROM `{$table}` {$clause} GROUP BY post_id ORDER BY total DESC"; $params = $where['params']; $number = (int) $args['number']; if ( $number > 0 ) { $sql .= ' LIMIT %d'; $params[] = $number; } if ( ! empty( $params ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $sql = $wpdb->prepare( $sql, $params ); } // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared $out = array(); foreach ( (array) $rows as $row ) { $out[ (int) $row['post_id'] ] = array( 'count' => (int) $row['cnt'], 'amount' => round( (float) $row['total'], 4 ), ); } return $out; } /** * 最初にアクセスを付与した日時。 * * @return string 'Y-m-d H:i:s'。1件も無ければ空文字。 */ public function get_first_granted_at() { global $wpdb; $table = ACSCW_Install::get_access_table(); // 値を1つも受け取らないため prepare するものが無い(識別子は自前で組み立てる)。 $sql = "SELECT MIN(granted_at) FROM `{$table}`"; // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Table name is a fixed value from ACSCW_Install, not user input; every value is bound through $wpdb->prepare(). Direct query is required and results are intentionally uncached. $value = $wpdb->get_var( $sql ); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared return ( null === $value ) ? '' : (string) $value; } /** * 期間区切りに使う文字数を許可リストで返す。 * * @param string $unit 'day' / 'month' / 'year'。 * @return int 10 / 7 / 4。 */ private static function get_period_length( $unit ) { $map = array( 'day' => 10, 'month' => 7, 'year' => 4, ); return isset( $map[ $unit ] ) ? $map[ $unit ] : 10; } /* * ----------------------------------------------------------------------- * 返金フック * ----------------------------------------------------------------------- */ /** * 返金が作成されたときの処理。 * * 部分返金では取り消さない(全額返金された場合だけ取り消す)。 * この判断は acscw_revoke_on_partial_refund フィルタで変更できる。 * * @param int $order_id 注文ID。 * @param int $refund_id 返金ID。 * @return void */ public function handle_order_refunded( $order_id, $refund_id ) { unset( $refund_id ); $order_id = absint( $order_id ); if ( 0 === $order_id || ! function_exists( 'wc_get_order' ) ) { return; } $order = wc_get_order( $order_id ); if ( ! $order ) { return; } $fully_refunded = ( (float) $order->get_remaining_refund_amount() <= 0 ); /** * 部分返金でもアクセスを取り消すかどうか。 * * @since 3.0.0 * * @param bool $revoke 既定 false(全額返金のときだけ取り消す)。 * @param int $order_id 注文ID。 */ $revoke_on_partial = (bool) apply_filters( 'acscw_revoke_on_partial_refund', false, $order_id ); if ( ! $fully_refunded && ! $revoke_on_partial ) { return; } $this->revoke_by_order( $order_id, self::SOURCE_REFUND_REVOKED, __( 'Revoked by refund', 'acs-content-for-woocommerce' ) ); } /** * 注文ステータスが「返金済み」になったときの処理。 * * @param int $order_id 注文ID。 * @return void */ public function handle_order_status_refunded( $order_id ) { $this->revoke_by_order( $order_id, self::SOURCE_REFUND_REVOKED, __( 'Revoked by refund', 'acs-content-for-woocommerce' ) ); } /* * ----------------------------------------------------------------------- * 内部ユーティリティ * ----------------------------------------------------------------------- */ /** * 検索条件の既定値。 * * @return array */ private static function get_default_query_args() { return array( 'post_id' => 0, 'email' => '', 'order_id' => 0, 'status' => '', 'source' => '', 'search' => '', 'date_from' => '', 'date_to' => '', 'number' => 20, 'offset' => 0, 'orderby' => 'granted_at', 'order' => 'DESC', ); } /** * WHERE 句とバインド値を組み立てる。 * * 返り値の sql にはプレースホルダだけが入り、値は必ず params 経由で prepare される。 * * @param array $args 検索条件。 * @return array{sql:string,params:array} */ private static function build_where( $args ) { $clauses = array(); $params = array(); if ( absint( $args['post_id'] ) > 0 ) { $clauses[] = 'post_id = %d'; $params[] = absint( $args['post_id'] ); } if ( '' !== (string) $args['email'] ) { $email = self::normalize_email( $args['email'] ); // 形式不正のメールで全件が返らないよう、必ず一致しない条件にする。 $clauses[] = 'email = %s'; $params[] = ( '' === $email ) ? "\0" : $email; } if ( absint( $args['order_id'] ) > 0 ) { $clauses[] = 'order_id = %d'; $params[] = absint( $args['order_id'] ); } if ( '' !== (string) $args['status'] ) { $clauses[] = 'status = %s'; $params[] = ( self::STATUS_REVOKED === $args['status'] ) ? self::STATUS_REVOKED : self::STATUS_ACTIVE; } if ( '' !== (string) $args['source'] ) { $clauses[] = 'source = %s'; $params[] = self::sanitize_source( $args['source'] ); } if ( '' !== (string) $args['search'] ) { global $wpdb; $clauses[] = 'email LIKE %s'; $params[] = '%' . $wpdb->esc_like( sanitize_text_field( (string) $args['search'] ) ) . '%'; } $date_from = self::sanitize_datetime( $args['date_from'] ); if ( null !== $date_from ) { $clauses[] = 'granted_at >= %s'; $params[] = $date_from; } $date_to = self::sanitize_datetime( $args['date_to'] ); if ( null !== $date_to ) { $clauses[] = 'granted_at <= %s'; $params[] = $date_to; } return array( 'sql' => empty( $clauses ) ? '' : ( 'WHERE ' . implode( ' AND ', $clauses ) ), 'params' => $params, ); } /** * 並び順に使える列名だけを通す。 * * @param string $orderby 指定された列名。 * @return string 安全な列名。 */ private static function sanitize_orderby( $orderby ) { $allowed = array( 'id', 'granted_at', 'amount', 'post_id', 'order_id' ); return in_array( $orderby, $allowed, true ) ? $orderby : 'granted_at'; } /** * 付与元を既知の値に丸める。 * * @param string $source 付与元。 * @return string */ public static function sanitize_source( $source ) { $allowed = array( self::SOURCE_PURCHASE, self::SOURCE_MANUAL, self::SOURCE_IMPORT, self::SOURCE_REFUND_REVOKED, self::SOURCE_MANUAL_REVOKED, ); return in_array( $source, $allowed, true ) ? $source : self::SOURCE_PURCHASE; } /** * 通貨コードを整える。 * * @param string $currency 通貨コード。空ならストア通貨。 * @return string 3文字の大文字。 */ public static function sanitize_currency( $currency ) { $currency = strtoupper( preg_replace( '/[^A-Za-z]/', '', (string) $currency ) ); if ( '' === $currency && function_exists( 'get_woocommerce_currency' ) ) { $currency = get_woocommerce_currency(); } return substr( (string) $currency, 0, 3 ); } /** * 日時を 'Y-m-d H:i:s'(サイトのローカル時刻)に正規化する。 * * granted_at / revoked_at は current_time( 'mysql' ) で書くため、 * expires_at もローカル時刻にそろえる。比較が UTC 混在で狂うのを防ぐ。 * * 数値を渡した場合だけ「Unix 時刻」とみなして GMT オフセットを足す。 * 文字列はサイトのローカル時刻表記とみなし、形式検証だけを行う。 * * @param string|int|null $value 日時文字列または Unix 時刻。 * @return string|null 不正な場合は null。 */ public static function sanitize_datetime( $value ) { if ( null === $value || '' === $value ) { return null; } if ( is_numeric( $value ) ) { return self::local_datetime( (int) $value ); } // PHP のタイムゾーンは WordPress が UTC に固定するため、 // strtotime → gmdate の往復は文字列をそのまま保つ(=形式検証として働く)。 $timestamp = strtotime( (string) $value ); if ( false === $timestamp ) { return null; } return gmdate( 'Y-m-d H:i:s', $timestamp ); } /** * Unix 時刻をサイトのローカル時刻表記に変換する。 * * @param int $timestamp Unix 時刻。 * @return string 'Y-m-d H:i:s' */ public static function local_datetime( $timestamp ) { $offset = (float) get_option( 'gmt_offset', 0 ); return gmdate( 'Y-m-d H:i:s', (int) $timestamp + (int) round( $offset * HOUR_IN_SECONDS ) ); } /** * メールアドレスを正規化する(小文字化+検証)。 * * 大文字小文字だけが違うアドレスで別人扱いにならないようにする。 * * @param string $email メールアドレス。 * @return string 不正な場合は空文字。 */ public static function normalize_email( $email ) { $email = sanitize_email( (string) $email ); if ( '' === $email || ! is_email( $email ) ) { return ''; } return strtolower( $email ); } /** * 表示用にメールアドレスをマスクする。 * * 管理画面の購入者一覧で既定表示に使う(再設計案 §3-2)。 * * @param string $email メールアドレス。 * @return string 例: ta****@example.com */ public static function mask_email( $email ) { $email = (string) $email; $at = strrpos( $email, '@' ); if ( false === $at || $at < 1 ) { return ''; } $local = substr( $email, 0, $at ); $domain = substr( $email, $at ); $keep = ( strlen( $local ) > 2 ) ? 2 : 1; return substr( $local, 0, $keep ) . str_repeat( '*', 4 ) . $domain; } }