prefix 로 만든다(사용자 입력이 아니다). * $wpdb->prepare() 는 식별자 플레이스홀더를 지원하지 않으므로 다른 방법이 없다. * 값은 예외 없이 prepare() 의 %d / %s 로 바인딩한다. */ // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter /** * 폼 유형 정의. * - form : 기본 폼. 관리자는 개별 응답 내용을 보지 않는다. * - survey : 설문. 제출 결과를 집계/통계로 보여준다. */ function aj_form_types() { return array( 'form' => __( 'Form', 'ajebang-form-survey-builder' ), 'survey' => __( 'Survey', 'ajebang-form-survey-builder' ), ); } /** * 유효한 폼 유형인지 검사 후 기본값 보정. * * @param string $type * @return string */ function aj_form_normalize_type( $type ) { return array_key_exists( $type, aj_form_types() ) ? $type : 'form'; } /** * 공개 상태 정의. * * - draft : 초안. 프론트엔드 어디에도 노출하지 않는다(숏코드·목록·바로가기 전부). * - publish : 공개. * * @return array */ function aj_form_statuses() { return array( 'publish' => __( 'Published', 'ajebang-form-survey-builder' ), 'draft' => __( 'Draft', 'ajebang-form-survey-builder' ), ); } /** * 유효한 공개 상태인지 검사 후 기본값 보정. * * **기본값은 publish 다.** settings 에 status 키가 없던 시절에 만든 폼이 * 이 함수를 거쳐 초안으로 바뀌면 이미 게시된 폼이 사이트에서 사라진다. * 신규 폼을 초안으로 시작시키는 것은 편집 화면의 초기값이 담당한다. * * @param string $status * @return string */ function aj_form_normalize_status( $status ) { return array_key_exists( $status, aj_form_statuses() ) ? $status : 'publish'; } /** * 폼별 옵션 기본값. * * 옵션이 늘어날 것을 대비해 전용 컬럼 대신 settings JSON 컬럼에 모은다. * * @return array */ function aj_form_default_settings() { $global = aj_form_global_settings(); $d = $global['survey_defaults']; return array( // 공개 상태. 위 주석대로 기존 폼 보호를 위해 기본값은 publish. 'status' => 'publish', // 응답 마감 일시. 빈 문자열이면 무기한. 사이트 로컬 시각 'Y-m-d H:i:s'. 'deadline' => '', // 마감 후에도 집계 결과를 보여줄지 여부(설문에만 해당). 'show_results_after_deadline' => ! empty( $d['show_results_after_deadline'] ), // 폼 아래에 함께 노출할 관련 링크 목록. 각 항목은 label + url. 'links' => array(), // 대표 이미지의 첨부 파일 ID. 0 이면 없음. 'image_id' => 0, // 설문 제출 후 결과 위에 감사 메시지를 표시할지 여부. 'show_success_message' => ! empty( $d['show_success_message'] ), // 결과 상단에 전체 응답 수를 표시할지 여부. 'show_total_responses' => ! empty( $d['show_total_responses'] ), // 질문 제목 옆에 그 질문의 응답 수를 표시할지 여부. 'show_field_counts' => ! empty( $d['show_field_counts'] ), // 중복 참여 제한 방식. aj_form_duplicate_modes() 의 키. 'duplicate_check' => aj_form_normalize_duplicate_mode( $d['duplicate_check'] ), // 제출 방식. aj_form_submit_modes() 의 키. 'submit_mode' => aj_form_normalize_submit_mode( $d['submit_mode'] ), ); } /** * 제출 방식 정의. * * @return array */ function aj_form_submit_modes() { return array( 'button' => __( 'Show the submit button', 'ajebang-form-survey-builder' ), 'auto_all' => __( 'Hide the button, submit once every field is answered', 'ajebang-form-survey-builder' ), 'per_field' => __( 'Hide the button, reveal each question’s results as it is answered', 'ajebang-form-survey-builder' ), ); } /** * 유효한 제출 방식인지 검사 후 기본값 보정. * * @param string $mode * @return string */ function aj_form_normalize_submit_mode( $mode ) { return array_key_exists( $mode, aj_form_submit_modes() ) ? $mode : 'button'; } /** * 중복 참여 제한 방식 정의. * * 익명 제출을 허용하는 플러그인이라 완벽한 차단은 불가능하다. * 쿠키는 지우거나 시크릿 창으로 우회 가능하고, IP 는 회사·모바일 캐리어처럼 * 여러 사람이 공유하는 환경에서 정상 참여자를 막는다. 용도에 맞게 고르게 한다. * * @return array */ function aj_form_duplicate_modes() { return array( 'none' => __( 'No restriction', 'ajebang-form-survey-builder' ), 'cookie' => __( 'One response per browser (cookie)', 'ajebang-form-survey-builder' ), 'ip' => __( 'One response per browser or IP address', 'ajebang-form-survey-builder' ), ); } /** * 유효한 중복 제한 방식인지 검사 후 기본값 보정. * * @param string $mode * @return string */ function aj_form_normalize_duplicate_mode( $mode ) { return array_key_exists( $mode, aj_form_duplicate_modes() ) ? $mode : 'cookie'; } /** * settings JSON 을 배열로 디코드하고 기본값을 채운다. * * 컬럼이 없던 시절의 행은 빈 값이므로 항상 기본값으로 떨어진다. * * @param string $json * @return array */ function aj_form_decode_settings( $json ) { $decoded = json_decode( (string) $json, true ); if ( ! is_array( $decoded ) ) { $decoded = array(); } // 1.5.0 의 auto_submit(bool) 을 submit_mode 로 승격. 저장된 폼을 건드리지 않고 // 읽는 시점에 변환하므로 마이그레이션 스크립트가 필요 없다. if ( ! isset( $decoded['submit_mode'] ) && isset( $decoded['auto_submit'] ) ) { $decoded['submit_mode'] = $decoded['auto_submit'] ? 'auto_all' : 'button'; } unset( $decoded['auto_submit'] ); return array_merge( aj_form_default_settings(), $decoded ); } /** * 저장 전 옵션 정제. 정의된 키만 통과시킨다. * * @param mixed $settings * @return array */ function aj_form_sanitize_settings( $settings ) { if ( ! is_array( $settings ) ) { return aj_form_default_settings(); } return array( 'status' => aj_form_normalize_status( isset( $settings['status'] ) ? (string) $settings['status'] : '' ), 'deadline' => aj_form_sanitize_deadline( isset( $settings['deadline'] ) ? $settings['deadline'] : '' ), 'show_results_after_deadline' => ! empty( $settings['show_results_after_deadline'] ), 'links' => aj_form_sanitize_links( isset( $settings['links'] ) ? $settings['links'] : array() ), 'image_id' => isset( $settings['image_id'] ) ? absint( $settings['image_id'] ) : 0, 'show_success_message' => ! empty( $settings['show_success_message'] ), 'show_total_responses' => ! empty( $settings['show_total_responses'] ), 'show_field_counts' => ! empty( $settings['show_field_counts'] ), 'duplicate_check' => aj_form_normalize_duplicate_mode( isset( $settings['duplicate_check'] ) ? (string) $settings['duplicate_check'] : '' ), 'submit_mode' => aj_form_normalize_submit_mode( isset( $settings['submit_mode'] ) ? (string) $settings['submit_mode'] : '' ), ); } /** * 마감 일시 정제. * * 저장 형식은 사이트 로컬 시각의 'Y-m-d H:i:s' 다. datetime-local 입력이 주는 * 'Y-m-dTH:i' 도 받는다. 형식이 어긋나면 빈 문자열(=무기한)로 떨어뜨린다. * * @param mixed $value * @return string */ function aj_form_sanitize_deadline( $value ) { if ( ! is_string( $value ) && ! is_numeric( $value ) ) { return ''; } $value = trim( str_replace( 'T', ' ', (string) $value ) ); if ( '' === $value ) { return ''; } if ( ! preg_match( '/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})(?::(\d{2}))?$/', $value, $m ) ) { return ''; } if ( ! checkdate( (int) $m[2], (int) $m[3], (int) $m[1] ) ) { return ''; } if ( (int) $m[4] > 23 || (int) $m[5] > 59 ) { return ''; } $seconds = isset( $m[6] ) ? min( 59, (int) $m[6] ) : 0; return sprintf( '%s-%s-%s %s:%s:%02d', $m[1], $m[2], $m[3], $m[4], $m[5], $seconds ); } /** * 관련 링크 목록 정제. * * URL 이 비면 그 줄은 버린다(라벨만 남은 빈 줄 방지). 라벨이 없으면 렌더 시 * 호스트명을 대신 쓰므로 여기서는 비워 둔 채로 통과시킨다. * * @param mixed $links * @return array 각 항목: label, url. */ function aj_form_sanitize_links( $links ) { if ( ! is_array( $links ) ) { return array(); } $clean = array(); foreach ( $links as $link ) { if ( ! is_array( $link ) ) { continue; } $url = isset( $link['url'] ) ? trim( (string) $link['url'] ) : ''; // 스킴 없이 'ajebang.com/x' 로 적는 경우가 흔하다. esc_url_raw 는 이때 // 상대 경로로 판단해 그대로 두므로 http 를 붙여 절대 URL 로 만든다. if ( '' !== $url && ! preg_match( '#^(https?:|mailto:|tel:|/)#i', $url ) ) { $url = 'https://' . $url; } $url = esc_url_raw( $url, array( 'http', 'https', 'mailto', 'tel' ) ); if ( '' === $url ) { continue; } $clean[] = array( 'label' => isset( $link['label'] ) ? sanitize_text_field( $link['label'] ) : '', 'url' => $url, ); // 폼 하나에 링크가 스무 개를 넘을 이유가 없다. 잘못된 POST 방어. if ( count( $clean ) >= 20 ) { break; } } return $clean; } /** * 폼의 대표 이미지 첨부 ID. 없거나 이미 삭제된 첨부면 0. * * @param array $form * @return int */ function aj_form_image_id( $form ) { $id = absint( aj_form_setting( $form, 'image_id' ) ); // 미디어 라이브러리에서 지운 이미지를 그대로 참조하면 깨진 자리가 남는다. if ( $id && ! wp_attachment_is_image( $id ) ) { return 0; } return $id; } /** * 폼이 프론트엔드에 노출 가능한 상태인지(=초안이 아닌지). * * @param array $form * @return bool */ function aj_form_is_published( $form ) { return 'publish' === aj_form_normalize_status( aj_form_setting( $form, 'status' ) ); } /** * 마감 일시의 유닉스 타임스탬프. 마감이 없으면 0. * * 저장값은 사이트 로컬 시각이므로 UTC 로 바꿔 비교한다. WP 는 PHP 기본 * 타임존을 UTC 로 고정하므로 strtotime() 을 그대로 쓰면 로컬 시각이 * UTC 로 해석돼 최대 하루 가까이 어긋난다. * * @param array $form * @return int */ function aj_form_deadline_timestamp( $form ) { $deadline = aj_form_sanitize_deadline( aj_form_setting( $form, 'deadline' ) ); if ( '' === $deadline ) { return 0; } $gmt = get_gmt_from_date( $deadline ); $ts = strtotime( $gmt . ' +0000' ); return $ts ? (int) $ts : 0; } /** * 응답을 더 받지 않는 상태인지. * * @param array $form * @return bool */ function aj_form_is_closed( $form ) { $deadline = aj_form_deadline_timestamp( $form ); return $deadline > 0 && time() > $deadline; } /** * 마감 일시를 사이트 날짜 형식으로. * * @param array $form * @return string 마감이 없으면 빈 문자열. */ function aj_form_deadline_display( $form ) { $deadline = aj_form_sanitize_deadline( aj_form_setting( $form, 'deadline' ) ); if ( '' === $deadline ) { return ''; } return mysql2date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $deadline ); } /** * 폼 옵션 값 하나 읽기. * * @param array $form * @param string $key * @return mixed */ function aj_form_setting( $form, $key ) { $defaults = aj_form_default_settings(); $settings = isset( $form['settings'] ) && is_array( $form['settings'] ) ? $form['settings'] : array(); if ( array_key_exists( $key, $settings ) ) { return $settings[ $key ]; } return isset( $defaults[ $key ] ) ? $defaults[ $key ] : null; } /** * 사용 가능한 필드 타입 정의. */ function aj_form_field_types() { return array( 'text' => __( 'Text', 'ajebang-form-survey-builder' ), 'textarea' => __( 'Textarea', 'ajebang-form-survey-builder' ), 'email' => __( 'Email', 'ajebang-form-survey-builder' ), 'number' => __( 'Number', 'ajebang-form-survey-builder' ), 'select' => __( 'Dropdown', 'ajebang-form-survey-builder' ), 'radio' => __( 'Radio', 'ajebang-form-survey-builder' ), 'checkbox' => __( 'Checkbox', 'ajebang-form-survey-builder' ), 'date' => __( 'Date', 'ajebang-form-survey-builder' ), ); } /** * 폼 목록 조회. * * @return array 각 항목: id, title, fields(array), created_at, submission_count */ function aj_form_get_forms() { global $wpdb; $forms_table = aj_form_table( 'forms' ); $sub_table = aj_form_table( 'submissions' ); $rows = $wpdb->get_results( "SELECT f.*, ( SELECT COUNT(*) FROM {$sub_table} s WHERE s.form_id = f.id ) AS submission_count FROM {$forms_table} f ORDER BY f.created_at DESC", ARRAY_A ); if ( ! $rows ) { return array(); } foreach ( $rows as &$row ) { $row['fields'] = aj_form_decode_fields( $row['fields'] ); $row['settings'] = aj_form_decode_settings( isset( $row['settings'] ) ? $row['settings'] : '' ); } return $rows; } /** * 단일 폼 조회. * * @param int $form_id * @return array|null */ function aj_form_get_form( $form_id ) { global $wpdb; $forms_table = aj_form_table( 'forms' ); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$forms_table} WHERE id = %d", $form_id ), ARRAY_A ); if ( ! $row ) { return null; } $row['fields'] = aj_form_decode_fields( $row['fields'] ); $row['settings'] = aj_form_decode_settings( isset( $row['settings'] ) ? $row['settings'] : '' ); return $row; } /** * 폼 생성/수정. * * @param int $form_id 0이면 신규. * @param string $title * @param string $type form | survey. * @param string $description 폼/설문 안내 내용 (제한적 HTML 허용). * @param array $fields 정제된 필드 배열. * @param array $settings 폼별 옵션 배열. * @return int 폼 ID. */ function aj_form_save_form( $form_id, $title, $type, $description, $fields, $settings = array() ) { global $wpdb; $forms_table = aj_form_table( 'forms' ); $now = current_time( 'mysql' ); $encoded = wp_json_encode( array_values( $fields ) ); $type = aj_form_normalize_type( $type ); $settings = wp_json_encode( aj_form_sanitize_settings( $settings ) ); if ( $form_id ) { $wpdb->update( $forms_table, array( 'title' => $title, 'type' => $type, 'description' => $description, 'fields' => $encoded, 'settings' => $settings, 'updated_at' => $now, ), array( 'id' => $form_id ), array( '%s', '%s', '%s', '%s', '%s', '%s' ), array( '%d' ) ); return $form_id; } $wpdb->insert( $forms_table, array( 'title' => $title, 'type' => $type, 'description' => $description, 'fields' => $encoded, 'settings' => $settings, 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ); return (int) $wpdb->insert_id; } /** * 폼 삭제 (관련 응답도 함께 삭제). * * @param int $form_id */ function aj_form_delete_form( $form_id ) { global $wpdb; $wpdb->delete( aj_form_table( 'forms' ), array( 'id' => $form_id ), array( '%d' ) ); $wpdb->delete( aj_form_table( 'submissions' ), array( 'form_id' => $form_id ), array( '%d' ) ); } /** * 응답 저장. * * @param int $form_id * @param array $data key=필드 인덱스, value=제출값. * @param string $ip * @return int 응답 ID. */ function aj_form_save_submission( $form_id, $data, $ip = '' ) { global $wpdb; $wpdb->insert( aj_form_table( 'submissions' ), array( 'form_id' => $form_id, 'data' => wp_json_encode( $data ), 'ip' => $ip, 'created_at' => current_time( 'mysql' ), ), array( '%d', '%s', '%s', '%s' ) ); return (int) $wpdb->insert_id; } /** * 응답 한 건 조회. * * @param int $submission_id * @return array|null */ function aj_form_get_submission( $submission_id ) { global $wpdb; $sub_table = aj_form_table( 'submissions' ); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$sub_table} WHERE id = %d", $submission_id ), ARRAY_A ); if ( ! $row ) { return null; } $row['data'] = json_decode( (string) $row['data'], true ); if ( ! is_array( $row['data'] ) ) { $row['data'] = array(); } return $row; } /** * 기존 응답의 값 갱신. 항목별 제출에서 같은 사람의 행을 채워 나갈 때 쓴다. * * @param int $submission_id * @param array $data */ function aj_form_update_submission_data( $submission_id, $data ) { global $wpdb; $wpdb->update( aj_form_table( 'submissions' ), array( 'data' => wp_json_encode( $data ) ), array( 'id' => $submission_id ), array( '%s' ), array( '%d' ) ); } /** * 특정 폼의 응답을 전부 삭제. 폼 정의는 남긴다. * * @param int $form_id * @return int 삭제된 응답 수. */ function aj_form_delete_submissions( $form_id ) { global $wpdb; return (int) $wpdb->delete( aj_form_table( 'submissions' ), array( 'form_id' => $form_id ), array( '%d' ) ); } /** * 같은 IP 로 제출한 가장 최근 응답. * * 쿠키가 없어진 방문자를 IP 로 되찾을 때 쓴다. * * @param int $form_id * @param string $ip * @return array|null */ function aj_form_get_submission_by_ip( $form_id, $ip ) { global $wpdb; if ( '' === $ip ) { return null; } $sub_table = aj_form_table( 'submissions' ); $id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$sub_table} WHERE form_id = %d AND ip = %s ORDER BY id DESC LIMIT 1", $form_id, $ip ) ); return $id ? aj_form_get_submission( (int) $id ) : null; } /** * 같은 IP 로 제출한 응답이 이미 있는지. * * @param int $form_id * @param string $ip * @return bool */ function aj_form_ip_has_submitted( $form_id, $ip ) { global $wpdb; if ( '' === $ip ) { return false; } $sub_table = aj_form_table( 'submissions' ); return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$sub_table} WHERE form_id = %d AND ip = %s LIMIT 1", $form_id, $ip ) ); } /** * 특정 폼의 응답 목록 조회. * * @param int $form_id * @return array */ function aj_form_get_submissions( $form_id ) { global $wpdb; $sub_table = aj_form_table( 'submissions' ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$sub_table} WHERE form_id = %d ORDER BY created_at DESC", $form_id ), ARRAY_A ); if ( ! $rows ) { return array(); } foreach ( $rows as &$row ) { $row['data'] = json_decode( (string) $row['data'], true ); if ( ! is_array( $row['data'] ) ) { $row['data'] = array(); } } return $rows; } /** * fields JSON 문자열을 배열로 디코드. * * @param string $json * @return array */ function aj_form_decode_fields( $json ) { $decoded = json_decode( (string) $json, true ); return is_array( $decoded ) ? $decoded : array(); } /** * 저장 전 필드 배열 정제. * * @param mixed $fields * @return array */ function aj_form_sanitize_fields( $fields ) { if ( ! is_array( $fields ) ) { return array(); } $allowed_types = array_keys( aj_form_field_types() ); $clean = array(); foreach ( $fields as $field ) { if ( empty( $field['type'] ) || ! in_array( $field['type'], $allowed_types, true ) ) { continue; } $options = array(); if ( ! empty( $field['options'] ) && is_array( $field['options'] ) ) { foreach ( $field['options'] as $opt ) { $opt = sanitize_text_field( $opt ); if ( '' !== $opt ) { $options[] = $opt; } } } // 선택지별 표시 수치(seed). 존재하는 옵션에 대한 양수만 남긴다. $seeds = array(); if ( ! empty( $field['seeds'] ) && is_array( $field['seeds'] ) ) { foreach ( $field['seeds'] as $opt => $seed ) { $opt = sanitize_text_field( $opt ); $seed = max( 0, (int) $seed ); if ( '' !== $opt && $seed > 0 && in_array( $opt, $options, true ) ) { $seeds[ $opt ] = $seed; } } } $clean[] = array( 'type' => $field['type'], 'label' => isset( $field['label'] ) ? sanitize_text_field( $field['label'] ) : '', 'required' => ! empty( $field['required'] ), 'options' => $options, 'seeds' => $seeds, ); } return $clean; }