Results computed in this request, by form id + values hash. */ private static $cache = array(); /** Hooks. */ public static function init() { Helpers::boot(); add_filter( 'fwren/form_defaults', array( __CLASS__, 'defaults' ) ); add_action( 'fwren/submission/inserted', array( __CLASS__, 'on_inserted' ), 5, 3 ); add_filter( 'fwren/smartcode', array( __CLASS__, 'smartcode' ), 10, 7 ); add_filter( 'fwren/smartcodes', array( __CLASS__, 'catalog' ) ); add_filter( 'fwren/confirmation_extra', array( __CLASS__, 'confirmation' ), 10, 4 ); add_filter( 'fwren/admin/form_tabs', array( __CLASS__, 'tab' ), 23, 2 ); add_action( 'fwren/admin/form_tab/quiz', array( __CLASS__, 'render_tab' ), 10, 2 ); add_action( 'fwren/admin/form_tab_save/quiz', array( __CLASS__, 'save_tab' ), 20, 2 ); add_action( 'fwren/admin/entry_sidebar', array( __CLASS__, 'entry_sidebar' ) ); } /** Extra defaults. */ public static function defaults( $d ) { $d['quiz'] = array_merge( array( 'mode' => 'score', 'show_answers' => false, 'personalities' => array(), 'questions' => array(), ), (array) ( $d['quiz'] ?? array() ) ); return $d; } /* ------------------------------------------------------------------ * * Scoring * ------------------------------------------------------------------ */ /** @return array Enabled questions keyed by field. */ public static function questions( array $quiz ) { $out = array(); foreach ( (array) $quiz['questions'] as $q ) { if ( is_array( $q ) && ! empty( $q['field'] ) && Helpers::on( $q['enabled'] ?? '1' ) ) { $out[ (string) $q['field'] ] = $q; } } return $out; } /** * Score a set of values. * * @param int $form_id Form id. * @param array $values Clean values. * @return array|null Null when the quiz is off. */ public static function compute( $form_id, array $values ) { $quiz = Form::settings( $form_id )['quiz']; if ( empty( $quiz['enabled'] ) ) { return null; } $ck = $form_id . ':' . md5( wp_json_encode( $values ) ); if ( isset( self::$cache[ $ck ] ) ) { return self::$cache[ $ck ]; } $schema = Schema::get( $form_id ); $qs = self::questions( $quiz ); $person = 'personality' === $quiz['mode']; $score = 0.0; $total = 0.0; $items = array(); $flags = array(); $tally = array(); foreach ( $schema['order'] as $key ) { if ( ! isset( $qs[ $key ] ) || ! isset( $schema['fields'][ $key ] ) ) { continue; } $q = $qs[ $key ]; $f = $schema['fields'][ $key ]; $v = $values[ $key ] ?? ''; $type = Fields::get( $f['type'] ); $ans = $type ? $type->format( $v, $f, 'text' ) : ( is_array( $v ) ? implode( ', ', $v ) : (string) $v ); if ( $person ) { $map = array(); foreach ( (array) ( $q['map'] ?? array() ) as $m ) { if ( isset( $m['value'] ) && '' !== trim( (string) ( $m['type'] ?? '' ) ) ) { $map[ Helpers::norm( $m['value'] ) ] = trim( (string) $m['type'] ); } } foreach ( is_array( $v ) ? $v : array( $v ) as $one ) { $one = Helpers::norm( $one ); if ( isset( $map[ $one ] ) ) { $tally[ $map[ $one ] ] = ( $tally[ $map[ $one ] ] ?? 0 ) + 1; } } $items[] = array( 'key' => $key, 'label' => Schema::label( $f ), 'answer' => $ans ); continue; } $pts = is_numeric( $q['points'] ?? '' ) ? (float) $q['points'] : 1.0; $ok = self::is_correct( $f, $q, $v ); $total += $pts; $score += $ok ? $pts : 0; $flags[ $key ] = $ok; $items[] = array( 'key' => $key, 'label' => Schema::label( $f ), 'answer' => $ans, 'correct' => $ok, 'expect' => self::expected_text( $f, $q ), 'points' => $ok ? $pts : 0, 'max' => $pts, ); } $percent = $total > 0 ? round( $score / $total * 100, 2 ) : 0; $grade = ''; $message = ''; if ( ! $person ) { $bands = array_values( array_filter( (array) $quiz['grading'], static function ( $b ) { return is_array( $b ) && '' !== trim( (string) ( $b['grade'] ?? '' ) ); } ) ); usort( $bands, static function ( $a, $b ) { return (float) $b['min'] <=> (float) $a['min']; } ); foreach ( $bands as $b ) { if ( $percent >= (float) $b['min'] ) { $grade = (string) $b['grade']; $message = (string) ( $b['message'] ?? '' ); break; } } } $personality = ''; if ( $person && $tally ) { $order = array(); foreach ( (array) $quiz['personalities'] as $i => $p ) { if ( ! empty( $p['type'] ) ) { $order[ trim( (string) $p['type'] ) ] = $i; } } uksort( $tally, static function ( $a, $b ) use ( $tally, $order ) { if ( $tally[ $a ] !== $tally[ $b ] ) { return $tally[ $b ] <=> $tally[ $a ]; } return ( $order[ $a ] ?? 999 ) <=> ( $order[ $b ] ?? 999 ); } ); $personality = (string) array_key_first( $tally ); foreach ( (array) $quiz['personalities'] as $p ) { if ( trim( (string) ( $p['type'] ?? '' ) ) === $personality ) { $message = (string) ( $p['message'] ?? '' ); } } $grade = $personality; } $out = array( 'mode' => $person ? 'personality' : 'score', 'score' => self::num( $score ), 'total' => self::num( $total ), 'percent' => self::num( $percent ), 'grade' => $grade, 'message' => $message, 'personality' => $personality, 'tally' => $tally, 'correct' => $flags, 'items' => $items, ); $out = apply_filters( 'fwren/quiz/result', $out, $form_id, $values ); self::$cache[ $ck ] = $out; return $out; } /** @return int|float Whole numbers without decimals. */ private static function num( $n ) { return floor( $n ) == $n ? (int) $n : round( $n, 2 ); // phpcs:ignore Universal.Operators.StrictComparisons } /** Whether an answer is right. */ private static function is_correct( array $f, array $q, $v ) { if ( ! empty( $f['options'] ) ) { $want = array_values( array_filter( array_map( array( Helpers::class, 'norm' ), (array) ( $q['answers'] ?? array() ) ), 'strlen' ) ); if ( ! $want ) { return false; } $got = array_values( array_filter( array_map( array( Helpers::class, 'norm' ), is_array( $v ) ? $v : array( $v ) ), 'strlen' ) ); if ( ! empty( $f['multiple'] ) ) { sort( $want ); sort( $got ); return $want === $got; } return 1 === count( $got ) && in_array( $got[0], $want, true ); } $accepted = self::accepted( $q ); if ( ! $accepted || is_array( $v ) ) { return false; } $given = trim( (string) $v ); foreach ( $accepted as $a ) { if ( is_numeric( $a ) && is_numeric( $given ) ) { if ( abs( (float) $a - (float) $given ) < 0.000001 ) { return true; } } elseif ( self::lower( $a ) === self::lower( $given ) ) { return true; } } return false; } /** @return string[] Accepted text answers (one per line or separated by |). */ private static function accepted( array $q ) { return array_values( array_filter( array_map( 'trim', preg_split( '/\r?\n|\|/', (string) ( $q['answer_text'] ?? '' ) ) ), 'strlen' ) ); } /** @return string */ private static function lower( $s ) { $s = preg_replace( '/\s+/u', ' ', trim( (string) $s ) ); return function_exists( 'mb_strtolower' ) ? mb_strtolower( $s ) : strtolower( $s ); } /** @return string Correct answer(s) as text. */ private static function expected_text( array $f, array $q ) { if ( ! empty( $f['options'] ) ) { $map = array(); foreach ( $f['options'] as $o ) { $map[ $o['value'] ] = $o['label']; } $out = array(); foreach ( (array) ( $q['answers'] ?? array() ) as $a ) { if ( '' !== (string) $a ) { $out[] = wp_strip_all_tags( $map[ $a ] ?? $a ); } } return implode( ', ', $out ); } return implode( ' / ', self::accepted( $q ) ); } /** Store the result on the entry. */ public static function on_inserted( $entry_id, $values, $form_id ) { $r = self::compute( (int) $form_id, (array) $values ); if ( $r && $entry_id ) { Entries::set_meta( (int) $entry_id, '_quiz', $r ); } } /** @return array|null Result of an entry (stored) or of the values. */ public static function result( $form_id, array $values, array $entry = array() ) { if ( ! empty( $entry['id'] ) ) { $r = Entries::get_meta( (int) $entry['id'], '_quiz' ); if ( is_array( $r ) ) { return $r; } } return self::compute( (int) $form_id, $values ); } /* ------------------------------------------------------------------ * * Output * ------------------------------------------------------------------ */ /** {quiz.*} smartcodes. */ public static function smartcode( $v, $group, $key, $values, $entry, $form_id, $mode = 'html' ) { if ( 'quiz' !== $group ) { return $v; } $r = self::result( (int) $form_id, (array) $values, (array) $entry ); if ( ! $r ) { return ''; } switch ( $key ) { case 'score': case 'total': case 'percent': return (string) $r[ $key ]; case 'grade': case 'personality': return 'html' === $mode ? esc_html( (string) $r[ $key ] ) : (string) $r[ $key ]; case 'message': return 'html' === $mode ? wp_kses_post( (string) $r['message'] ) : wp_strip_all_tags( (string) $r['message'] ); case 'result': return self::table( $r, 'html' === $mode ? 'html' : 'text' ); } return ''; } /** Smartcode picker. */ public static function catalog( $groups ) { $groups[ __( 'Quiz', 'fieldwren' ) ] = array( '{quiz.score}' => __( 'Score', 'fieldwren' ), '{quiz.total}' => __( 'Maximum score', 'fieldwren' ), '{quiz.percent}' => __( 'Percent', 'fieldwren' ), '{quiz.grade}' => __( 'Grade', 'fieldwren' ), '{quiz.message}' => __( 'Grade / personality message', 'fieldwren' ), '{quiz.personality}' => __( 'Personality type', 'fieldwren' ), '{quiz.result}' => __( 'Answers table', 'fieldwren' ), ); return $groups; } /** @return string Answers table (html) or lines (text). */ public static function table( array $r, $mode = 'html' ) { $items = (array) ( $r['items'] ?? array() ); $score = 'personality' !== ( $r['mode'] ?? 'score' ); if ( 'html' !== $mode ) { $lines = array(); foreach ( $items as $i ) { $lines[] = $i['label'] . ': ' . $i['answer'] . ( $score ? ' ' . ( ! empty( $i['correct'] ) ? '✓' : '✗ (' . $i['expect'] . ')' ) : '' ); } return implode( "\n", $lines ); } $td = 'padding:8px 10px;border:1px solid #eef0f3;vertical-align:top;text-align:left'; $h = ''; if ( $score ) { $h .= ''; } $h .= ''; foreach ( $items as $i ) { $ok = ! empty( $i['correct'] ); $h .= ''; if ( $score ) { $h .= ''; } $h .= ''; } return $h . '
' . esc_html__( 'Question', 'fieldwren' ) . '' . esc_html__( 'Your answer', 'fieldwren' ) . '' . esc_html__( 'Correct answer', 'fieldwren' ) . '' . esc_html__( 'Points', 'fieldwren' ) . '
' . esc_html( $i['label'] ) . '' . ( $score ? ( $ok ? '✓ ' : '✗ ' ) : '' ) . esc_html( (string) $i['answer'] ) . '' . esc_html( (string) $i['expect'] ) . '' . esc_html( $i['points'] . '/' . $i['max'] ) . '
'; } /** Result in the confirmation. */ public static function confirmation( $extra, $form_id, $values, $entry ) { $quiz = Form::settings( $form_id )['quiz']; if ( empty( $quiz['enabled'] ) || empty( $quiz['show_result'] ) ) { return $extra; } $r = self::result( (int) $form_id, (array) $values, (array) $entry ); if ( ! $r ) { return $extra; } $ctx = array( 'form_id' => $form_id, 'values' => (array) $values, 'entry' => (array) $entry ); $html = '
'; $html .= wpautop( Smartcodes::parse( (string) $quiz['result_message'], $ctx, 'html' ) ); if ( '' !== (string) $r['grade'] && false === strpos( (string) $quiz['result_message'], '{quiz.grade}' ) ) { $html .= '

' . esc_html( (string) $r['grade'] ) . '

'; } if ( '' !== (string) $r['message'] && false === strpos( (string) $quiz['result_message'], '{quiz.message}' ) ) { $html .= wpautop( wp_kses_post( (string) $r['message'] ) ); } if ( ! empty( $quiz['show_answers'] ) ) { $html .= self::table( $r, 'html' ); } return $extra . $html . '
'; } /* ------------------------------------------------------------------ * * Admin * ------------------------------------------------------------------ */ /** Per-form tab. */ public static function tab( $tabs, $form_id = 0 ) { $tabs['quiz'] = __( 'Quiz', 'fieldwren' ); return $tabs; } /** Tab content. */ public static function render_tab( $form_id, $settings ) { $q = $settings['quiz']; $n = 'fwren[quiz]'; $schema = Schema::get( $form_id ); $saved = array(); foreach ( (array) $q['questions'] as $row ) { if ( ! empty( $row['field'] ) ) { $saved[ (string) $row['field'] ] = $row; } } echo ''; Helpers::row_toggle( $n . '[enabled]', ! empty( $q['enabled'] ), __( 'This form is a quiz', 'fieldwren' ) ); Helpers::row_select( $n . '[mode]', $q['mode'], __( 'Scoring', 'fieldwren' ), array( 'score' => __( 'Points for correct answers', 'fieldwren' ), 'personality' => __( 'Personality type (most picked)', 'fieldwren' ) ) ); Helpers::row_toggle( $n . '[show_result]', ! empty( $q['show_result'] ), __( 'Show the result after submitting', 'fieldwren' ) ); Helpers::row_toggle( $n . '[show_answers]', ! empty( $q['show_answers'] ), __( 'Include the answers table', 'fieldwren' ) ); Helpers::row_textarea( $n . '[result_message]', $q['result_message'], __( 'Result message', 'fieldwren' ), __( 'Smartcodes: {quiz.score}, {quiz.total}, {quiz.percent}, {quiz.grade}, {quiz.message}, {quiz.personality}, {quiz.result}.', 'fieldwren' ), 3 ); echo ''; echo '

' . esc_html__( 'Questions', 'fieldwren' ) . '

'; echo '

' . esc_html__( 'Tick the correct options of choice fields. For text and number fields enter the accepted answers, one per line (case-insensitive). Multiple-choice questions score only when exactly the ticked options are chosen.', 'fieldwren' ) . '

'; echo ''; $i = 0; foreach ( $schema['order'] as $key ) { $f = $schema['fields'][ $key ]; if ( ! in_array( $f['type'], self::TYPES, true ) ) { continue; } $row = $saved[ $key ] ?? array(); $p = $n . '[questions][' . $i . ']'; echo ''; // phpcs:ignore echo ''; $i++; } if ( ! $i ) { echo ''; } echo '
' . esc_html__( 'Use', 'fieldwren' ) . '' . esc_html__( 'Question', 'fieldwren' ) . '' . esc_html__( 'Correct answer(s)', 'fieldwren' ) . '' . esc_html__( 'Points', 'fieldwren' ) . '' . esc_html__( 'Personality per option', 'fieldwren' ) . '
' . Helpers::checkbox( $p . '[enabled]', $row ? Helpers::on( $row['enabled'] ?? '1' ) : false ) . '' . esc_html( Schema::label( $f ) ) . '
' . esc_html( $key ) . '
'; if ( ! empty( $f['options'] ) ) { echo ''; $ans = array_map( array( Helpers::class, 'norm' ), (array) ( $row['answers'] ?? array() ) ); foreach ( $f['options'] as $o ) { echo ''; } } else { echo ''; } echo ''; if ( ! empty( $f['options'] ) ) { $map = array(); foreach ( (array) ( $row['map'] ?? array() ) as $m ) { $map[ Helpers::norm( $m['value'] ?? '' ) ] = (string) ( $m['type'] ?? '' ); } foreach ( $f['options'] as $j => $o ) { echo '
' . esc_html( wp_strip_all_tags( $o['label'] ) ) . ' →
'; } } else { echo '—'; } echo '
' . esc_html__( 'Add choice, text or number fields to the form first.', 'fieldwren' ) . '
'; echo '

' . esc_html__( 'Grading', 'fieldwren' ) . '

' . esc_html__( 'The highest band whose minimum percent is reached wins. Empty rows are ignored.', 'fieldwren' ) . '

'; echo ''; $bands = array_merge( array_values( (array) $q['grading'] ), array( array(), array(), array() ) ); foreach ( $bands as $b => $band ) { $p = $n . '[grading][' . $b . ']'; echo ''; } echo '
' . esc_html__( 'Minimum %', 'fieldwren' ) . '' . esc_html__( 'Grade', 'fieldwren' ) . '' . esc_html__( 'Message', 'fieldwren' ) . '
'; echo '

' . esc_html__( 'Personality types', 'fieldwren' ) . '

' . esc_html__( 'Used in personality mode. The order breaks ties.', 'fieldwren' ) . '

'; echo ''; $types = array_merge( array_values( (array) $q['personalities'] ), array( array(), array() ) ); foreach ( $types as $t => $type ) { $p = $n . '[personalities][' . $t . ']'; echo ''; } echo '
' . esc_html__( 'Type', 'fieldwren' ) . '' . esc_html__( 'Message', 'fieldwren' ) . '
'; } /** Clean and store the posted quiz settings (lists replace, blank rows dropped). */ public static function save_tab( $form_id, $post ) { if ( ! current_user_can( 'fwren_manage_forms' ) ) { return; } $in = Helpers::posted( (array) $post, 'quiz' ); $cur = Form::settings( $form_id )['quiz']; $out = array( 'enabled' => Helpers::on( $in['enabled'] ?? '' ), 'mode' => 'personality' === ( $in['mode'] ?? '' ) ? 'personality' : 'score', 'show_result' => Helpers::on( $in['show_result'] ?? '' ), 'show_answers' => Helpers::on( $in['show_answers'] ?? '' ), 'result_message' => Helpers::html( $in['result_message'] ?? $cur['result_message'] ), 'randomize' => ! empty( $cur['randomize'] ), 'grading' => array(), 'personalities' => array(), 'questions' => array(), ); foreach ( (array) ( $in['grading'] ?? array() ) as $b ) { if ( is_array( $b ) && '' !== trim( (string) ( $b['grade'] ?? '' ) ) ) { $out['grading'][] = array( 'min' => (float) ( $b['min'] ?? 0 ), 'grade' => Helpers::text( $b['grade'] ), 'message' => Helpers::html( $b['message'] ?? '' ) ); } } foreach ( (array) ( $in['personalities'] ?? array() ) as $p ) { if ( is_array( $p ) && '' !== trim( (string) ( $p['type'] ?? '' ) ) ) { $out['personalities'][] = array( 'type' => Helpers::text( $p['type'] ), 'message' => Helpers::html( $p['message'] ?? '' ) ); } } foreach ( (array) ( $in['questions'] ?? array() ) as $q ) { if ( ! is_array( $q ) || empty( $q['field'] ) ) { continue; } $map = array(); foreach ( (array) ( $q['map'] ?? array() ) as $m ) { if ( is_array( $m ) && '' !== trim( (string) ( $m['type'] ?? '' ) ) ) { $map[] = array( 'value' => Helpers::norm( $m['value'] ?? '' ), 'type' => Helpers::text( $m['type'] ) ); } } $out['questions'][] = array( 'field' => sanitize_key( $q['field'] ), 'enabled' => Helpers::on( $q['enabled'] ?? '' ), 'points' => is_numeric( $q['points'] ?? '' ) ? (float) $q['points'] : 1, 'answers' => array_values( array_filter( array_map( array( Helpers::class, 'norm' ), (array) ( $q['answers'] ?? array() ) ), 'strlen' ) ), 'answer_text' => sanitize_textarea_field( (string) ( $q['answer_text'] ?? '' ) ), 'map' => $map, ); } Helpers::save_setting( $form_id, 'quiz', $out ); } /** Score in the entry sidebar. */ public static function entry_sidebar( $entry ) { if ( empty( $entry['id'] ) ) { return; } $r = Entries::get_meta( (int) $entry['id'], '_quiz' ); if ( ! is_array( $r ) ) { return; } echo '

' . esc_html__( 'Quiz result', 'fieldwren' ) . '

'; if ( 'personality' === ( $r['mode'] ?? '' ) ) { echo '

' . esc_html( (string) $r['personality'] ) . '

'; } else { echo '

' . esc_html( $r['score'] . ' / ' . $r['total'] ) . ' (' . esc_html( $r['percent'] ) . '%)

'; if ( '' !== (string) $r['grade'] ) { /* translators: %s grade */ echo '

' . esc_html( sprintf( __( 'Grade: %s', 'fieldwren' ), $r['grade'] ) ) . '

'; } } echo '
' . esc_html__( 'Answers', 'fieldwren' ) . '' . self::table( $r, 'html' ) . '
'; // phpcs:ignore WordPress.Security.EscapeOutput } }